<commit_before>'use strict';

import debug_ from 'debug';

require("babel-polyfill");

import SerialPort from 'serialport';
import {EventEmitter} from 'events';
import sharp from 'sharp';

const NextionEvent = {
  0x00: 'invalidInstruction',
  0x01: 'success',
  0x02: 'invalidComponentID',
  0x03: 'invalidPageID',
  0x04: 'invalidPictureID',
  0x05: 'invalidFontID',
  0x11: 'invalidBaudRate',
  0x12: 'invalidCurveControl',
  0x1a: 'invalidVariableName',
  0x1b: 'invalidVariableOperation',
  0x1c: 'assignmentFailure',
  0x1d: 'eepromFailure',
  0x1e: 'invalidParameterQuantity',
  0x1f: 'ioOperationFailure',
  0x20: 'undefinedEscapeCharacter',
  0x23: 'variableNameTooLong',
  0x70: 'stringData',
  0x71: 'numericData',
  0x65: 'touchEvent',
  0x66: 'pageId',
  0x67: 'touchCoordinate',
  0x68: 'touchCoordinateOnWake',
  0x86: 'autoSleep',
  0x87: 'autoWake',
  0x88: 'startup',
  0x89: 'cardUpgrade',
  0xfd: 'transmitFinished',
  0xfe: 'transmitReady'
}

const debug = debug_('nextion');

export default class NextionService extends EventEmitter{

  _buffer;

  constructor(port) {
    super();

    this._buffer = new Buffer([]);
    this.configPort = port;
  }

  async connect(){

      debug("serialport open");

      let open = false;
      while (open == false) {
        try {
          await new Promise(function(resolve, reject) {
            SerialPort.list((err, ports)=>{
              console.log("list", ports);
              resolve();
            });
          });

          this.port = new SerialPort(this.configPort, {
            autoOpen: false, baudRate:115200});
          await new Promise((resolve, reject) => this.port.open(resolve));
          await new Promise((r)=> setTimeout(r, 1000));
          await this._initScreen();
          open = true;
        } catch (e) {
          await new Promise((r)=> setTimeout(r, 1000));
          console.log("error opening port ", this.configPort, "retry in 2 seconds");
        }
      }

      process.on('SIGINT', () => {
        this.setPage("connection");
        process.exit();
      });
  }

  async setPage(num){
    await this._writeUart('page '+num);
  }

  async setText(cmp, txt){
    let text = txt.toString().split("\r").join('"+"\\r"+"');
    await this._writeUart(cmp+'.txt="'+text+'"');
  }

  async setValue(cmp, txt){
    await this._writeUart(cmp+'.val='+txt+'');
  }

  async addToWaveForm(cmp, channel, value){
    //  console.log(`add ${cmp},${channel},${value.toInt()}`);
    await this._writeUart(`add ${cmp},${channel},${value}`);
  }

  async setVis(cmp, value){
    var val = value ? "1":"0";
    await this._writeUart('vis '+cmp+','+val);
  }

  async setLine(x, y, x2, y2, color){
    await this._writeUart(`line ${x},${y},${x2},${y2},${color}`, false);
  }

  async setFill(x, y, width, height, color){
      await this._writeUart(`fill ${x},${y},${width},${height},${color}`, false);
  }

  async stopRefresh(cmp, bco){
    await this._writeUart("ref_stop");
  }

  async startRefresh(cmp, bco){
    await this._writeUart("ref_star");
  }

  async setColor(cmp, bco){
    await this._writeUart(cmp + ".bco=" + bco);
    await this._writeUart("ref " + cmp);
  }

  async getPage(){
    var page = await this._writeUart('sendme');
    return page[0];
  }

  async getValue(cmp){
    var result = await this._writeUart('get '+cmp, true);
    return result[0];
  }

  async displayBlackWhiteImage(buffer, positionX, positionY, width){
    //debug(url);
    const image = sharp(buffer);

    image.metadata()
      .then((metadata) => {
        image
          .rotate((metadata.width>=metadata.height)?0:90)
          .resize(width)
          .extractChannel(1)
          //.toFile(__dirname+"/../1.min.png");
          .raw()
          .toBuffer(async (err, data, info)=> {
            debug(err);
            debug(data.length);
            debug(data);
            debug(info);

            //debug("fill", info.width, info.height, "0");
            this.setFill(positionX, positionY, info.width, info.height, 0);

            let index = 0;
            let numLine = 0;
            for (let i = 0; i < info.height; i++) {
              //debug("line ", i);
              var x = -1;
              var currentXColor = -1;
              let j = 0;
              for (j = 0; j < info.width; j++) {
                var currentColor = data[index] <= 50 ? 0 : 1;
                //debug(data[index]);
                if (j == 0) {
                  currentXColor = currentColor;
                } else if (currentColor != currentXColor) {
                  if (currentXColor == 1) {
                    this.setLine(x + positionX, i + positionY, j - 1 + positionX, i + positionY, 0xFFFFFF);
                    debug("setLine", ++numLine, "y", i, "from", x, "to", j - 1, "color", currentXColor);
                  }
                  x = j - 1;
                  currentXColor = currentColor;
                }
                index++;
              }
              if (x == 0 && currentXColor != 0) {
                this.setLine(x+positionX, i+positionY, j-1+positionX, i+positionY, 0xFFFFFF);
                debug("setLine", ++numLine, "y", i, "from", x, "to", j - 1, "color", currentXColor);
              }
            }
          debug("time = ", new Date().getTime() - date);
      });
    });
  }

  //private

  async _initScreen(){
    //await new Promise((resolve) => setTimeout(resolve, 1000));
    this.port.on("close", ()=>{
      this.emit("disconnect");
    });

    this.port.on('data', (byte) => {
      this._buffer = Buffer.concat([this._buffer, byte]);
      this._readBuffer();
    });

    this._writeUart('sleep=0');

    await this._writeUart('bkcmd=3');

    //await this._writeUart('bauds=115200');

    debug("screenInitialized");
  }

  _readBuffer(){
    let index = this._buffer.indexOf(delimiterBuffer);
    if (index>=0) {
      let result = this._parseData(this._buffer.slice(0, index));
      this.emit("data", result);
      debug("event", NextionEvent[result.event], ":", result.event.toString(16), result.data);
      switch (NextionEvent[result.event]) {
        case "touchEvent":
          debug("emit : ", "click_b"+result.data[1].toString());
          this.emit("click_b"+result.data[1].toString());
          break;

        case "numericData":
          debug("emit : ", "number");
          this.emit("number", result.data[0]);
          break;

        case "stringData":
          debug("emit : ", "string", result.data.toString());
          this.emit("string", result.data.toString());
          break;

        default:
          this.emit(NextionEvent[result.event], result.data);
      }

      this._buffer = this._buffer.slice(index+3);
      this._readBuffer();
    }
  }

  _parseData(buffer){
    let result = {};
    result.event = buffer[0];
    result.data = buffer.slice(1);
    return result;
  }

  async _writeUart(cmd, wait = true){
    debug("send command : "+cmd);
    this.port.write(this.hex(cmd));
    if(wait)
      return await this._waitForResult();
  }

  async _waitForResult(){
    return await new Promise((resolve, reject) => {
      this.once("data", (data)=>{
        debug("receiveResult", data);
        if(NextionEvent[data.event] !== null){
          return resolve(data.data);
        }

        return reject(data.data);
      })
    });

  }

  hex(str) {
    var arr = [];
    for (var i = 0, l = str.length; i < l; i ++) {
      var ascii = str.charCodeAt(i);
      arr.push(ascii);
    }
    arr.push(255);
    arr.push(255);
    arr.push(255);
    return new Buffer(arr);
  }
}

export const delimiter = [
  0xff,
  0xff,
  0xff
];

export const delimiterBuffer = Buffer.from(delimiter);
<commit_msg>Fixed getValue() math error<commit_after>'use strict';

import debug_ from 'debug';

require("babel-polyfill");

import SerialPort from 'serialport';
import {EventEmitter} from 'events';
import sharp from 'sharp';

const NextionEvent = {
  0x00: 'invalidInstruction',
  0x01: 'success',
  0x02: 'invalidComponentID',
  0x03: 'invalidPageID',
  0x04: 'invalidPictureID',
  0x05: 'invalidFontID',
  0x11: 'invalidBaudRate',
  0x12: 'invalidCurveControl',
  0x1a: 'invalidVariableName',
  0x1b: 'invalidVariableOperation',
  0x1c: 'assignmentFailure',
  0x1d: 'eepromFailure',
  0x1e: 'invalidParameterQuantity',
  0x1f: 'ioOperationFailure',
  0x20: 'undefinedEscapeCharacter',
  0x23: 'variableNameTooLong',
  0x70: 'stringData',
  0x71: 'numericData',
  0x65: 'touchEvent',
  0x66: 'pageId',
  0x67: 'touchCoordinate',
  0x68: 'touchCoordinateOnWake',
  0x86: 'autoSleep',
  0x87: 'autoWake',
  0x88: 'startup',
  0x89: 'cardUpgrade',
  0xfd: 'transmitFinished',
  0xfe: 'transmitReady'
}

const debug = debug_('nextion');

export default class NextionService extends EventEmitter{

  _buffer;

  constructor(port) {
    super();

    this._buffer = new Buffer([]);
    this.configPort = port;
  }

  async connect(){

      debug("serialport open");

      let open = false;
      while (open == false) {
        try {
          await new Promise(function(resolve, reject) {
            SerialPort.list((err, ports)=>{
              console.log("list", ports);
              resolve();
            });
          });

          this.port = new SerialPort(this.configPort, {
            autoOpen: false, baudRate:115200});
          await new Promise((resolve, reject) => this.port.open(resolve));
          await new Promise((r)=> setTimeout(r, 1000));
          await this._initScreen();
          open = true;
        } catch (e) {
          await new Promise((r)=> setTimeout(r, 1000));
          console.log("error opening port ", this.configPort, "retry in 2 seconds");
        }
      }

      process.on('SIGINT', () => {
        this.setPage("connection");
        process.exit();
      });
  }

  async setPage(num){
    await this._writeUart('page '+num);
  }

  async setText(cmp, txt){
    let text = txt.toString().split("\r").join('"+"\\r"+"');
    await this._writeUart(cmp+'.txt="'+text+'"');
  }

  async setValue(cmp, txt){
    await this._writeUart(cmp+'.val='+txt+'');
  }

  async addToWaveForm(cmp, channel, value){
    //  console.log(`add ${cmp},${channel},${value.toInt()}`);
    await this._writeUart(`add ${cmp},${channel},${value}`);
  }

  async setVis(cmp, value){
    var val = value ? "1":"0";
    await this._writeUart('vis '+cmp+','+val);
  }

  async setLine(x, y, x2, y2, color){
    await this._writeUart(`line ${x},${y},${x2},${y2},${color}`, false);
  }

  async setFill(x, y, width, height, color){
      await this._writeUart(`fill ${x},${y},${width},${height},${color}`, false);
  }

  async stopRefresh(cmp, bco){
    await this._writeUart("ref_stop");
  }

  async startRefresh(cmp, bco){
    await this._writeUart("ref_star");
  }

  async setColor(cmp, bco){
    await this._writeUart(cmp + ".bco=" + bco);
    await this._writeUart("ref " + cmp);
  }

  async getPage(){
    var page = await this._writeUart('sendme');
    return page[0];
  }

  async getValue(cmp){
    var result = await this._writeUart('get '+cmp, true);
    return (result[1]*256+result[0]);
  }

  async displayBlackWhiteImage(buffer, positionX, positionY, width){
    //debug(url);
    const image = sharp(buffer);

    image.metadata()
      .then((metadata) => {
        image
          .rotate((metadata.width>=metadata.height)?0:90)
          .resize(width)
          .extractChannel(1)
          //.toFile(__dirname+"/../1.min.png");
          .raw()
          .toBuffer(async (err, data, info)=> {
            debug(err);
            debug(data.length);
            debug(data);
            debug(info);

            //debug("fill", info.width, info.height, "0");
            this.setFill(positionX, positionY, info.width, info.height, 0);

            let index = 0;
            let numLine = 0;
            for (let i = 0; i < info.height; i++) {
              //debug("line ", i);
              var x = -1;
              var currentXColor = -1;
              let j = 0;
              for (j = 0; j < info.width; j++) {
                var currentColor = data[index] <= 50 ? 0 : 1;
                //debug(data[index]);
                if (j == 0) {
                  currentXColor = currentColor;
                } else if (currentColor != currentXColor) {
                  if (currentXColor == 1) {
                    this.setLine(x + positionX, i + positionY, j - 1 + positionX, i + positionY, 0xFFFFFF);
                    debug("setLine", ++numLine, "y", i, "from", x, "to", j - 1, "color", currentXColor);
                  }
                  x = j - 1;
                  currentXColor = currentColor;
                }
                index++;
              }
              if (x == 0 && currentXColor != 0) {
                this.setLine(x+positionX, i+positionY, j-1+positionX, i+positionY, 0xFFFFFF);
                debug("setLine", ++numLine, "y", i, "from", x, "to", j - 1, "color", currentXColor);
              }
            }
          debug("time = ", new Date().getTime() - date);
      });
    });
  }

  //private

  async _initScreen(){
    //await new Promise((resolve) => setTimeout(resolve, 1000));
    this.port.on("close", ()=>{
      this.emit("disconnect");
    });

    this.port.on('data', (byte) => {
      this._buffer = Buffer.concat([this._buffer, byte]);
      this._readBuffer();
    });

    this._writeUart('sleep=0');

    await this._writeUart('bkcmd=3');

    //await this._writeUart('bauds=115200');

    debug("screenInitialized");
  }

  _readBuffer(){
    let index = this._buffer.indexOf(delimiterBuffer);
    if (index>=0) {
      let result = this._parseData(this._buffer.slice(0, index));
      this.emit("data", result);
      debug("event", NextionEvent[result.event], ":", result.event.toString(16), result.data);
      switch (NextionEvent[result.event]) {
        case "touchEvent":
          debug("emit : ", "click_b"+result.data[1].toString());
          this.emit("click_b"+result.data[1].toString());
          break;

        case "numericData":
          debug("emit : ", "number");
          this.emit("number", result.data[0]);
          break;

        case "stringData":
          debug("emit : ", "string", result.data.toString());
          this.emit("string", result.data.toString());
          break;

        default:
          this.emit(NextionEvent[result.event], result.data);
      }

      this._buffer = this._buffer.slice(index+3);
      this._readBuffer();
    }
  }

  _parseData(buffer){
    let result = {};
    result.event = buffer[0];
    result.data = buffer.slice(1);
    return result;
  }

  async _writeUart(cmd, wait = true){
    debug("send command : "+cmd);
    this.port.write(this.hex(cmd));
    if(wait)
      return await this._waitForResult();
  }

  async _waitForResult(){
    return await new Promise((resolve, reject) => {
      this.once("data", (data)=>{
        debug("receiveResult", data);
        if(NextionEvent[data.event] !== null){
          return resolve(data.data);
        }

        return reject(data.data);
      })
    });

  }

  hex(str) {
    var arr = [];
    for (var i = 0, l = str.length; i < l; i ++) {
      var ascii = str.charCodeAt(i);
      arr.push(ascii);
    }
    arr.push(255);
    arr.push(255);
    arr.push(255);
    return new Buffer(arr);
  }
}

export const delimiter = [
  0xff,
  0xff,
  0xff
];

export const delimiterBuffer = Buffer.from(delimiter);
<|endoftext|>


<commit_before>define([
	'app',
	'appHelpers',

	'bookingsCollection',
	'bookingModel',

	'genericListView',
	'paginationView',
	'itemBookingView',
	'toolbarButtonsView'

], function(app, AppHelpers, BookingsCollection, BookingModel, GenericListView, PaginationView, ItemBookingView, ToolbarButtonsView){

	'use strict';

	/******************************************
	* Bookings List View
	*/
	var bookingsListView = GenericListView.extend({

		templateHTML : '/templates/lists/bookingsList.html',

		//overrides url GenericListView's url parameters to add 'recurrence parameter'
		urlParameters: ['recurrence', 'id', 'search', 'filter', 'sort', 'page'],

		// The DOM events //
		events: function(){
			return _.defaults({
				'click #filterStateBookingList li a' 	: 'setFilterState',
				'click #badgeActions[data-filter!=""]'  : 'badgeFilter',
			},
				GenericListView.prototype.events
			);
		},

		/** View Initialization
		*/
		initialize : function(params) {
			var self = this;

			this.options = params;

			this.initCollections().done(
				function(){
					app.router.render(self);
					// Unbind & bind the collection //
					self.collection.off();
					self.listenTo(self.collection, 'add',self.add);
				}
			);
		},

		add: function(model){
			//TODO : add item after new booking created
		},

		/** Partial Render of the view : refresh toolbar buttons
		*/
		partialRender: function(model){
			var self = this;
			if(! _.isNull(model) && !_.isUndefined(model) ) {
				if( model.getRecurrence('id')!= false )
					app.views.toolbarButtonsView.initialize( { collection: this.collection } );
			}
			this.collection.specialCount().done(function(){
				$('#badgeActions').html(self.collection.specialCpt);
				app.views.paginationView.render();
			});
		},

		/** Display the view
		*/
		render : function() {
			var self = this;

			// Change the page title //
			app.router.setPageTitle(app.lang.resa.viewsTitles.bookingsList);

			// Retrieve the HTML template //
			$.get(app.menus.openresa + this.templateHTML, function(templateData){
				var template = _.template(templateData, {
					lang             : app.lang,
					bookings         : self.collection,
					nbBookings       : self.collection.specialCpt,
					BookingModel	 : BookingModel,
					bookingsState    : BookingModel.status,
				});

				$(self.el).html(template);

				// Call the render Generic View //
				GenericListView.prototype.render(self.options);

				// Create item booking view //
				_.each(self.collection.models, function(booking, i){
					var itemView = new ItemBookingView( {model: booking} );
					$('#booking-items').append(itemView.render().el);
				});

				// Render Filter Link on the Table //
				if(!_.isUndefined(self.options.filter)){

					$('#filterStateBooking').removeClass('filter-disabled');
					$('#filterStateBookingList li.delete-filter').removeClass('disabled');

					$('a.filter-button').addClass('text-'+BookingModel.status[self.options.filter.value].color);
				}
				else{
					$('#filterStateBooking').addClass('filter-disabled');
					$('#filterStateBookingList li.delete-filter').addClass('disabled');
				}

				//Toolbar buttons : factory actions for multiple bookings ( confirm/cancel:close booking)
				app.views.toolbarButtonsView = new ToolbarButtonsView( { collection: self.collection } );

				// Pagination view //
				app.views.paginationView = new PaginationView({
					page       : self.options.page.page,
					collection : self.collection
				})

			});
			$(this.el).hide().fadeIn();
			return this;
		},

		/** Filter Requests on the State
			*/
		setFilterState: function(e){
			e.preventDefault();

			if($(e.target).is('i')){
				var filterValue = _($(e.target).parent().attr('href')).strRightBack('#');
			}else{
				var filterValue = _($(e.target).attr('href')).strRightBack('#');
			}

			// Set the filter value in the options of the view //
			if(filterValue != 'delete-filter'){
				this.options.filter = { by: 'state', value: filterValue};
				delete this.options.page;
			}
			else{
				delete this.options.filter;
			}

			app.router.navigate(this.urlBuilder(), {trigger: true, replace: true});
		},

		/** Filter Requests on the State of the Badge
		 	*/
		badgeFilter: function(e){
		 	e.preventDefault();
		 	delete this.options.recurrence

			var filterValue = $(e.target).data('filter');

			// Set the filter value in the options of the view //
			if(filterValue != ''){
				this.options.filter = { by: 'state', value: filterValue};
				delete this.options.search;
				delete this.options.page;
			}

			app.router.navigate(this.urlBuilder(), {trigger: true, replace: true});
		},

		/**
		 * Init reservation collection with url params
		 */
		initCollections: function(){
			var self = this;

			// Check if the collections are instantiated //
			if(_.isUndefined(this.collection)){ this.collection = new BookingsCollection(); }
			else{this.collection.reset();}

			this.options.page = AppHelpers.calculPageOffset(this.options.page);

			if(!_.isUndefined(this.options.filter)){
				this.options.filter = AppHelpers.calculPageFilter(this.options.filter);
			}

			if(_.isUndefined(this.options.sort)){
				this.options.sort = this.collection.default_sort;
			}
			else{
				this.options.sort = AppHelpers.calculPageSort(this.options.sort);
			}

			// Create Fetch params //
			this.fetchParams = {
				silent     : true,
				data       : {
					limit  : app.config.itemsPerPage,
					offset : this.options.page.offset,
					sort   : this.options.sort.by+' '+this.options.sort.order,
				}
			};

			if(_.isUndefined(this.fetchParams.data.filters))
				this.fetchParams.data.filters = new Object();

			var globalSearch = {};

			if(!_.isUndefined(this.options.search)){
				globalSearch.search = this.options.search;
			}
			if(!_.isUndefined(this.options.filter)){
				globalSearch.filter = this.options.filter;
			}

			if(!_.isEmpty(globalSearch)){
				this.fetchParams.data.filters = AppHelpers.calculSearch(globalSearch, BookingModel.prototype.searchable_fields);
			}

			//Add filter on recurrence selected
			if(!_.isUndefined(this.options.recurrence)){
				this.fetchParams.data.filters  = _.toArray(this.fetchParams.data.filters);
				this.fetchParams.data.filters.push({field: 'recurrence_id.id', operator:'=', value:this.options.recurrence})
				this.fetchParams.data.filters = app.objectifyFilters(this.fetchParams.data.filters)
			}

			var ajaxRequests = [this.collection.fetch(this.fetchParams)]

			var deferred = $.Deferred();
			$.when.apply( $, ajaxRequests )
				.done(function(){
					deferred.resolve();
				})
				.fail(function(e){
					console.error(e);
				})

			return deferred;
		}
	});

	return bookingsListView;
});<commit_msg>bugfixe: #2479, added domain on BookingList if user is not manager<commit_after>define([
	'app',
	'appHelpers',

	'bookingsCollection',
	'bookingModel',

	'genericListView',
	'paginationView',
	'itemBookingView',
	'toolbarButtonsView'

], function(app, AppHelpers, BookingsCollection, BookingModel, GenericListView, PaginationView, ItemBookingView, ToolbarButtonsView){

	'use strict';

	/******************************************
	* Bookings List View
	*/
	var bookingsListView = GenericListView.extend({

		templateHTML : '/templates/lists/bookingsList.html',

		//overrides url GenericListView's url parameters to add 'recurrence parameter'
		urlParameters: ['recurrence', 'id', 'search', 'filter', 'sort', 'page'],

		// The DOM events //
		events: function(){
			return _.defaults({
				'click #filterStateBookingList li a' 	: 'setFilterState',
				'click #badgeActions[data-filter!=""]'  : 'badgeFilter',
			},
				GenericListView.prototype.events
			);
		},

		/** View Initialization
		*/
		initialize : function(params) {
			var self = this;

			this.options = params;

			this.initCollections().done(
				function(){
					app.router.render(self);
					// Unbind & bind the collection //
					self.collection.off();
					self.listenTo(self.collection, 'add',self.add);
				}
			);
		},

		add: function(model){
			//TODO : add item after new booking created
		},

		/** Partial Render of the view : refresh toolbar buttons
		*/
		partialRender: function(model){
			var self = this;
			if(! _.isNull(model) && !_.isUndefined(model) ) {
				if( model.getRecurrence('id')!= false )
					app.views.toolbarButtonsView.initialize( { collection: this.collection } );
			}
			this.collection.specialCount().done(function(){
				$('#badgeActions').html(self.collection.specialCpt);
				app.views.paginationView.render();
			});
		},

		/** Display the view
		*/
		render : function() {
			var self = this;

			// Change the page title //
			app.router.setPageTitle(app.lang.resa.viewsTitles.bookingsList);

			// Retrieve the HTML template //
			$.get(app.menus.openresa + this.templateHTML, function(templateData){
				var template = _.template(templateData, {
					lang             : app.lang,
					bookings         : self.collection,
					nbBookings       : self.collection.specialCpt,
					BookingModel	 : BookingModel,
					bookingsState    : BookingModel.status,
				});

				$(self.el).html(template);

				// Call the render Generic View //
				GenericListView.prototype.render(self.options);

				// Create item booking view //
				_.each(self.collection.models, function(booking, i){
					var itemView = new ItemBookingView( {model: booking} );
					$('#booking-items').append(itemView.render().el);
				});

				// Render Filter Link on the Table //
				if(!_.isUndefined(self.options.filter)){

					$('#filterStateBooking').removeClass('filter-disabled');
					$('#filterStateBookingList li.delete-filter').removeClass('disabled');

					$('a.filter-button').addClass('text-'+BookingModel.status[self.options.filter.value].color);
				}
				else{
					$('#filterStateBooking').addClass('filter-disabled');
					$('#filterStateBookingList li.delete-filter').addClass('disabled');
				}

				//Toolbar buttons : factory actions for multiple bookings ( confirm/cancel:close booking)
				app.views.toolbarButtonsView = new ToolbarButtonsView( { collection: self.collection } );

				// Pagination view //
				app.views.paginationView = new PaginationView({
					page       : self.options.page.page,
					collection : self.collection
				})

			});
			$(this.el).hide().fadeIn();
			return this;
		},

		/** Filter Requests on the State
			*/
		setFilterState: function(e){
			e.preventDefault();

			if($(e.target).is('i')){
				var filterValue = _($(e.target).parent().attr('href')).strRightBack('#');
			}else{
				var filterValue = _($(e.target).attr('href')).strRightBack('#');
			}

			// Set the filter value in the options of the view //
			if(filterValue != 'delete-filter'){
				this.options.filter = { by: 'state', value: filterValue};
				delete this.options.page;
			}
			else{
				delete this.options.filter;
			}

			app.router.navigate(this.urlBuilder(), {trigger: true, replace: true});
		},

		/** Filter Requests on the State of the Badge
		 	*/
		badgeFilter: function(e){
		 	e.preventDefault();
		 	delete this.options.recurrence

			var filterValue = $(e.target).data('filter');

			// Set the filter value in the options of the view //
			if(filterValue != ''){
				this.options.filter = { by: 'state', value: filterValue};
				delete this.options.search;
				delete this.options.page;
			}

			app.router.navigate(this.urlBuilder(), {trigger: true, replace: true});
		},

		/**
		 * Init reservation collection with url params
		 */
		initCollections: function(){
			var self = this;

			// Check if the collections are instantiated //
			if(_.isUndefined(this.collection)){ this.collection = new BookingsCollection(); }
			else{this.collection.reset();}

			this.options.page = AppHelpers.calculPageOffset(this.options.page);

			if(!_.isUndefined(this.options.filter)){
				this.options.filter = AppHelpers.calculPageFilter(this.options.filter);
			}

			if(_.isUndefined(this.options.sort)){
				this.options.sort = this.collection.default_sort;
			}
			else{
				this.options.sort = AppHelpers.calculPageSort(this.options.sort);
			}

			// Create Fetch params //
			this.fetchParams = {
				silent     : true,
				data       : {
					limit  : app.config.itemsPerPage,
					offset : this.options.page.offset,
					sort   : this.options.sort.by+' '+this.options.sort.order,
				}
			};

			if(_.isUndefined(this.fetchParams.data.filters))
				this.fetchParams.data.filters = new Object();

			var globalSearch = {};

			if(!_.isUndefined(this.options.search)){
				globalSearch.search = this.options.search;
			}
			if(!_.isUndefined(this.options.filter)){
				globalSearch.filter = this.options.filter;
			}

			if(!_.isEmpty(globalSearch)){
				this.fetchParams.data.filters = AppHelpers.calculSearch(globalSearch, BookingModel.prototype.searchable_fields);
			}

			//add filter for claimer to fetch only their own bookings
			if(!app.current_user.isResaManager()){
				this.fetchParams.data.filters  = _.toArray(this.fetchParams.data.filters);
				this.fetchParams.data.filters.push({field: 'partner_id.address.id', operator:'in', value:app.current_user.get('contact_id')});
				this.fetchParams.data.filters = app.objectifyFilters(this.fetchParams.data.filters);
			}

			//Add filter on recurrence selected
			if(!_.isUndefined(this.options.recurrence)){
				this.fetchParams.data.filters  = _.toArray(this.fetchParams.data.filters);
				this.fetchParams.data.filters.push({field: 'recurrence_id.id', operator:'=', value:this.options.recurrence})
				this.fetchParams.data.filters = app.objectifyFilters(this.fetchParams.data.filters)
			}

			var ajaxRequests = [this.collection.fetch(this.fetchParams)]

			var deferred = $.Deferred();
			$.when.apply( $, ajaxRequests )
				.done(function(){
					deferred.resolve();
				})
				.fail(function(e){
					console.error(e);
				})

			return deferred;
		}
	});

	return bookingsListView;
});<|endoftext|>


<commit_before>(function(){
    window.pengine = window.pengine||{};
    window.pengine.mapBuilder = function(){
        var blockMap;
        var gameMap;

        /**
         *
         * @param blockMapURL
         * @param scene
         */
        function buildBlockMap(blockMapURL, scene){
            $.getJSON(blockMapURL, function(data){
                blockMap = data;
                pengine.sceneBuilder.drawBoxes(blockMap.arrayMap, scene);
            });
        }

        /**
         *
         * @param gameMapURL
         * @param scene
         * @param layer
         */
        function buildGameMap(gameMapURL, scene, layer){
            $.getJSON(gameMapURL, function(data){
                gameMap = data;
                pengine.sceneBuilder.drawEntities(gameMap.arrayMap, scene, blockMap.arrayMap);
            });
        }

        /**
         *
         */
        function exportToJSON(){
            $("#txt2").val(JSON.stringify(blockMap));
            console.log(JSON.stringify(blockMap));
        }

        /**
         *
         */
        function exportGameToJSON(){
            $("#txt2").val(JSON.stringify(gameMap));
            console.log(JSON.stringify(gameMap));
        }

        /**
         *
         * @param scene
         */
        function addBlockArrayX(scene){
            var lx = blockMap.arrayMap[0].length;
            blockMap.arrayMap.forEach(function(arrX, index){
                arrX.push({});
                pengine.sceneBuilder.addPlaneGround(index, lx, scene, "water");
            });
        }

        /**
         *
         * @param scene
         */
        function addBlockArrayZ(scene){
            var yL = blockMap.arrayMap[0].length;
            var newArr = [];
            for(var i = 0; i < yL; i++){
                newArr.push({type:"water",height:0});

            }
            blockMap.arrayMap.push(newArr);
            newArr.forEach(function(arrY,index){
                var lX = blockMap.arrayMap.length;
                var lY = blockMap.arrayMap[0].length;
                pengine.sceneBuilder.addPlaneGround( lX-1, index , scene, "water");
            });

        }

        /**
         *
         * @param scene
         * @constructor
         */
        function AddXZ(scene){
            addBlockArrayX(scene);
            addBlockArrayZ(scene);
        }

        /**
         *
         * @param x
         * @param z
         * @return {Boolean}
         */
        function isWater(x,z){
            if(blockMap.arrayMap[x][z].type === "water")
            return true;
        }

        /**
         *
         * @param x
         * @param z
         * @return {Boolean}
         */
        function isPlane(x,z){
            return true;
        }

        /**
         *
         * @param x
         * @param z
         * @return {*}
         */
        function getType(x,z){
            return blockMap.arrayMap[x][z].type;
        }

        /**
         *
         * @param x
         * @param z
         * @param h
         * @param mesh
         */
        function setHeight(x,z,h, mesh, scene){
            blockMap.arrayMap[x][z] = {type:"earth", height:h};
            pengine.sceneBuilder.setHeight(x,z,h,mesh, scene);
        }

        /**
         * Convert a block object to a position on the map array
         * @param {object} intersectObject
         * @return {array}
         */
        function getMapPosition(intersectObject){
            if(intersectObject){
                var bm = new Array(3);
                var px = intersectObject.position.x;
                var pz = intersectObject.position.pz;
                var height = intersectObject.geometry.height;

                var bmX = intersectObject.position.x/200;
                var bmZ = intersectObject.position.z/200;

                return   [bmX,bmZ] ;
            }else{
                return  null;
            }
        }

        return {
            buildBlockMap:buildBlockMap,
            buildGameMap:buildGameMap,
            exportToJSON:exportToJSON,
            exportGameToJSON:exportGameToJSON,
            AddXZ:AddXZ,
            isWater:isWater,
            isPlane:isPlane,
            getType:getType,
            setHeight:setHeight,
            getMapPosition:getMapPosition
        };
    }();
})();
<commit_msg>refactor<commit_after>(function(){
    "use strict";
    window.pengine = window.pengine||{};
    window.pengine.mapBuilder = function(){
        var blockMap;
        var gameMap;

        /**
         *
         * @param blockMapURL
         * @param scene
         */
        function buildBlockMap(blockMapURL, scene){
            $.getJSON(blockMapURL, function(data){
                blockMap = data;
                pengine.sceneBuilder.drawBoxes(blockMap.arrayMap, scene);
            });
        }

        /**
         *
         * @param gameMapURL
         * @param scene
         * @param layer
         */
        function buildGameMap(gameMapURL, scene, layer){
            $.getJSON(gameMapURL, function(data){
                gameMap = data;
                pengine.sceneBuilder.drawEntities(gameMap.arrayMap, scene, blockMap.arrayMap);
            });
        }

        /**
         *
         */
        function exportToJSON(){
            $("#txt2").val(JSON.stringify(blockMap));
            console.log(JSON.stringify(blockMap));
        }

        /**
         *
         */
        function exportGameToJSON(){
            $("#txt2").val(JSON.stringify(gameMap));
            console.log(JSON.stringify(gameMap));
        }

        /**
         *
         * @param scene
         */
        function addBlockArrayX(scene){
            var lx = blockMap.arrayMap[0].length;
            blockMap.arrayMap.forEach(function(arrX, index){
                arrX.push({});
                pengine.sceneBuilder.addPlaneGround(index, lx, scene, "water");
            });
        }

        /**
         *
         * @param scene
         */
        function addBlockArrayZ(scene){
            var yL = blockMap.arrayMap[0].length;
            var newArr = [];
            for(var i = 0; i < yL; i++){
                newArr.push({type:"water",height:0});

            }
            blockMap.arrayMap.push(newArr);
            newArr.forEach(function(arrY,index){
                var lX = blockMap.arrayMap.length;
                var lY = blockMap.arrayMap[0].length;
                pengine.sceneBuilder.addPlaneGround( lX-1, index , scene, "water");
            });

        }

        /**
         *
         * @param scene
         * @constructor
         */
        function AddXZ(scene){
            addBlockArrayX(scene);
            addBlockArrayZ(scene);
        }

        /**
         *
         * @param x
         * @param z
         * @return {Boolean}
         */
        function isWater(x,z){
            if(blockMap.arrayMap[x][z].type === "water")
            return true;
        }

        /**
         *
         * @param x
         * @param z
         * @return {Boolean}
         */
        function isPlane(x,z){
            return true;
        }

        /**
         *
         * @param x
         * @param z
         * @return {*}
         */
        function getType(x,z){
            return blockMap.arrayMap[x][z].type;
        }

        /**
         *
         * @param x
         * @param z
         * @param h
         * @param mesh
         */
        function setHeight(x,z,h, mesh, scene){
            blockMap.arrayMap[x][z] = {type:"earth", height:h};
            pengine.sceneBuilder.setHeight(x,z,h,mesh, scene);
        }

        /**
         * Convert a block object to a position on the map array
         * @param {object} intersectObject
         * @return {array}
         */
        function getMapPosition(intersectObject){
            if(intersectObject){
                var bm = new Array(3);
                var px = intersectObject.position.x;
                var pz = intersectObject.position.pz;
                var height = intersectObject.geometry.height;

                var bmX = intersectObject.position.x/200;
                var bmZ = intersectObject.position.z/200;

                return   [bmX,bmZ] ;
            }else{
                return  null;
            }
        }

        return {
            buildBlockMap:buildBlockMap,
            buildGameMap:buildGameMap,
            exportToJSON:exportToJSON,
            exportGameToJSON:exportGameToJSON,
            AddXZ:AddXZ,
            isWater:isWater,
            isPlane:isPlane,
            getType:getType,
            setHeight:setHeight,
            getMapPosition:getMapPosition
        };
    }();
})();
<|endoftext|>


<commit_before>// knockout-sortable 0.10.0 | (c) 2015 Ryan Niemeyer |  http://www.opensource.org/licenses/mit-license
;(function(factory) {
    if (typeof define === "function" && define.amd) {
        // AMD anonymous module
        define(["knockout", "jquery", "jquery.ui/sortable"], factory);
    } else if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
        // CommonJS module
        var ko = require("knockout"),
            jQuery = require("jquery");
        require("jquery.ui/sortable");
        factory(ko, jQuery);
    } else {
        // No module loader (plain


<commit_before>(function() {
	/* jshint node: true */
	var
		fs = require("fs"),
		path = require("path"),
		walker = require("walker"),
		uglify = require("uglify-js"),
		nopt = require("nopt"),
		less = require("less");

	var basename = path.basename(__filename),
		w = console.log,
		e = console.error,
		opt;

	// Shimming path.relative with 0.8.8's version if it doesn't exist
	if(!path.relative){
		path.relative = require('./path-relative-shim').relative;
	}

	function printUsage() {
		w("Enyo 2.0 Minifier");
		w("Usage: " + __filename + " [Flags] [path/to/package.js]");
		w("Flags:");
		w("-no-less:", "Don't compile less; instad substitute css for less");
		w("-no-alias:", "Don't use path macros");
		w("-alias:", "Give paths a macroized alias");
		w("-enyo ENYOPATH:", "Relative path to enyo folder (enyo)");
		w("-lib LIBPATH:", "Relative path to lib folder ($enyo/../lib)");
		w("-destdir DESTDIR:", "Target directory, prepended to any output file but skipped within generated files (current dir)");
		w("-output RELPATH/PREFIX:", "Folder + output file prefix, relative to DESTDIR (build/out)");
		w("-beautify:", "Output pretty version that's less compressed but has code on separate lines");
		w("-f", "Remote source mapping: from local path");
		w("-t", "Remote source mapping: to remote path");
		w("-h, -?, -help:", "Show this message");
	}

	// properly split path based on platform
	function pathSplit(inPath) {
		var sep = process.platform == "win32" ? "\\" : "/";
		return inPath.split(sep);
	}

	function concatCss(sheets, doneCB) {
		w("");
		var blob = "";
		var addToBlob = function(sheet, code) {
			// fix url paths
			code = code.replace(/url\([^)]*\)/g, function(inMatch) {
				// find the url path, ignore quotes in url string
				var matches = /url\s*\(\s*(('([^']*)')|("([^"]*)")|([^'"]*))\s*\)/.exec(inMatch);
				var urlPath = matches[3] || matches[5] || matches[6];
				// skip data urls
				if (/^data:/.test(urlPath)) {
					return "url(" + urlPath + ")";
				}
				// skip an external link
				if (/^http(:?s)?:/.test(urlPath)) {
					return "url(" + urlPath + ")";
				}
				// get absolute path to referenced asset
				var normalizedUrlPath = path.join(sheet, "..", urlPath);
				// Make relative asset path to built css
				var relPath = path.relative(path.dirname(opt.output), normalizedUrlPath);
				if (process.platform == "win32") {
					relPath = pathSplit(relPath).join("/");
				}
				return "url(" + relPath + ")";
			});
			blob += "\n/* " + path.relative(process.cwd(), sheet) + " */\n\n" + code + "\n";
		};
		// Pops one sheet off the sheets[] array, reads (and parses if less), and then
		// recurses again from the async callback until no sheets left, then calls doneCB
		function readAndParse() {
			var sheet = sheets.shift();
			if (sheet) {
				w(sheet);
				var isLess = (sheet.slice(-4) == "less");
				if (isLess && (opt.less !== true)) {
					sheet = sheet.slice(0, sheet.length-4) + "css";
					isLess = false;
					w(" (Substituting CSS: " + sheet + ")");
				}
				var code = fs.readFileSync(sheet, "utf8");
				if (isLess) {
					var parser = new(less.Parser)({filename:sheet, paths:[path.dirname(sheet)]});
					parser.parse(code, function (err, tree) {
						if (err) {
							console.error(err);
						} else {
							addToBlob(sheet, tree.toCSS());
						}
						readAndParse(sheets);
					});
				} else {
					addToBlob(sheet, code);
					readAndParse(sheets);
				}
			} else {
				doneCB(blob);
			}
		}
		readAndParse();
	}

	var concatJs = function(loader, scripts) {
		w("");
		var blob = "";
		for (var i=0, script; (script=scripts[i]); i++) {
			w(script);
			blob += "\n// " + path.relative(process.cwd(), script) + "\n" + compressJsFile(script) + "\n";
		}
		return blob;
	};

	var compressJsFile = function(inPath) {
		var outputOpts = {
//			beautify: false,
//			indent_level: 4,
			ascii_only: true
		};
		if (opt.beautify) {
			outputOpts.beautify = true;
			outputOpts.indent_level = 4;
		}
		var result = uglify.minify(inPath, {output: outputOpts});
		return result.code;
	};

	var walkerFinished = function(loader, chunks) {
		var outfolder = path.dirname(path.join(opt.destdir, opt.output));
		var exists = fs.existsSync || path.existsSync;
		var currChunk = 1;
		var topDepends;
		if (outfolder != "." && !exists(outfolder)) {
			fs.mkdirSync(outfolder);
		}
		if ((chunks.length == 1) && (typeof chunks[0] == "object")) {
			topDepends = false;
			currChunk = "";
		} else {
			topDepends = [];
		}
		var processNextChunk = function(done) {
			if (chunks.length > 0) {
				var chunk = chunks.shift();
				if (typeof chunk == "string") {
					topDepends.push(chunk);
					processNextChunk(done);
				} else {
					concatCss(chunk.sheets, function(css) {
						if (css.length) {
							w("");
							var cssFile = opt.output + currChunk + ".css";
							fs.writeFileSync(path.join(opt.destdir, cssFile), css, "utf8");
							if (topDepends) {
								topDepends.push(cssFile);
							}
						}
						var js = concatJs(loader, chunk.scripts);
						if (js.length) {
							w("");
							var jsFile = opt.output + currChunk + ".js";
							fs.writeFileSync(path.join(opt.destdir, jsFile), js, "utf8");
							if (topDepends) {
								topDepends.push(jsFile);
							}
						}
						currChunk++;
						processNextChunk(done);
					});
				}
			} else {
				done();
			}
		};
		processNextChunk(function() {
			if (topDepends) {
				var js = "";
				// Add path aliases to the mapped sources
				for (var i=0; i<opt.mapfrom.length; i++) {
					js = js + "enyo.path.addPath(\"" + opt.mapfrom[i] + "\", \"" + opt.mapto[i] + "\");\n";
				}
				// Override the default rule that $lib lives next to $enyo, since enyo may be remote
				js = js + "enyo.path.addPath(\"lib\", \"lib\");\n";
				// Add depends for all of the top-level files
				js = js + "enyo.depends(\n\t\"" + topDepends.join("\",\n\t\"") + "\"\n);";
				fs.writeFileSync(path.join(opt.destdir, opt.output + ".js"), js, "utf8");
				fs.writeFileSync(path.join(opt.destdir, opt.output + ".css"), "/* CSS loaded via enyo.depends() call in " + opt.output + ".js */", "utf8");
			}

			w("");
			w("done.");
			w("");

			// required to properly terminate a
			// node.process.fork() call, as defined by
			// <http://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options>
			process.exit(0);
		});
	};

	var knownOpts = {
		"alias": Boolean,
		"enyo": String,
		"lib": String,
		"destdir": path, // only path that needs to be revoved by nopt as an absolute one
		"output": String,
		"help": Boolean,
		"beautify": Boolean,
		"mapfrom": [String, Array],
		"mapto": [String, Array]
	};

	var shortHands = {
		"alias": ['--alias'],
		"enyo": ['--enyo'],
		"lib": ['--lib'],
		"destdir": ['--destdir'],
		"output": ['--output'],
		"h": ['--help'],
		"?": ['--help'],
		"help": ['--help'],
		"beautify": ['--beautify'],
		"f": ['--mapfrom'],
		"t": ['--mapto']
	};

	opt = nopt(knownOpts, shortHands, process.argv, 2);
	opt.source = opt.argv.remain[0] || "package.js";
	w(opt);
	if (opt.source) {
		process.chdir(path.dirname(opt.source));
	}

	w("");
	w("");

	if (opt.help) {
		printUsage();
		process.exit();
	}

	// Send message to parent node process, if any
	process.on('uncaughtException', function (err) {
		e(err.stack);
		if (process.send) {
			// only available if parent-process is node
			process.send({error: err});
		}
		process.exit(1);
	});
	// receive error messages from child node processes
	process.on('message', function(msg) {
		console.dir(basename, msg);
		if (msg.error && msg.error.stack) {
			console.error(basename, msg.error.stack);
		}
		if (process.send) {
			process.send(msg);
		}
	});

	opt.destdir = opt.destdir || process.cwd();
	opt.output = opt.output || "build/out";
	if (path.resolve(opt.output) === opt.output) {
		throw new Error("-output must be a relative path prefix");
	}

	walker.init(opt.enyo, opt.lib || opt.enyo + "/../lib", opt.mapfrom, opt.mapto);
	walker.walk('package.js', walkerFinished);

})();<commit_msg>ENYO-3012: (less) fix case where `package.js` deep (>1) in the source tree<commit_after>(function() {
	/* jshint node: true */
	var
		fs = require("fs"),
		path = require("path"),
		walker = require("walker"),
		uglify = require("uglify-js"),
		nopt = require("nopt"),
		less = require("less");

	var basename = path.basename(__filename),
		w = console.log,
		e = console.error,
		opt;

	// Shimming path.relative with 0.8.8's version if it doesn't exist
	if(!path.relative){
		path.relative = require('./path-relative-shim').relative;
	}

	function printUsage() {
		w("Enyo 2.0 Minifier");
		w("Usage: " + __filename + " [Flags] [path/to/package.js]");
		w("Flags:");
		w("-no-less:", "Don't compile less; instad substitute css for less");
		w("-no-alias:", "Don't use path macros");
		w("-alias:", "Give paths a macroized alias");
		w("-enyo ENYOPATH:", "Relative path to enyo folder (enyo)");
		w("-lib LIBPATH:", "Relative path to lib folder ($enyo/../lib)");
		w("-destdir DESTDIR:", "Target directory, prepended to any output file but skipped within generated files (current dir)");
		w("-output RELPATH/PREFIX:", "Folder + output file prefix, relative to DESTDIR (build/out)");
		w("-beautify:", "Output pretty version that's less compressed but has code on separate lines");
		w("-f", "Remote source mapping: from local path");
		w("-t", "Remote source mapping: to remote path");
		w("-h, -?, -help:", "Show this message");
	}

	// properly split path based on platform
	function pathSplit(inPath) {
		var sep = process.platform == "win32" ? "\\" : "/";
		return inPath.split(sep);
	}

	function concatCss(sheets, doneCB) {
		w("");
		var blob = "";
		var addToBlob = function(sheet, code) {
			// fix url paths
			code = code.replace(/url\([^)]*\)/g, function(inMatch) {
				// find the url path, ignore quotes in url string
				var matches = /url\s*\(\s*(('([^']*)')|("([^"]*)")|([^'"]*))\s*\)/.exec(inMatch);
				var urlPath = matches[3] || matches[5] || matches[6];
				// skip data urls
				if (/^data:/.test(urlPath)) {
					return "url(" + urlPath + ")";
				}
				// skip an external link
				if (/^http(:?s)?:/.test(urlPath)) {
					return "url(" + urlPath + ")";
				}
				// Make relative asset path from 'top-of-the-tree/build'
				var relPath = path.join("..", opt.relsrcdir, path.dirname(sheet), urlPath);
				if (process.platform == "win32") {
					relPath = pathSplit(relPath).join("/");
				}
				console.log("opt.relsrcdir:", opt.relsrcdir);
				console.log("sheet:", sheet);
				console.log("urlPath:", urlPath);
				console.log("relPath:", relPath);
				return "url(" + relPath + ")";
			});
			blob += "\n/* " + path.relative(process.cwd(), sheet) + " */\n\n" + code + "\n";
		};
		// Pops one sheet off the sheets[] array, reads (and parses if less), and then
		// recurses again from the async callback until no sheets left, then calls doneCB
		function readAndParse() {
			var sheet = sheets.shift();
			if (sheet) {
				w(sheet);
				var isLess = (sheet.slice(-4) == "less");
				if (isLess && (opt.less !== true)) {
					sheet = sheet.slice(0, sheet.length-4) + "css";
					isLess = false;
					w(" (Substituting CSS: " + sheet + ")");
				}
				var code = fs.readFileSync(sheet, "utf8");
				if (isLess) {
					var parser = new(less.Parser)({filename:sheet, paths:[path.dirname(sheet)]});
					parser.parse(code, function (err, tree) {
						if (err) {
							console.error(err);
						} else {
							addToBlob(sheet, tree.toCSS());
						}
						readAndParse(sheets);
					});
				} else {
					addToBlob(sheet, code);
					readAndParse(sheets);
				}
			} else {
				doneCB(blob);
			}
		}
		readAndParse();
	}

	var concatJs = function(loader, scripts) {
		w("");
		var blob = "";
		for (var i=0, script; (script=scripts[i]); i++) {
			w(script);
			blob += "\n// " + path.relative(process.cwd(), script) + "\n" + compressJsFile(script) + "\n";
		}
		return blob;
	};

	var compressJsFile = function(inPath) {
		var outputOpts = {
//			beautify: false,
//			indent_level: 4,
			ascii_only: true
		};
		if (opt.beautify) {
			outputOpts.beautify = true;
			outputOpts.indent_level = 4;
		}
		var result = uglify.minify(inPath, {output: outputOpts});
		return result.code;
	};

	var walkerFinished = function(loader, chunks) {
		var outfolder = path.dirname(path.join(opt.destdir, opt.output));
		var exists = fs.existsSync || path.existsSync;
		var currChunk = 1;
		var topDepends;
		if (outfolder != "." && !exists(outfolder)) {
			fs.mkdirSync(outfolder);
		}
		if ((chunks.length == 1) && (typeof chunks[0] == "object")) {
			topDepends = false;
			currChunk = "";
		} else {
			topDepends = [];
		}
		var processNextChunk = function(done) {
			if (chunks.length > 0) {
				var chunk = chunks.shift();
				if (typeof chunk == "string") {
					topDepends.push(chunk);
					processNextChunk(done);
				} else {
					concatCss(chunk.sheets, function(css) {
						if (css.length) {
							w("");
							var cssFile = opt.output + currChunk + ".css";
							fs.writeFileSync(path.join(opt.destdir, cssFile), css, "utf8");
							if (topDepends) {
								topDepends.push(cssFile);
							}
						}
						var js = concatJs(loader, chunk.scripts);
						if (js.length) {
							w("");
							var jsFile = opt.output + currChunk + ".js";
							fs.writeFileSync(path.join(opt.destdir, jsFile), js, "utf8");
							if (topDepends) {
								topDepends.push(jsFile);
							}
						}
						currChunk++;
						processNextChunk(done);
					});
				}
			} else {
				done();
			}
		};
		processNextChunk(function() {
			if (topDepends) {
				var js = "";
				// Add path aliases to the mapped sources
				for (var i=0; i<opt.mapfrom.length; i++) {
					js = js + "enyo.path.addPath(\"" + opt.mapfrom[i] + "\", \"" + opt.mapto[i] + "\");\n";
				}
				// Override the default rule that $lib lives next to $enyo, since enyo may be remote
				js = js + "enyo.path.addPath(\"lib\", \"lib\");\n";
				// Add depends for all of the top-level files
				js = js + "enyo.depends(\n\t\"" + topDepends.join("\",\n\t\"") + "\"\n);";
				fs.writeFileSync(path.join(opt.destdir, opt.output + ".js"), js, "utf8");
				fs.writeFileSync(path.join(opt.destdir, opt.output + ".css"), "/* CSS loaded via enyo.depends() call in " + opt.output + ".js */", "utf8");
			}

			w("");
			w("done.");
			w("");

			// required to properly terminate a
			// node.process.fork() call, as defined by
			// <http://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options>
			process.exit(0);
		});
	};

	var knownOpts = {
		"alias": Boolean,
		"enyo": String,	 // relative path
		"lib": String,	 // relative path
		"destdir": path, // absolute path (resolved by nopt)
		"srcdir": path,	 // absolute path (resolved by nopt)
		"output": String, // relative path
		"help": Boolean,
		"beautify": Boolean,
		"mapfrom": [String, Array],
		"mapto": [String, Array]
	};

	var shortHands = {
		"alias": ['--alias'],
		"enyo": ['--enyo'],
		"lib": ['--lib'],
		"srcdir": ['--srcdir'],
		"destdir": ['--destdir'],
		"output": ['--output'],
		"h": ['--help'],
		"?": ['--help'],
		"help": ['--help'],
		"beautify": ['--beautify'],
		"f": ['--mapfrom'],
		"t": ['--mapto']
	};

	opt = nopt(knownOpts, shortHands, process.argv, 2);
	opt.packagejs = opt.argv.remain[0] || "package.js";
	opt.srcdir = opt.srcdir || process.cwd();
	if (opt.packagejs) {
		// walker only works from top-level package.js...
		process.chdir(path.dirname(opt.packagejs));
	}
	// ...but we still want to (relatively) track the top of the
	// tree, because this is the root from which the LESS sheets
	// are resolved (unlike the JS dependencies, which are
	// resolved from the folder of the top-level package.js).
	opt.relsrcdir = path.relative(opt.srcdir, process.cwd());

	if (opt.help) {
		printUsage();
		process.exit();
	}

	// Send message to parent node process, if any
	process.on('uncaughtException', function (err) {
		e(err.stack);
		if (process.send) {
			// only available if parent-process is node
			process.send({error: err});
		}
		process.exit(1);
	});
	// receive error messages from child node processes
	process.on('message', function(msg) {
		console.dir(basename, msg);
		if (msg.error && msg.error.stack) {
			console.error(basename, msg.error.stack);
		}
		if (process.send) {
			process.send(msg);
		}
	});

	opt.destdir = opt.destdir || process.cwd();
	opt.output = opt.output || "build/out";
	if (path.resolve(opt.output) === opt.output) {
		throw new Error("-output must be a relative path prefix");
	}

	w(opt);
	walker.init(opt.enyo, opt.lib || opt.enyo + "/../lib", opt.mapfrom, opt.mapto);
	walker.walk('package.js', walkerFinished);

})();<|endoftext|>


<commit_before>import AddCategoryClass from 'discourse/mixins/add-category-class';
import { listenForViewEvent } from 'discourse/lib/app-events';
import { categoryBadgeHTML } from 'discourse/helpers/category-link';

var TopicView = Discourse.View.extend(AddCategoryClass, Discourse.Scrolling, {
  templateName: 'topic',
  topicBinding: 'controller.model',
  userFiltersBinding: 'controller.userFilters',
  classNameBindings: ['controller.multiSelect:multi-select',
                      'topic.archetype',
                      'topic.is_warning',
                      'topic.category.read_restricted:read_restricted',
                      'topic.deleted:deleted-topic',
                      'topic.categoryClass'],
  menuVisible: true,
  SHORT_POST: 1200,

  categorySlug: Em.computed.alias('topic.category.slug'),

  postStream: Em.computed.alias('controller.postStream'),

  _composeChanged: function() {
    var composerController = Discourse.get('router.composerController');
    composerController.clearState();
    composerController.set('topic', this.get('topic'));
  }.observes('composer'),

  _enteredTopic: function() {
    // Ember is supposed to only call observers when values change but something
    // in our view set up is firing this observer with the same value. This check
    // prevents scrolled from being called twice.
    var enteredAt = this.get('controller.enteredAt');
    if (enteredAt && (this.get('lastEnteredAt') !== enteredAt)) {
      this.scrolled();
      this.set('lastEnteredAt', enteredAt);
    }
  }.observes('controller.enteredAt'),

  _inserted: function() {
    this.bindScrolling({name: 'topic-view'});

    var self = this;
    $(window).on('resize.discourse-on-scroll', function() {
      self.scrolled();
    });

    this.$().on('mouseup.discourse-redirect', '.cooked a, a.track-link', function(e) {
      var selection = window.getSelection && window.getSelection();
      // bypass if we are selecting stuff
      if (selection.type === "Range" || selection.rangeCount > 0) { return true; }

      var $target = $(e.target);
      if ($target.hasClass('mention') || $target.parents('.expanded-embed').length) { return false; }
      return Discourse.ClickTrack.trackClick(e);

    });

  }.on('didInsertElement'),

  // This view is being removed. Shut down operations
  _destroyed: function() {
    this.unbindScrolling('topic-view');
    $(window).unbind('resize.discourse-on-scroll');

    // Unbind link tracking
    this.$().off('mouseup.discourse-redirect', '.cooked a, a.track-link');

    this.resetExamineDockCache();

    // this happens after route exit, stuff could have trickled in
    this.set('controller.controllers.header.showExtraInfo', false);

  }.on('willDestroyElement'),

  gotFocus: function(){
    if (Discourse.get('hasFocus')){
      this.scrolled();
    }
  }.observes("Discourse.hasFocus"),

  resetExamineDockCache: function() {
    this.set('docAt', false);
  },

  offset: 0,
  hasScrolled: Em.computed.gt("offset", 0),

  /**
    The user has scrolled the window, or it is finished rendering and ready for processing.

    @method scrolled
  **/
  scrolled: function(){

    if(this.isDestroyed || this.isDestroying) {
      return;
    }

    var offset = window.pageYOffset || $('html').scrollTop();
    if (!this.get('docAt')) {
      var title = $('#topic-title');
      if (title && title.length === 1) {
        this.set('docAt', title.offset().top);
      }
    }

    this.set("offset", offset);

    var headerController = this.get('controller.controllers.header'),
        topic = this.get('controller.model');
    if (this.get('docAt')) {
      headerController.set('showExtraInfo', offset >= this.get('docAt') || topic.get('postStream.firstPostNotLoaded'));
    } else {
      headerController.set('showExtraInfo', topic.get('postStream.firstPostNotLoaded'));
    }

    // Trigger a scrolled event
    this.appEvents.trigger('topic:scrolled', offset);
  },

  topicTrackingState: function() {
    return Discourse.TopicTrackingState.current();
  }.property(),

  browseMoreMessage: function() {
    var opts = { latestLink: "" + I18n.t("topic.view_latest_topics") + "" },
        category = this.get('controller.content.category');

    if(Em.get(category, 'id') === Discourse.Site.currentProp("uncategorized_category_id")) {
      category = null;
    }

    if (category) {
      opts.catLink = categoryBadgeHTML(category);
    } else {
      opts.catLink = "" + I18n.t("topic.browse_all_categories") + "";
    }

    var tracking = this.get('topicTrackingState'),
        unreadTopics = tracking.countUnread(),
        newTopics = tracking.countNew();

    if (newTopics + unreadTopics > 0) {
      var hasBoth = unreadTopics > 0 && newTopics > 0;

      return I18n.messageFormat("topic.read_more_MF", {
        "BOTH": hasBoth,
        "UNREAD": unreadTopics,
        "NEW": newTopics,
        "CATEGORY": category ? true : false,
        latestLink: opts.latestLink,
        catLink: opts.catLink
      });
    }
    else if (category) {
      return I18n.t("topic.read_more_in_category", opts);
    } else {
      return I18n.t("topic.read_more", opts);
    }
  }.property('topicTrackingState.messageCount')
});

function highlight(postNumber) {
  var $contents = $('#post_' + postNumber +' .topic-body'),
      origColor = $contents.data('orig-color') || $contents.css('backgroundColor');

  $contents.data("orig-color", origColor)
    .addClass('highlighted')
    .stop()
    .animate({ backgroundColor: origColor }, 2500, 'swing', function(){
      $contents.removeClass('highlighted');
      $contents.css({'background-color': ''});
    });
}

listenForViewEvent(TopicView, 'post:highlight', function(postNumber) {
  Ember.run.scheduleOnce('afterRender', null, highlight, postNumber);
});

export default TopicView;
<commit_msg>FIX: category background in topic views<commit_after>import AddCategoryClass from 'discourse/mixins/add-category-class';
import { listenForViewEvent } from 'discourse/lib/app-events';
import { categoryBadgeHTML } from 'discourse/helpers/category-link';

var TopicView = Discourse.View.extend(AddCategoryClass, Discourse.Scrolling, {
  templateName: 'topic',
  topicBinding: 'controller.model',
  userFiltersBinding: 'controller.userFilters',
  classNameBindings: ['controller.multiSelect:multi-select',
                      'topic.archetype',
                      'topic.is_warning',
                      'topic.category.read_restricted:read_restricted',
                      'topic.deleted:deleted-topic',
                      'topic.categoryClass'],
  menuVisible: true,
  SHORT_POST: 1200,

  categoryFullSlug: Em.computed.alias('topic.category.fullSlug'),

  postStream: Em.computed.alias('controller.postStream'),

  _composeChanged: function() {
    var composerController = Discourse.get('router.composerController');
    composerController.clearState();
    composerController.set('topic', this.get('topic'));
  }.observes('composer'),

  _enteredTopic: function() {
    // Ember is supposed to only call observers when values change but something
    // in our view set up is firing this observer with the same value. This check
    // prevents scrolled from being called twice.
    var enteredAt = this.get('controller.enteredAt');
    if (enteredAt && (this.get('lastEnteredAt') !== enteredAt)) {
      this.scrolled();
      this.set('lastEnteredAt', enteredAt);
    }
  }.observes('controller.enteredAt'),

  _inserted: function() {
    this.bindScrolling({name: 'topic-view'});

    var self = this;
    $(window).on('resize.discourse-on-scroll', function() {
      self.scrolled();
    });

    this.$().on('mouseup.discourse-redirect', '.cooked a, a.track-link', function(e) {
      var selection = window.getSelection && window.getSelection();
      // bypass if we are selecting stuff
      if (selection.type === "Range" || selection.rangeCount > 0) { return true; }

      var $target = $(e.target);
      if ($target.hasClass('mention') || $target.parents('.expanded-embed').length) { return false; }
      return Discourse.ClickTrack.trackClick(e);

    });

  }.on('didInsertElement'),

  // This view is being removed. Shut down operations
  _destroyed: function() {
    this.unbindScrolling('topic-view');
    $(window).unbind('resize.discourse-on-scroll');

    // Unbind link tracking
    this.$().off('mouseup.discourse-redirect', '.cooked a, a.track-link');

    this.resetExamineDockCache();

    // this happens after route exit, stuff could have trickled in
    this.set('controller.controllers.header.showExtraInfo', false);

  }.on('willDestroyElement'),

  gotFocus: function(){
    if (Discourse.get('hasFocus')){
      this.scrolled();
    }
  }.observes("Discourse.hasFocus"),

  resetExamineDockCache: function() {
    this.set('docAt', false);
  },

  offset: 0,
  hasScrolled: Em.computed.gt("offset", 0),

  /**
    The user has scrolled the window, or it is finished rendering and ready for processing.

    @method scrolled
  **/
  scrolled: function(){

    if(this.isDestroyed || this.isDestroying) {
      return;
    }

    var offset = window.pageYOffset || $('html').scrollTop();
    if (!this.get('docAt')) {
      var title = $('#topic-title');
      if (title && title.length === 1) {
        this.set('docAt', title.offset().top);
      }
    }

    this.set("offset", offset);

    var headerController = this.get('controller.controllers.header'),
        topic = this.get('controller.model');
    if (this.get('docAt')) {
      headerController.set('showExtraInfo', offset >= this.get('docAt') || topic.get('postStream.firstPostNotLoaded'));
    } else {
      headerController.set('showExtraInfo', topic.get('postStream.firstPostNotLoaded'));
    }

    // Trigger a scrolled event
    this.appEvents.trigger('topic:scrolled', offset);
  },

  topicTrackingState: function() {
    return Discourse.TopicTrackingState.current();
  }.property(),

  browseMoreMessage: function() {
    var opts = { latestLink: "" + I18n.t("topic.view_latest_topics") + "" },
        category = this.get('controller.content.category');

    if(Em.get(category, 'id') === Discourse.Site.currentProp("uncategorized_category_id")) {
      category = null;
    }

    if (category) {
      opts.catLink = categoryBadgeHTML(category);
    } else {
      opts.catLink = "" + I18n.t("topic.browse_all_categories") + "";
    }

    var tracking = this.get('topicTrackingState'),
        unreadTopics = tracking.countUnread(),
        newTopics = tracking.countNew();

    if (newTopics + unreadTopics > 0) {
      var hasBoth = unreadTopics > 0 && newTopics > 0;

      return I18n.messageFormat("topic.read_more_MF", {
        "BOTH": hasBoth,
        "UNREAD": unreadTopics,
        "NEW": newTopics,
        "CATEGORY": category ? true : false,
        latestLink: opts.latestLink,
        catLink: opts.catLink
      });
    }
    else if (category) {
      return I18n.t("topic.read_more_in_category", opts);
    } else {
      return I18n.t("topic.read_more", opts);
    }
  }.property('topicTrackingState.messageCount')
});

function highlight(postNumber) {
  var $contents = $('#post_' + postNumber +' .topic-body'),
      origColor = $contents.data('orig-color') || $contents.css('backgroundColor');

  $contents.data("orig-color", origColor)
    .addClass('highlighted')
    .stop()
    .animate({ backgroundColor: origColor }, 2500, 'swing', function(){
      $contents.removeClass('highlighted');
      $contents.css({'background-color': ''});
    });
}

listenForViewEvent(TopicView, 'post:highlight', function(postNumber) {
  Ember.run.scheduleOnce('afterRender', null, highlight, postNumber);
});

export default TopicView;
<|endoftext|>


<commit_before>/**
 * The LayerSpecModel model.
 *
 * @return LayerSpecModel (extends Backbone.Model).
 */
define([
  'underscore',
  'backbone'
], function(_, Backbone) {

  'use strict';

  var LayerSpecModel = Backbone.Model.extend({

    // You should put more importants layers at the bottom of the layerOrder
    // As you see forestchange layers are the more importants so they will be added to top

    layerOrder: [
      // FOREST USE
      "grump2000",
      "forest2000",
      "pantropical",
      "mangrove",
      "colombia_forest_change",
      "idn_primary",
      "ifl_2013_deg",
      "ifl_2000",
      // PEOPLE
      "land_rights",
      "resource_rights",
      // CONSERVATION
      "biodiversity_hotspots",
      "protected_areasCDB",
      // FOREST USE
      "wood_fiber_plantations",
      "oil_palm",
      "mining",
      "logging",
      // FOREST CHANGE
      "terraicanvas_cover_cover",
      "forma_cover",
      "imazon_cover",
      "modis_cover",
      // FOREST CHANGE
      "terrailoss",
      "fires",
      "modis",
      "imazon",
      "forma",
      "loss",
      "forestgain"
    ],

    categoryOrder: [
      'forest_clearing',
      'forest_cover',
      'forest_use',
      'people',
      'conservation',
      'stories'
    ],

    /**
     * Add a position attribute to the provided layers.
     *
     * @param  {object} layers
     * @return {object} layers
     */
    positionizer: function(layers) {
      var layerOrder = _.intersection(this.layerOrder, _.pluck(layers, 'slug'));
      _.each(layerOrder, _.bind(function(slug, i) {
        layers[slug].position = this.layerOrder.indexOf(slug) + 1;
      }, this ));

      return layers;
    },

    getLayer: function(where) {
      if (!where) {return;}
      var layer = _.findWhere(this.getLayers(), where, this);
      return layer;
    },

    /**
     * Get all the layers uncategorized.
     * {forest2000: {}, gain:{}, ...}
     *
     * @return {object} layers
     */
    getLayers: function() {
      var layers = {};

      _.each(this.toJSON(), function(category) {
        _.extend(layers, category);
      });

      return this.positionizer(layers);
    },

    /**
     * Return baselayers object.
     *
     * @return {object} baselayers
     */
    getBaselayers: function() {
      return this.positionizer(this.get('forest_clearing') || {});
    },

    /**
     * Return sublayers object.
     *
     * @return {object} sublayers
     */
    getSublayers: function() {
      var layers = {};

      _.each(_.omit(this.toJSON(), 'forest_clearing'),
        function(results) {
          layers = _.extend(layers, results);
        });

      return this.positionizer(layers);
    },

   /**
     * Return an ordered array of layers. Order by layer position.
     *
     * @return {array} layers
     */
    getOrderedLayers: function() {
      return _.sortBy(this.getLayers(), function(layer) {
        return layer.position;
      });
    },

    /**
     * Return an ordered array of categories and layers.
     *
     * @return {array} categories
     */
    getLayersByCategory: function() {
      var categories = [];

      _.each(this.categoryOrder, _.bind(function(categoryName) {
        var category = this.get(categoryName);
        if (category) {
          categories.push(_.sortBy(this.positionizer(category),
            function(layer) {
              return layer.position;
            }));
        }
      }, this));

      return categories;
    }

  });

  return LayerSpecModel;

});
<commit_msg>layers added<commit_after>/**
 * The LayerSpecModel model.
 *
 * @return LayerSpecModel (extends Backbone.Model).
 */
define([
  'underscore',
  'backbone'
], function(_, Backbone) {

  'use strict';

  var LayerSpecModel = Backbone.Model.extend({

    // You should put more importants layers at the bottom of the layerOrder
    // As you see forestchange layers are the more importants so they will be added to top
    //the order will be Grump, forest cover,Conservation, Forest Use, and People layers and finally  Forest Change layers
    layerOrder: [
      "grump2000",
      //FOREST COVER
      "forest2000",
      "WMSLayer",
      "intact_forest",
      "pantropical",
      "mangrove",
      "colombia_forest_change",
      "idn_primary",
      "ifl_2013_deg",
      "ifl_2000",
      // PEOPLE
      "land_rights",
      "aus_land_rights",
      "pan_land_rights",
      "bra_land_rights",
      "can_land_rights",
      "cri_land_rights",
      "resource_rights",
      "cmr_resource_rights",
      "lbr_resource_rights",
      "gnq_resource_rights",
      "nam_resource_rights",

      // CONSERVATION
      "biodiversity_hotspots",
      "verified_carbon",
      "azepoly",
      "wwf",
      "usa_conservation_easements",
      "birdlife",
      "tigers",
      "biodiversity_hotspots",
      "protected_areasCDB",
      // FOREST USE
      "wood_fiber_plantations",
      "gab_wood_fiber",
      "cog_wood_fiber",
      "idn_wood_fiber",
      "oil_palm",
      "idn_oil_palm",
      "cmr_oil_palm",
      "lbr_oil_palm",
      "cog_oil_palm",
      "mining",
      "can_permits",
      "cmr_mining",
      "cod_mining",
      "cog_mining",
      "gab_mining",
      "col_mining",
      "can_coal",
      "logging",
      "cod_logging",
      "cmr_logging",
      "idn_logging",
      "gnq_logging",
      "gnq_logging",
      "idn_logging",
      "cmr_logging",
      "caf_logging",
      "cod_logging",
      "gab_logging",
      "concesiones_forestales",
      "concesiones_forestalesNS",
      "concesiones_wrapper",
      "dam_hotspots",
      //STORIES
      "user_stories",
      "infoamazonia",
      "mongabay",
      // FOREST CHANGE
      "terraicanvas_cover_cover",
      "forma_cover",
      "imazon_cover",
      "modis_cover",
      // FOREST CHANGE
      "terrailoss",
      "fires",
      "modis",
      "imazon",
      "forma",
      "loss",
      "forestgain"
    ],

    categoryOrder: [
      'forest_clearing',
      'forest_cover',
      'forest_use',
      'people',
      'conservation',
      'stories'
    ],

    /**
     * Add a position attribute to the provided layers.
     *
     * @param  {object} layers
     * @return {object} layers
     */
    positionizer: function(layers) {
      var layerOrder = _.intersection(this.layerOrder, _.pluck(layers, 'slug'));
      _.each(layerOrder, _.bind(function(slug, i) {
        layers[slug].position = this.layerOrder.indexOf(slug) + 1;
      }, this ));

      return layers;
    },

    getLayer: function(where) {
      if (!where) {return;}
      var layer = _.findWhere(this.getLayers(), where, this);
      return layer;
    },

    /**
     * Get all the layers uncategorized.
     * {forest2000: {}, gain:{}, ...}
     *
     * @return {object} layers
     */
    getLayers: function() {
      var layers = {};

      _.each(this.toJSON(), function(category) {
        _.extend(layers, category);
      });

      return this.positionizer(layers);
    },

    /**
     * Return baselayers object.
     *
     * @return {object} baselayers
     */
    getBaselayers: function() {
      return this.positionizer(this.get('forest_clearing') || {});
    },

    /**
     * Return sublayers object.
     *
     * @return {object} sublayers
     */
    getSublayers: function() {
      var layers = {};

      _.each(_.omit(this.toJSON(), 'forest_clearing'),
        function(results) {
          layers = _.extend(layers, results);
        });

      return this.positionizer(layers);
    },

   /**
     * Return an ordered array of layers. Order by layer position.
     *
     * @return {array} layers
     */
    getOrderedLayers: function() {
      return _.sortBy(this.getLayers(), function(layer) {
        return layer.position;
      });
    },

    /**
     * Return an ordered array of categories and layers.
     *
     * @return {array} categories
     */
    getLayersByCategory: function() {
      var categories = [];

      _.each(this.categoryOrder, _.bind(function(categoryName) {
        var category = this.get(categoryName);
        if (category) {
          categories.push(_.sortBy(this.positionizer(category),
            function(layer) {
              return layer.position;
            }));
        }
      }, this));

      return categories;
    }

  });

  return LayerSpecModel;

});
<|endoftext|>


<commit_before>function Movements($http) {
  this.getMovements = function() {
    return $http.get('http://localhost:3000/movements.json')
  }

  this.createMovement = function() {
    return $http.post('http://localhost:3000/movements')
  }
}

angular
  .module('app')
  .service('Movements', Movements)
<commit_msg>add artwork parameter in .createMovement function<commit_after>function Movements($http) {
  this.getMovements = function() {
    return $http.get('http://localhost:3000/movements.json')
  }

  this.createMovement = function(artwork) {
    return $http.post('http://localhost:3000/movements', artwork)
  }
}

angular
  .module('app')
  .service('Movements', Movements)
<|endoftext|>


<commit_before>import Node from '../Node.js';
import { UNKNOWN } from '../../utils/sentinels.js';
import stringify from '../../utils/stringify.js';

const calculators = {
	'**' : ( a, b ) => Math.pow( a, b ),
	'*'  : ( a, b ) => a * b,
	'/'  : ( a, b ) => a / b,
	'%'  : ( a, b ) => a % b,
	'+'  : ( a, b ) => a + b,
	'-'  : ( a, b ) => a - b,
	'<<' : ( a, b ) => a << b,
	'>>' : ( a, b ) => a >> b,
	'>>>': ( a, b ) => a >>> b,
	'<'  : ( a, b ) => a < b,
	'<=' : ( a, b ) => a <= b,
	'>'  : ( a, b ) => a > b,
	'>=' : ( a, b ) => a >= b,
	'==' : ( a, b ) => a == b,
	'!=' : ( a, b ) => a != b,
	'===': ( a, b ) => a === b,
	'!==': ( a, b ) => a !== b,
	'&'  : ( a, b ) => a & b,
	'^'  : ( a, b ) => a ^ b,
	'|'  : ( a, b ) => a | b,
	in   : ( a, b ) => a in b,
	instanceof: ( a, b ) => a instanceof b
};

const binaryExpressionPrecedence = {};
[
	[  7, '|' ],
	[  8, '^' ],
	[  9, '&' ],
	[ 10, '!== === != ==' ],
	[ 11, 'instanceof in >= > <= <' ],
	[ 12, '>>> >> <<' ],
	[ 13, '- +' ],
	[ 14, '% / * **' ]
].forEach( ([ precedence, operators ]) => {
	operators.split( ' ' ).forEach( operator => binaryExpressionPrecedence[ operator ] = precedence );
});

export default class BinaryExpression extends Node {
	getLeftHandSide () {
		return this.left.getLeftHandSide();
	}

	getPrecedence () {
		const left = this.left.getValue();
		const right = this.right.getValue();

		if ( left === UNKNOWN || right === UNKNOWN ) return binaryExpressionPrecedence[ this.operator ];

		return 20; // will be replaced by a literal
	}

	getValue () {
		const left = this.left.getValue();
		const right = this.right.getValue();

		if ( left === UNKNOWN || right === UNKNOWN ) return UNKNOWN;

		return calculators[ this.operator ]( left, right );
	}

	minify ( code ) {
		const value = this.getValue();

		if ( value !== UNKNOWN ) {
			code.overwrite( this.start, this.end, stringify( value ) );
		}

		else {
			let operator = this.operator;

			if ( code.original[ this.right.getLeftHandSide().start ] === operator ) {
				// prevent e.g. `1 - --t` becoming 1---t
				operator = `${operator} `;
			} else if ( /\w/.test( this.operator ) ) {
				// `foo in bar`, not `fooinbar`
				operator = ` ${operator} `;
			}

			if ( this.right.start > this.left.end + operator.length ) {
				code.overwrite( this.left.end, this.right.start, operator );
			}

			super.minify( code );
		}
	}
}
<commit_msg>Only fold BinaryExpression if both operands are completely known<commit_after>import Node from '../Node.js';
import { TRUTHY, FALSY, UNKNOWN } from '../../utils/sentinels.js';
import stringify from '../../utils/stringify.js';

const calculators = {
	'**' : ( a, b ) => Math.pow( a, b ),
	'*'  : ( a, b ) => a * b,
	'/'  : ( a, b ) => a / b,
	'%'  : ( a, b ) => a % b,
	'+'  : ( a, b ) => a + b,
	'-'  : ( a, b ) => a - b,
	'<<' : ( a, b ) => a << b,
	'>>' : ( a, b ) => a >> b,
	'>>>': ( a, b ) => a >>> b,
	'<'  : ( a, b ) => a < b,
	'<=' : ( a, b ) => a <= b,
	'>'  : ( a, b ) => a > b,
	'>=' : ( a, b ) => a >= b,
	'==' : ( a, b ) => a == b,
	'!=' : ( a, b ) => a != b,
	'===': ( a, b ) => a === b,
	'!==': ( a, b ) => a !== b,
	'&'  : ( a, b ) => a & b,
	'^'  : ( a, b ) => a ^ b,
	'|'  : ( a, b ) => a | b,
	in   : ( a, b ) => a in b,
	instanceof: ( a, b ) => a instanceof b
};

const binaryExpressionPrecedence = {};
[
	[  7, '|' ],
	[  8, '^' ],
	[  9, '&' ],
	[ 10, '!== === != ==' ],
	[ 11, 'instanceof in >= > <= <' ],
	[ 12, '>>> >> <<' ],
	[ 13, '- +' ],
	[ 14, '% / * **' ]
].forEach( ([ precedence, operators ]) => {
	operators.split( ' ' ).forEach( operator => binaryExpressionPrecedence[ operator ] = precedence );
});

export default class BinaryExpression extends Node {
	getLeftHandSide () {
		return this.left.getLeftHandSide();
	}

	getPrecedence () {
		const left = this.left.getValue();
		const right = this.right.getValue();

		if (
			left === UNKNOWN || left === TRUTHY || left === FALSY ||
			right === UNKNOWN || right === TRUTHY || right === FALSY
		) return binaryExpressionPrecedence[ this.operator ];

		return 20; // will be replaced by a literal
	}

	getValue () {
		const left = this.left.getValue();
		const right = this.right.getValue();

		if (
			left === UNKNOWN || left === TRUTHY || left === FALSY ||
			right === UNKNOWN || right === TRUTHY || right === FALSY
		) return UNKNOWN;

		return calculators[ this.operator ]( left, right );
	}

	minify ( code ) {
		const value = this.getValue();

		if ( value !== UNKNOWN ) {
			code.overwrite( this.start, this.end, stringify( value ) );
		}

		else {
			let operator = this.operator;

			if ( code.original[ this.right.getLeftHandSide().start ] === operator ) {
				// prevent e.g. `1 - --t` becoming 1---t
				operator = `${operator} `;
			} else if ( /\w/.test( this.operator ) ) {
				// `foo in bar`, not `fooinbar`
				operator = ` ${operator} `;
			}

			if ( this.right.start > this.left.end + operator.length ) {
				code.overwrite( this.left.end, this.right.start, operator );
			}

			super.minify( code );
		}
	}
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	ShopGrocery = mongoose.model('ShopGrocery'),
	_ = require('lodash');

/**
 * Create a Shop grocery
 */
exports.create = function(req, res) {
	var shopGrocery = new ShopGrocery(req.body);

	shopGrocery.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(shopGrocery);
		}
	});

};

exports.createAll = function(req, res, next) {
  var importShops = req.body;
  console.log(importShops)
  var bulk = ShopGrocery.collection.initializeUnorderedBulkOp();
  importShops.forEach(function(shop) {
    if (shop)
    bulk.insert(shop);
  })
  bulk.execute(function (err,result) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(result);
    }
  });
};

/**
 * Show the current Shop grocery
 */
exports.read = function(req, res) {
	res.jsonp(req.shopGrocery);
};

/**
 * Update a Shop grocery
 */
exports.update = function(req, res) {
	var shopGrocery = req.shopGrocery ;

	shopGrocery = _.extend(shopGrocery , req.body);

	shopGrocery.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(shopGrocery);
		}
	});
};

/**
 * Delete an Shop grocery
 */
exports.delete = function(req, res) {
	var shopGrocery = req.shopGrocery ;

	shopGrocery.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(shopGrocery);
		}
	});
};

/**
 * List of Shop groceries
 */
exports.list = function(req, res) {
	ShopGrocery.find().sort('-created').populate('user', 'displayName').exec(function(err, shopGroceries) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(shopGroceries);
		}
	});
};

exports.listNear = function(req, res) {
  if(!req.params.page)
  {
    var page = 1;
  }else{
    var page = req.params.page;
  }
  var per_page = 10;

  ShopGrocery.find(
      {
        loc:
        { $near :
        {
          $geometry: { type: "Point",  coordinates: [ req.params.lng, req.params.lat ] },
          $maxDistance: 5000
        }
        }
      }
  ).skip((page-1)*per_page).limit(per_page).exec(function(err, shopGroceries) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(shopGroceries);
    }
  });
};

/**
 * Shop grocery middleware
 */
exports.shopGroceryByID = function(req, res, next, id) {
	ShopGrocery.findById(id).populate('user', 'displayName').exec(function(err, shopGrocery) {
		if (err) return next(err);
		if (! shopGrocery) return next(new Error('Failed to load Shop grocery ' + id));
		req.shopGrocery = shopGrocery ;
		next();
	});
};

/**
 * Shop grocery middleware
 */
exports.shopGroceryByMobile= function(req, res) {
  ShopGrocery.findOneAndUpdate({ mobile: req.params.mobile },{deviceId: req.params.deviceId}).exec(function(err, shopGrocery) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(shopGrocery);
    }
  });
};

exports.listByDevice = function(req, res) {
  console.log("$$$$$$$$$$$$$$$$$$$$")
  ShopGrocery.find().exists('deviceId').exec(function(err, shopGrocery) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(shopGrocery);
    }
  });
};

/**
 * Shop grocery authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	//if (req.shopGrocery.user.id !== req.user.id) {
	if ('gehlotchirag@gmail.com' !== req.user.email) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<commit_msg>grocery shops added<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	ShopGrocery = mongoose.model('ShopGrocery'),
	_ = require('lodash');

/**
 * Create a Shop grocery
 */
exports.create = function(req, res) {
	var shopGrocery = new ShopGrocery(req.body);

	shopGrocery.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(shopGrocery);
		}
	});

};

exports.createAll = function(req, res, next) {
  console.log("****")
  var importShops = req.body;
  console.log(importShops)
  var bulk = ShopGrocery.collection.initializeUnorderedBulkOp();
  importShops.forEach(function(shop) {
    if (shop)
    bulk.insert(shop);
  })
  bulk.execute(function (err,result) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(result);
    }
  });
};

/**
 * Show the current Shop grocery
 */
exports.read = function(req, res) {
	res.jsonp(req.shopGrocery);
};

/**
 * Update a Shop grocery
 */
exports.update = function(req, res) {
	var shopGrocery = req.shopGrocery ;

	shopGrocery = _.extend(shopGrocery , req.body);

	shopGrocery.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(shopGrocery);
		}
	});
};

/**
 * Delete an Shop grocery
 */
exports.delete = function(req, res) {
	var shopGrocery = req.shopGrocery ;

	shopGrocery.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(shopGrocery);
		}
	});
};

/**
 * List of Shop groceries
 */
exports.list = function(req, res) {
	ShopGrocery.find().sort('-created').populate('user', 'displayName').exec(function(err, shopGroceries) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(shopGroceries);
		}
	});
};

exports.listNear = function(req, res) {
  if(!req.params.page)
  {
    var page = 1;
  }else{
    var page = req.params.page;
  }
  var per_page = 10;

  ShopGrocery.find(
      {
        loc:
        { $near :
        {
          $geometry: { type: "Point",  coordinates: [ req.params.lng, req.params.lat ] },
          $maxDistance: 5000
        }
        }
      }
  ).skip((page-1)*per_page).limit(per_page).exec(function(err, shopGroceries) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(shopGroceries);
    }
  });
};

/**
 * Shop grocery middleware
 */
exports.shopGroceryByID = function(req, res, next, id) {
	ShopGrocery.findById(id).populate('user', 'displayName').exec(function(err, shopGrocery) {
		if (err) return next(err);
		if (! shopGrocery) return next(new Error('Failed to load Shop grocery ' + id));
		req.shopGrocery = shopGrocery ;
		next();
	});
};

/**
 * Shop grocery middleware
 */
exports.shopGroceryByMobile= function(req, res) {
  ShopGrocery.findOneAndUpdate({ mobile: req.params.mobile },{deviceId: req.params.deviceId}).exec(function(err, shopGrocery) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(shopGrocery);
    }
  });
};

exports.listByDevice = function(req, res) {
  console.log("$$$$$$$$$$$$$$$$$$$$")
  ShopGrocery.find().exists('deviceId').exec(function(err, shopGrocery) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(shopGrocery);
    }
  });
};

/**
 * Shop grocery authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	//if (req.shopGrocery.user.id !== req.user.id) {
	if ('gehlotchirag@gmail.com' !== req.user.email) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<|endoftext|>


<commit_before>// @flow
import * as React from 'react';
import { View, StyleSheet, Text, TouchableOpacity } from 'react-native';
import { Price } from '@kiwicom/react-native-app-common';
import NoneSelected from './NoneSelected';

const styles = StyleSheet.create({
  container: {
    borderRadius: 3,
    backgroundColor: 'rgba(0, 151, 169, 0.2)',
    flexDirection: 'row',
  },
  button: {
    backgroundColor: '#0097a9',
    width: 60,
    paddingVertical: 10,
    alignItems: 'center',
  },
  minusButton: {
    borderTopLeftRadius: 3,
    borderBottomLeftRadius: 3,
  },
  plusButton: {
    borderTopRightRadius: 3,
    borderBottomRightRadius: 3,
  },
  disabledButton: {
    width: 60,
    backgroundColor: 'transparent',
  },
  buttonText: {
    backgroundColor: 'transparent',
    fontSize: 20,
    fontWeight: '600',
    color: '#ffffff',
  },
  priceAndCount: {
    flexGrow: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  count: {
    fontSize: 14,
    color: '#0097a9',
    fontWeight: '800',
  },
  price: {
    fontSize: 14,
    color: '#0097a9',
  },
});

type Props = {|
  price: number,
  currency: string,
  selectedCount: number,
  selectableCount: number,
  increment: () => void,
  decrement: () => void,
|};

export default function RoomPicker({
  price,
  currency,
  selectedCount,
  selectableCount,
  increment,
  decrement,
}: Props) {
  if (selectedCount === 0) {
    return (
      <NoneSelected price={price} currency={currency} onSelect={increment} />
    );
  }

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={[styles.button, styles.minusButton]}
        onPress={decrement}
      >
        <Text style={styles.buttonText}>-</Text>
      </TouchableOpacity>
      <View style={styles.priceAndCount}>
        <Text style={styles.count}>{selectedCount} × </Text>
        <Price amount={price} currency={currency} style={styles.price} />
      </View>
      {selectedCount < selectableCount ? (
        <TouchableOpacity
          style={[styles.button, styles.plusButton]}
          onPress={increment}
        >
          <Text style={styles.buttonText}>+</Text>
        </TouchableOpacity>
      ) : (
        <View style={[styles.disabledButton]} />
      )}
    </View>
  );
}
<commit_msg>Render disabled button as a lighter untouchable button<commit_after>// @flow
import * as React from 'react';
import { View, StyleSheet, Text, TouchableOpacity } from 'react-native';
import { Price } from '@kiwicom/react-native-app-common';
import NoneSelected from './NoneSelected';

const styles = StyleSheet.create({
  container: {
    borderRadius: 3,
    backgroundColor: 'rgba(0, 151, 169, 0.2)',
    flexDirection: 'row',
  },
  button: {
    backgroundColor: '#0097a9',
    width: 60,
    paddingVertical: 10,
    alignItems: 'center',
  },
  minusButton: {
    borderTopLeftRadius: 3,
    borderBottomLeftRadius: 3,
  },
  plusButton: {
    borderTopRightRadius: 3,
    borderBottomRightRadius: 3,
  },
  disabledButton: {
    opacity: 0.2,
  },
  buttonText: {
    backgroundColor: 'transparent',
    fontSize: 20,
    fontWeight: '600',
    color: '#ffffff',
  },
  priceAndCount: {
    flexGrow: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  count: {
    fontSize: 14,
    color: '#0097a9',
    fontWeight: '800',
  },
  price: {
    fontSize: 14,
    color: '#0097a9',
  },
});

type Props = {|
  price: number,
  currency: string,
  selectedCount: number,
  selectableCount: number,
  increment: () => void,
  decrement: () => void,
|};

export default function RoomPicker({
  price,
  currency,
  selectedCount,
  selectableCount,
  increment,
  decrement,
}: Props) {
  if (selectedCount === 0) {
    return (
      <NoneSelected price={price} currency={currency} onSelect={increment} />
    );
  }

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={[styles.button, styles.minusButton]}
        onPress={decrement}
      >
        <Text style={styles.buttonText}>-</Text>
      </TouchableOpacity>
      <View style={styles.priceAndCount}>
        <Text style={styles.count}>{selectedCount} × </Text>
        <Price amount={price} currency={currency} style={styles.price} />
      </View>
      {selectedCount < selectableCount ? (
        <TouchableOpacity
          style={[styles.button, styles.plusButton]}
          onPress={increment}
        >
          <Text style={styles.buttonText}>+</Text>
        </TouchableOpacity>
      ) : (
        <View style={[styles.button, styles.plusButton, styles.disabledButton]}>
          <Text style={styles.buttonText}>+</Text>
        </View>
      )}
    </View>
  );
}
<|endoftext|>