<commit_before>import mapbox from "mapbox-gl";
// import bbox from "@turf/bbox";
import _ from "lodash";

import "mapbox-gl/dist/mapbox-gl.css";

mapbox.accessToken = Meteor.settings.public.mapboxAccessToken;

Template.visGeoMap.onRendered(function() {
  const template = this;
  const container = template.find(".mapbox");
  let activeSettings = {};

  this.autorun(() => {
    const { settings, data } = Template.currentData();
    const hasChangedSettings = !_.isEqual(settings, activeSettings);
    activeSettings = settings;

    const { longField = "longitude", latField = "latitude" } = settings;

    const sources = _.chain(data)
      .groupBy(x => x[settings.catField] || "_default")
      .mapValues(arr => ({
        type: "FeatureCollection",
        features: arr.map(x => ({
          type: "Feature",
          properties: x,
          geometry: {
            type: "Point",
            coordinates: [x[longField], x[latField]]
          }
        }))
      }))
      .value();

    if (!this.map || hasChangedSettings) {
      // Map is new or settings have changed.
      if (this.map) {
        this.map.remove();
      }

      const map = new mapbox.Map({
        container,
        style: `mapbox://styles/mapbox/${settings.mapStyle || "streets"}-v9`,
        interactive: !!settings.interactive,
        bounds: settings.bounds // || bbox(geojson)
      });
      this.map = map;

      map.on("load", () => {
        _.forEach(sources, (data, key) => {
          map.addSource(key, { type: "geojson", data });
        });

        const layers = JSON.parse(settings.layersJson || "[]");
        if (layers.length) {
          layers.forEach(x => map.addLayer(x));
        }
      });
    } else {
      // Only data has changed, update sources.
      const map = this.map;
      _.forEach(sources, (data, key) => {
        const source = map.getSource(key);
        if (source) {
          source.setData(data);
        } else {
          map.addSource(key, { type: "geojson", data });
        }
      });
    }
  });
});
<commit_msg>FIXES geomaps to be more robust<commit_after>import mapbox from "mapbox-gl";
// import bbox from "@turf/bbox";
import _ from "lodash";

import "mapbox-gl/dist/mapbox-gl.css";

mapbox.accessToken = Meteor.settings.public.mapboxAccessToken;

Template.visGeoMap.onRendered(function() {
  const template = this;
  const container = template.find(".mapbox");
  let activeSettings = {};

  this.autorun(computation => {
    const { settings, data } = Template.currentData();
    const hasChangedSettings = !_.isEqual(settings, activeSettings);
    activeSettings = settings;

    const { longField = "longitude", latField = "latitude" } = settings;

    const sources = _.chain(data)
      .groupBy(x => x[settings.catField] || "_default")
      .mapValues(arr => ({
        type: "FeatureCollection",
        features: arr.map(x => ({
          type: "Feature",
          properties: x,
          geometry: {
            type: "Point",
            coordinates: [x[longField], x[latField]]
          }
        }))
      }))
      .value();

    if (!this.map || hasChangedSettings) {
      // Map is new or settings have changed.
      if (this.map) {
        this.map.remove();
      }

      const map = new mapbox.Map({
        container,
        style: `mapbox://styles/mapbox/${settings.mapStyle || "streets"}-v9`,
        interactive: !!settings.interactive,
        bounds: settings.bounds // || bbox(geojson)
      });
      this.map = map;

      map.on("load", () => {
        _.forEach(sources, (data, key) => {
          map.addSource(key, { type: "geojson", data });
        });

        const layers = JSON.parse(settings.layersJson || "[]");
        if (layers.length) {
          layers.forEach(layer => {
            // Make sure every layer has at least a dummy source.
            if (!map.getSource(layer.source)) {
              map.addSource(layer.source, {
                type: "geojson",
                data: {
                  type: "FeatureCollection",
                  features: []
                }
              });
            }
            map.addLayer(layer);
          });
        }
      });
    } else {
      // Only data has changed, update sources.
      const map = this.map;

      // Map isn't quite ready yet - wait a bit to rerun.
      if (!map.loaded) {
        setTimeout(() => {
          computation.invalidate();
        }, 200);
      }

      // Upsert all sources.
      _.forEach(sources, (data, key) => {
        const source = map.getSource(key);
        if (source) {
          source.setData(data);
        } else {
          map.addSource(key, { type: "geojson", data });
        }
      });
    }
  });
});
<|endoftext|>


<commit_before>GLClient.controller('ReceiverSidebarCtrl', ['$scope', '$location', function($scope, $location){
  var current_menu = $location.path().split('/').slice(-1);
  $scope.active = {};
  $scope.active[current_menu] = "active";
}]).
controller('ReceiverTipsCtrl', ['$scope',  '$http', '$route', '$location', '$uibModal', 'RTipExport', 'ReceiverTips',
  function($scope, $http, $route, $location, $uibModal, RTipExport, ReceiverTips) {
  $scope.tips = ReceiverTips.query();
  $scope.exportTip = RTipExport;

  $scope.selected_tips = [];

  $scope.select_all = function () {
    $scope.selected_tips = [];
    angular.forEach($scope.tips, function (tip) {
      $scope.selected_tips.push(tip.id);
    });
  };

  $scope.deselect_all = function () {
    $scope.selected_tips = [];
  };

  $scope.tip_switch = function (id) {
    var index = $scope.selected_tips.indexOf(id);
    if (index > -1) {
      $scope.selected_tips.splice(index, 1);
    } else {
      $scope.selected_tips.push(id);
    }
  };

  $scope.isSelected = function (id) {
    return $scope.selected_tips.indexOf(id) !== -1;
  };

  $scope.tip_delete_all = function () {
    $uibModal.open({
      templateUrl: 'views/partials/tip_operation_delete_selected.html',
      controller: 'TipBulkOperationsCtrl',
      resolve: {
        selected_tips: function () {
          return $scope.selected_tips;
        },
        operation: function() {
          return 'delete';
        }
      }
    });
  };

  $scope.tip_postpone_all = function () {
    $uibModal.open({
      templateUrl: 'views/partials/tip_operation_postpone_selected.html',
      controller: 'TipBulkOperationsCtrl',
      resolve: {
        selected_tips: function () {
          return $scope.selected_tips;
        },
        operation: function() {
          return 'postpone';
        }
      }
    });
  };
}]).
controller('TipBulkOperationsCtrl', ['$scope', '$http', '$route', '$location', '$uibModalInstance', 'selected_tips', 'operation',
                        function ($scope, $http, $route, $location, $uibModalInstance, selected_tips, operation) {
  $scope.selected_tips = selected_tips;
  $scope.operation = operation;

  $scope.cancel = function () {
    $uibModalInstance.close();
  };

  $scope.ok = function () {
     $uibModalInstance.close();

    if (['postpone', 'delete'].indexOf(operation) === -1) {
      return;
    }

    return $http({method: 'PUT', url: '/rtip/operations', data:{
      'operation': $scope.operation,
      'rtips': $scope.selected_tips
    }}).success(function(){
      $scope.selected_tips = [];
      $route.reload();
    });
  };
}]);
<commit_msg>Removal of old and never used ReceiverSidebarCtrl<commit_after>GLClient.controller('ReceiverTipsCtrl', ['$scope',  '$http', '$route', '$location', '$uibModal', 'RTipExport', 'ReceiverTips',
  function($scope, $http, $route, $location, $uibModal, RTipExport, ReceiverTips) {
  $scope.tips = ReceiverTips.query();
  $scope.exportTip = RTipExport;

  $scope.selected_tips = [];

  $scope.select_all = function () {
    $scope.selected_tips = [];
    angular.forEach($scope.tips, function (tip) {
      $scope.selected_tips.push(tip.id);
    });
  };

  $scope.deselect_all = function () {
    $scope.selected_tips = [];
  };

  $scope.tip_switch = function (id) {
    var index = $scope.selected_tips.indexOf(id);
    if (index > -1) {
      $scope.selected_tips.splice(index, 1);
    } else {
      $scope.selected_tips.push(id);
    }
  };

  $scope.isSelected = function (id) {
    return $scope.selected_tips.indexOf(id) !== -1;
  };

  $scope.tip_delete_all = function () {
    $uibModal.open({
      templateUrl: 'views/partials/tip_operation_delete_selected.html',
      controller: 'TipBulkOperationsCtrl',
      resolve: {
        selected_tips: function () {
          return $scope.selected_tips;
        },
        operation: function() {
          return 'delete';
        }
      }
    });
  };

  $scope.tip_postpone_all = function () {
    $uibModal.open({
      templateUrl: 'views/partials/tip_operation_postpone_selected.html',
      controller: 'TipBulkOperationsCtrl',
      resolve: {
        selected_tips: function () {
          return $scope.selected_tips;
        },
        operation: function() {
          return 'postpone';
        }
      }
    });
  };
}]).
controller('TipBulkOperationsCtrl', ['$scope', '$http', '$route', '$location', '$uibModalInstance', 'selected_tips', 'operation',
                        function ($scope, $http, $route, $location, $uibModalInstance, selected_tips, operation) {
  $scope.selected_tips = selected_tips;
  $scope.operation = operation;

  $scope.cancel = function () {
    $uibModalInstance.close();
  };

  $scope.ok = function () {
     $uibModalInstance.close();

    if (['postpone', 'delete'].indexOf(operation) === -1) {
      return;
    }

    return $http({method: 'PUT', url: '/rtip/operations', data:{
      'operation': $scope.operation,
      'rtips': $scope.selected_tips
    }}).success(function(){
      $scope.selected_tips = [];
      $route.reload();
    });
  };
}]);
<|endoftext|>


<commit_before>angular.
  module('MatWeb').
  config(['$locationProvider', '$routeProvider', '$httpProvider',
    function config($locationProvider, $routeProvider, $httpProvider) {
      $locationProvider.html5Mode(true).hashPrefix('!');

      $httpProvider.defaults.headers.common.Authorization = ""
      $httpProvider.defaults.headers.post = { 'Content-Type' : 'application/json; charset=UTF-8' }

      $routeProvider.when('/Usuario/Entrar', {
          template: '<usuario-entrar></usuario-entrar>'
        }).otherwise('/');
    }
  ]);<commit_msg>teste frontend<commit_after>angular.
  module('MatWeb').
  config(['$locationProvider', '$routeProvider', '$httpProvider',
    function config($locationProvider, $routeProvider, $httpProvider) {
      $locationProvider.html5Mode(true).hashPrefix('!');

      $httpProvider.defaults.headers.common.Authorization = ""
      $httpProvider.defaults.headers.post = { 'Content-Type' : 'application/json; charset=UTF-8' }

      $routeProvider.when('/Usuario/Entrar', {
          template: '<usuario-entrar></usuario-entrar>'
        })
      .when('/Usuario/Entrar2', {
          template: '<usuario-entrar></usuario-entrar>'
        })
      .otherwise('/');
    }
  ]);<|endoftext|>


<commit_before>// Component to list locations events in chunks
//
var template = require('./template.ejs');
var emitter = require('component-emitter');
var renderEvent = require('../Events/renderEvent');
var ui = require('georap-ui');
var __ = georap.i18n.__;

module.exports = function (fetch, opts) {
  // Parameters:
  //   fetch
  //     function (skip, limit, callback)
  //       skip
  //         integer
  //       limit
  //         integer
  //       callback
  //         function (err, events)
  //           err
  //           events
  //             array of event objects
  //   opts, optional object with props
  //     listSize
  //       integer, default 50, number of events per load
  //     showThumbnails
  //       boolean, default false,
  //

  // Handle parameters
  if (!opts) {
    opts = {};
  }
  opts = Object.assign({
    listSize: 50,
    showThumbnails: false,
  }, opts);

  // Init
  var $mount = null;
  var $elems = {};
  var self = this;
  emitter(self);

  // Chunks
  var skip = 0;
  var limit = opts.listSize;

  // Public methods

  this.bind = function ($mountEl) {
    $mount = $mountEl;
    $mount.html(template({
      __: __,
    }));

    $elems.events = $mount.find('.events-group');
    $elems.more = $mount.find('.events-more');
    $elems.progress = $mount.find('.events-progress');
    $elems.error = $mount.find('.events-error');

    var doFetch = function () {
      ui.hide($elems.more);
      ui.show($elems.progress);

      fetch(skip, limit + 1, function (err, events) {
        ui.hide($elems.progress);

        if (err) {
          $elems.error.html(err.message);
          ui.show($elems.error);
          return;
        }

        events.slice(0, limit).forEach(function (ev) {
          $elems.events.append(renderEvent(ev, opts));
        });

        if (events.length > limit) {
          // More events are available
          ui.show($elems.more);
        }
      });
    };

    $elems.more.click(function (cev) {
      cev.preventDefault();
      skip += opts.listSize;
      doFetch();
    });

    // Initial fetch
    doFetch();
  };

  this.append = function (newEvent) {
    if ($mount) {
      $elems.events.append(renderEvent(newEvent, opts));
    }
  };

  this.prepend = function (newEvent) {
    if ($mount) {
      $elems.events.prepend(renderEvent(newEvent, opts));
    }
  };

  this.unbind = function () {
    if ($mount) {
      $mount = null;
      ui.offAll($elems);
      $elems = {};
    }
  };
};
<commit_msg>opts.eventFilter for EventsMore for correct more logic<commit_after>// Component to list locations events in chunks
//
var template = require('./template.ejs');
var emitter = require('component-emitter');
var renderEvent = require('../Events/renderEvent');
var ui = require('georap-ui');
var __ = georap.i18n.__;

var noFilter = function (evs) {
  return evs;
};

module.exports = function (fetch, opts) {
  // Parameters:
  //   fetch
  //     function (skip, limit, callback)
  //       skip
  //         integer
  //       limit
  //         integer
  //       callback
  //         function (err, events)
  //           err
  //           events
  //             array of event objects
  //   opts, optional object with optional props
  //     listSize
  //       integer, default 50, number of events per load
  //     showThumbnails
  //       boolean, default false,
  //     eventFilter
  //       function (evs), a filter to hide certain events
  //
  // Note that fetch fn should not attempt to filter events because
  // it can interfere with more detection. Set opts.eventFilter if
  // any filtering is necessary.
  //

  // Handle parameters
  if (!opts) {
    opts = {};
  }
  opts = Object.assign({
    listSize: 50,
    showThumbnails: false,
    eventFilter: noFilter,
  }, opts);

  // Init
  var $mount = null;
  var $elems = {};
  var self = this;
  emitter(self);

  // Chunks
  var skip = 0;
  var limit = opts.listSize;

  // Public methods

  this.bind = function ($mountEl) {
    $mount = $mountEl;
    $mount.html(template({
      __: __,
    }));

    $elems.events = $mount.find('.events-group');
    $elems.more = $mount.find('.events-more');
    $elems.progress = $mount.find('.events-progress');
    $elems.error = $mount.find('.events-error');

    var doFetch = function () {
      ui.hide($elems.more);
      ui.show($elems.progress);

      fetch(skip, limit + 1, function (err, events) {
        ui.hide($elems.progress);

        if (err) {
          $elems.error.html(err.message);
          ui.show($elems.error);
          return;
        }

        // Remove the extra item and apply given event filter.
        var prettyEvs = opts.eventFilter(events.slice(0, limit));

        prettyEvs.forEach(function (ev) {
          $elems.events.append(renderEvent(ev, opts));
        });

        if (events.length > limit) {
          // More events are available
          ui.show($elems.more);
        }
      });
    };

    $elems.more.click(function (cev) {
      cev.preventDefault();
      skip += opts.listSize;
      doFetch();
    });

    // Initial fetch
    doFetch();
  };

  this.append = function (newEvent) {
    if ($mount) {
      $elems.events.append(renderEvent(newEvent, opts));
    }
  };

  this.prepend = function (newEvent) {
    if ($mount) {
      $elems.events.prepend(renderEvent(newEvent, opts));
    }
  };

  this.unbind = function () {
    if ($mount) {
      $mount = null;
      ui.offAll($elems);
      $elems = {};
    }
  };
};
<|endoftext|>


<commit_before>/**
 * Modal
 */
Garnish.Modal = Garnish.Base.extend({

	$container: null,
	$shade: null,

	visible: false,

	dragger: null,

	desiredWidth: null,
	desiredHeight: null,
	resizeDragger: null,
	resizeStartWidth: null,
	resizeStartHeight: null,

	init: function(container, settings)
	{
		// Param mapping
		if (!settings && $.isPlainObject(container))
		{
			// (settings)
			settings = container;
            container = null;
		}

		this.setSettings(settings, Garnish.Modal.defaults);

        // If container already set, drop the shade below it.
        if (container)
        {
            this.$shade = $('
').insertBefore(container);
        }
        else
        {
            this.$shade = $('
').appendTo(Garnish.$bod);
        }

        if (container)
		{
			this.setContainer(container);
			this.show();
		}

		Garnish.Modal.instances.push(this);
	},

	setContainer: function(container)
	{
		this.$container = $(container);

		// Is this already a modal?
		if (this.$container.data('modal'))
		{
			Garnish.log('Double-instantiating a modal on an element');
			this.$container.data('modal').destroy();
		}

		this.$container.data('modal', this);

		if (this.settings.draggable)
		{
			this.dragger = new Garnish.DragMove(this.$container, {
				handle: (this.settings.dragHandleSelector ? this.$container.find(this.settings.dragHandleSelector) : this.$container)
			});
		}

		if (this.settings.resizable)
		{
			var $resizeDragHandle = $('
').appendTo(this.$container);

			this.resizeDragger = new Garnish.BaseDrag($resizeDragHandle, {
				onDragStart:   $.proxy(this, '_onResizeStart'),
				onDrag:        $.proxy(this, '_onResize')
			});
		}

		this.addListener(this.$container, 'click', function(ev) {
			ev.stopPropagation();
		});

		// Show it if we're late to the party
		if (this.visible)
		{
			this.show();
		}
	},

	show: function()
	{
        // Close other modals as needed
		if (this.settings.closeOtherModals && Garnish.Modal.visibleModal && Garnish.Modal.visibleModal != this)
		{
			Garnish.Modal.visibleModal.hide();
		}

		if (this.$container)
		{
			// Move it to the end of  so it gets the highest sub-z-index
			this.$shade.appendTo(Garnish.$bod);
			this.$container.appendTo(Garnish.$bod);

			this.$container.show();
			this.updateSizeAndPosition();

			this.$shade.fadeIn(50);
			this.$container.delay(50).fadeIn($.proxy(this, 'onFadeIn'));

			this.addListener(this.$shade, 'click', 'hide');
			this.addListener(Garnish.$win, 'resize', 'updateSizeAndPosition');
		}

		Garnish.escManager.register(this, 'hide');

		if (!this.visible)
		{
			this.visible = true;
			Garnish.Modal.visibleModal = this;

			this.settings.onShow();
		}
	},

	hide: function(ev)
	{
		if (ev)
		{
			ev.stopPropagation();
		}

		if (this.$container)
		{
			this.$container.fadeOut('fast');
			this.$shade.fadeOut('fast', $.proxy(this, 'onFadeOut'));

			this.removeListener(this.$shade, 'click');
			this.removeListener(Garnish.$win, 'resize');
		}

		this.visible = false;
		Garnish.Modal.visibleModal = null;
		Garnish.escManager.unregister(this);
		this.settings.onHide();
	},

	updateSizeAndPosition: function()
	{
		if (!this.$container)
		{
			return;
		}

		this.$container.css({
			'width':      (this.desiredWidth ? Math.max(this.desiredWidth, 200) : ''),
			'height':     (this.desiredHeight ? Math.max(this.desiredHeight, 200) : ''),
			'min-width':  '',
			'min-height': ''
		});

		// Set the width first so that the height can adjust for the width
		this.updateSizeAndPosition._windowWidth = Garnish.$win.width();
		this.updateSizeAndPosition._width = Math.min(this.getWidth(), this.updateSizeAndPosition._windowWidth - 20);

		this.$container.css({
			'width':      this.updateSizeAndPosition._width,
			'min-width':  this.updateSizeAndPosition._width,
			'left':       Math.round((this.updateSizeAndPosition._windowWidth - this.updateSizeAndPosition._width) / 2)
		});

		// Now set the height
		this.updateSizeAndPosition._windowHeight = Garnish.$win.height();
		this.updateSizeAndPosition._height = Math.min(this.getHeight(), this.updateSizeAndPosition._windowHeight - 20);

		this.$container.css({
			'height':     this.updateSizeAndPosition._height,
			'min-height': this.updateSizeAndPosition._height,
			'top':        Math.round((this.updateSizeAndPosition._windowHeight - this.updateSizeAndPosition._height) / 2)
		});
	},

	onFadeIn: function()
	{
		this.settings.onFadeIn();
	},

	onFadeOut: function()
	{
		this.settings.onFadeOut();
	},

	getHeight: function()
	{
		if (!this.$container)
		{
			throw 'Attempted to get the height of a modal whose container has not been set.';
		}

		if (!this.visible)
		{
			this.$container.show();
		}

		this.getHeight._height = this.$container.outerHeight();

		if (!this.visible)
		{
			this.$container.hide();
		}

		return this.getHeight._height;
	},

	getWidth: function()
	{
		if (!this.$container)
		{
			throw 'Attempted to get the width of a modal whose container has not been set.';
		}

		if (!this.visible)
		{
			this.$container.show();
		}

		this.getWidth._width = this.$container.outerWidth();

		if (!this.visible)
		{
			this.$container.hide();
		}

		return this.getWidth._width;
	},

	_onResizeStart: function()
	{
		this.resizeStartWidth = this.getWidth();
		this.resizeStartHeight = this.getHeight();
	},

	_onResize: function()
	{
		if (Garnish.ltr)
		{
			this.desiredWidth = this.resizeStartWidth + (this.resizeDragger.mouseDistX * 2);
			this.desiredHeight = this.resizeStartHeight + (this.resizeDragger.mouseDistY * 2);
		}
		else
		{
			this.desiredWidth = this.resizeStartWidth - (this.resizeDragger.mouseDistX * 2);
			this.desiredHeight = this.resizeStartHeight - (this.resizeDragger.mouseDistY * 2);
		}

		this.updateSizeAndPosition();
	},

	destroy: function()
	{
		this.base();

		if (this.dragger)
		{
			this.dragger.destroy();
		}

		if (this.resizeDragger)
		{
			this.resizeDragger.destroy();
		}
	}
},
{
	relativeElemPadding: 8,
	defaults: {
		draggable: false,
		dragHandleSelector: null,
		resizable: false,
		onShow: $.noop,
		onHide: $.noop,
		onFadeIn: $.noop,
		onFadeOut: $.noop,
        closeOtherModals: true
	},
	instances: [],
	visibleModal: null
});
<commit_msg>Fixed a bug where modal height resizing was getting reversed when in RTL mode<commit_after>/**
 * Modal
 */
Garnish.Modal = Garnish.Base.extend({

	$container: null,
	$shade: null,

	visible: false,

	dragger: null,

	desiredWidth: null,
	desiredHeight: null,
	resizeDragger: null,
	resizeStartWidth: null,
	resizeStartHeight: null,

	init: function(container, settings)
	{
		// Param mapping
		if (!settings && $.isPlainObject(container))
		{
			// (settings)
			settings = container;
            container = null;
		}

		this.setSettings(settings, Garnish.Modal.defaults);

        // If container already set, drop the shade below it.
        if (container)
        {
            this.$shade = $('
').insertBefore(container);
        }
        else
        {
            this.$shade = $('
').appendTo(Garnish.$bod);
        }

        if (container)
		{
			this.setContainer(container);
			this.show();
		}

		Garnish.Modal.instances.push(this);
	},

	setContainer: function(container)
	{
		this.$container = $(container);

		// Is this already a modal?
		if (this.$container.data('modal'))
		{
			Garnish.log('Double-instantiating a modal on an element');
			this.$container.data('modal').destroy();
		}

		this.$container.data('modal', this);

		if (this.settings.draggable)
		{
			this.dragger = new Garnish.DragMove(this.$container, {
				handle: (this.settings.dragHandleSelector ? this.$container.find(this.settings.dragHandleSelector) : this.$container)
			});
		}

		if (this.settings.resizable)
		{
			var $resizeDragHandle = $('
').appendTo(this.$container);

			this.resizeDragger = new Garnish.BaseDrag($resizeDragHandle, {
				onDragStart:   $.proxy(this, '_onResizeStart'),
				onDrag:        $.proxy(this, '_onResize')
			});
		}

		this.addListener(this.$container, 'click', function(ev) {
			ev.stopPropagation();
		});

		// Show it if we're late to the party
		if (this.visible)
		{
			this.show();
		}
	},

	show: function()
	{
        // Close other modals as needed
		if (this.settings.closeOtherModals && Garnish.Modal.visibleModal && Garnish.Modal.visibleModal != this)
		{
			Garnish.Modal.visibleModal.hide();
		}

		if (this.$container)
		{
			// Move it to the end of  so it gets the highest sub-z-index
			this.$shade.appendTo(Garnish.$bod);
			this.$container.appendTo(Garnish.$bod);

			this.$container.show();
			this.updateSizeAndPosition();

			this.$shade.fadeIn(50);
			this.$container.delay(50).fadeIn($.proxy(this, 'onFadeIn'));

			this.addListener(this.$shade, 'click', 'hide');
			this.addListener(Garnish.$win, 'resize', 'updateSizeAndPosition');
		}

		Garnish.escManager.register(this, 'hide');

		if (!this.visible)
		{
			this.visible = true;
			Garnish.Modal.visibleModal = this;

			this.settings.onShow();
		}
	},

	hide: function(ev)
	{
		if (ev)
		{
			ev.stopPropagation();
		}

		if (this.$container)
		{
			this.$container.fadeOut('fast');
			this.$shade.fadeOut('fast', $.proxy(this, 'onFadeOut'));

			this.removeListener(this.$shade, 'click');
			this.removeListener(Garnish.$win, 'resize');
		}

		this.visible = false;
		Garnish.Modal.visibleModal = null;
		Garnish.escManager.unregister(this);
		this.settings.onHide();
	},

	updateSizeAndPosition: function()
	{
		if (!this.$container)
		{
			return;
		}

		this.$container.css({
			'width':      (this.desiredWidth ? Math.max(this.desiredWidth, 200) : ''),
			'height':     (this.desiredHeight ? Math.max(this.desiredHeight, 200) : ''),
			'min-width':  '',
			'min-height': ''
		});

		// Set the width first so that the height can adjust for the width
		this.updateSizeAndPosition._windowWidth = Garnish.$win.width();
		this.updateSizeAndPosition._width = Math.min(this.getWidth(), this.updateSizeAndPosition._windowWidth - 20);

		this.$container.css({
			'width':      this.updateSizeAndPosition._width,
			'min-width':  this.updateSizeAndPosition._width,
			'left':       Math.round((this.updateSizeAndPosition._windowWidth - this.updateSizeAndPosition._width) / 2)
		});

		// Now set the height
		this.updateSizeAndPosition._windowHeight = Garnish.$win.height();
		this.updateSizeAndPosition._height = Math.min(this.getHeight(), this.updateSizeAndPosition._windowHeight - 20);

		this.$container.css({
			'height':     this.updateSizeAndPosition._height,
			'min-height': this.updateSizeAndPosition._height,
			'top':        Math.round((this.updateSizeAndPosition._windowHeight - this.updateSizeAndPosition._height) / 2)
		});
	},

	onFadeIn: function()
	{
		this.settings.onFadeIn();
	},

	onFadeOut: function()
	{
		this.settings.onFadeOut();
	},

	getHeight: function()
	{
		if (!this.$container)
		{
			throw 'Attempted to get the height of a modal whose container has not been set.';
		}

		if (!this.visible)
		{
			this.$container.show();
		}

		this.getHeight._height = this.$container.outerHeight();

		if (!this.visible)
		{
			this.$container.hide();
		}

		return this.getHeight._height;
	},

	getWidth: function()
	{
		if (!this.$container)
		{
			throw 'Attempted to get the width of a modal whose container has not been set.';
		}

		if (!this.visible)
		{
			this.$container.show();
		}

		this.getWidth._width = this.$container.outerWidth();

		if (!this.visible)
		{
			this.$container.hide();
		}

		return this.getWidth._width;
	},

	_onResizeStart: function()
	{
		this.resizeStartWidth = this.getWidth();
		this.resizeStartHeight = this.getHeight();
	},

	_onResize: function()
	{
		if (Garnish.ltr)
		{
			this.desiredWidth = this.resizeStartWidth + (this.resizeDragger.mouseDistX * 2);
		}
		else
		{
			this.desiredWidth = this.resizeStartWidth - (this.resizeDragger.mouseDistX * 2);
		}

		this.desiredHeight = this.resizeStartHeight + (this.resizeDragger.mouseDistY * 2);

		this.updateSizeAndPosition();
	},

	destroy: function()
	{
		this.base();

		if (this.dragger)
		{
			this.dragger.destroy();
		}

		if (this.resizeDragger)
		{
			this.resizeDragger.destroy();
		}
	}
},
{
	relativeElemPadding: 8,
	defaults: {
		draggable: false,
		dragHandleSelector: null,
		resizable: false,
		onShow: $.noop,
		onHide: $.noop,
		onFadeIn: $.noop,
		onFadeOut: $.noop,
        closeOtherModals: true
	},
	instances: [],
	visibleModal: null
});
<|endoftext|>


<commit_before>	function getUser() {
		var xhttp = new XMLHttpRequest();
		xhttp.open("GET", "http://ec2-34-208-19-115.us-west-2.compute.amazonaws.com:18080/player/rob", false); //find a way to set async to true and have it return when it has something
		xhttp.setRequestHeader("Content-type", "text/plain");
		xhttp.send();
		var response = JSON.stringify(xhttp.responseText);
		console.log(response);
		return response;
	}
	document.getElementById("user").innerHTML = getUser();<commit_msg><commit_after>
var DnDObj = getUser();

function getUserText() {
	var xhttp = new XMLHttpRequest();
	xhttp.open("GET", "http://ec2-34-208-19-115.us-west-2.compute.amazonaws.com:18080/player/rob", false); //find a way to set async to true and have it return when it has something
	xhttp.setRequestHeader("Content-type", "text/plain");
	xhttp.send();
	var response = JSON.stringify(xhttp.responseText);
	console.log(response);
	return response;
}

function getUser() {
	var xhttp = new XMLHttpRequest();
	xhttp.open("GET", "http://ec2-34-208-19-115.us-west-2.compute.amazonaws.com:18080/player/rob", false); //find a way to set async to true and have it return when it has something
	xhttp.setRequestHeader("Content-type", "text/plain");
	xhttp.send();
	var response = JSON.parse(xhttp.responseText);
	console.log(response);
	return response;
}
<|endoftext|>


<commit_before>/**
 * Main application routes
 */

'use strict';

var errors = require('./components/errors');

module.exports = function(app) {

  // Insert routes below
  app.use('/api/things', require('./api/thing'));
  app.use('/api/users', require('./api/user'));
  app.use('/api/profile', require('./api/profile'));

  app.use('/auth', require('./auth'));

  // All undefined asset or api routes should return a 404
  app.route('/:url(api|auth|components|app|bower_components|assets)/*')
   .get(errors[404]);

    var express = require("express");

    app.use('/node_modules', express.static('node_modules'));

  // All other routes should redirect to the index.html
   app.route('/*')
     .get(function(req, res) {
       res.sendfile(app.get('appPath') + '/index.html');
     });
};
<commit_msg>remove `thing` route<commit_after>/**
 * Main application routes
 */

'use strict';

var errors = require('./components/errors');

module.exports = function(app) {

  // Insert routes below
  app.use('/api/users', require('./api/user'));
  app.use('/api/profile', require('./api/profile'));

  app.use('/auth', require('./auth'));

  // All undefined asset or api routes should return a 404
  app.route('/:url(api|auth|components|app|bower_components|assets)/*')
   .get(errors[404]);

    var express = require("express");

    app.use('/node_modules', express.static('node_modules'));

  // All other routes should redirect to the index.html
   app.route('/*')
     .get(function(req, res) {
       res.sendfile(app.get('appPath') + '/index.html');
     });
};
<|endoftext|>


<commit_before>import {BottomNavigation, BottomNavigationItem} from 'material-ui/BottomNavigation';
import React, { Component } from 'react';

import './index.css'
import kitwareLogo from './Kitware_Full_Logo.png';
import strobeLogo from './strobe.png';
import uclaLogo from './ucla.png';
import berkeleyLogo from './berkeley.jpg';

const style = {
  position: 'fixed',
  bottom: '20px'
}

export default class Footer extends Component {
  render = () => {
    return (
        <BottomNavigation style={style}>
          <BottomNavigationItem
            icon={}
            onClick={() => this.select(0)} href="http://www.kitware.com"
          />
          <BottomNavigationItem
            icon={}
              onClick={() => this.select(0)} href="http://strobe.colorado.edu/"
          />
          <BottomNavigationItem
            icon={}
            onClick={() => this.select(0)} href="http://www.ucla.edu/"
          />
          <BottomNavigationItem
            icon={}
            onClick={() => this.select(0)} href="http://www.lbl.gov/"
          />
      </BottomNavigation>
    );
  }
}
<commit_msg>Remove logo<commit_after>import {BottomNavigation, BottomNavigationItem} from 'material-ui/BottomNavigation';
import React, { Component } from 'react';

import './index.css'
import kitwareLogo from './Kitware_Full_Logo.png';
import strobeLogo from './strobe.png';
import uclaLogo from './ucla.png';
import berkeleyLogo from './berkeley.jpg';

const style = {
  position: 'fixed',
  bottom: '20px'
}

export default class Footer extends Component {
  render = () => {
    return (
        <BottomNavigation style={style}>
          <BottomNavigationItem
            icon={}
            onClick={() => this.select(0)} href="http://www.kitware.com"
          />
          <BottomNavigationItem
            icon={}
              onClick={() => this.select(0)} href="http://strobe.colorado.edu/"
          />
          <BottomNavigationItem
            icon={}
            onClick={() => this.select(0)} href="http://www.lbl.gov/"
          />
      </BottomNavigation>
    );
  }
}
<|endoftext|>


<commit_before>angular.module(PKG.name + '.feature.etlapps')
  .controller('ETLAppsCreateController', function($scope, MyDataSource, $filter, $alert, $bootstrapModal, $state) {
    var filterFilter = $filter('filter');
    var dataSrc = new MyDataSource($scope);

    // Loading flag to indicate source & sinks have
    // not been loaded yet (after/before choosing an etl template)
    $scope.loadingEtlSourceProps = false;
    $scope.loadingEtlSinkProps = false;

    // List of ETL Sources, Sinks & Transforms
    // for a particular etl template type fetched from backend.
    $scope.etlSources = [];
    $scope.etlSinks = [];
    $scope.etlTransforms = [];

    // Default ETL Templates
    $scope.etlTypes = [
      {
        name: 'Etl Batch',
        type: 'etlbatch'
      },
      {
        name: 'ETL Real Time',
        type: 'realtime'
      }
    ];

    // Metadata Model
    $scope.metadata = {
        name: '',
        description: '',
        type: ''
    };

    // Source, Sink and Transform Models
    $scope.source = {
      name: '',
      properties: {}
    };

    $scope.sink = {
      name: '',
      properties: {}
    };

    $scope.transforms = [];
    $scope.activePanel = 0;

    $scope.$watch('metadata.type',function(etlType) {
      fetchSources(etlType);
      fetchSinks(etlType);
      fetchTransforms(etlType);
    });

    function fetchSources(etlType) {
      if (!etlType) return;
      dataSrc.request({
        _cdapPath: '/templates/etl.' + etlType + '/sources'
      })
        .then(function(res) {
          $scope.etlSources = res;
        });
    }

    function fetchSinks(etlType) {
      dataSrc.request({
        _cdapPath: '/templates/etl.'+ etlType + '/sinks'
      })
        .then(function(res) {
          $scope.etlSinks = res;
        });
    }

    function fetchTransforms(etlType) {
      dataSrc.request({
        _cdapPath: '/templates/etl.' + etlType + '/transforms'
      })
        .then(function(res) {
          $scope.etlTransforms = res;
        });
    }

    function fetchSourceProperties(etlSource) {
      if (!etlSource) return;
      dataSrc.request({
        _cdapPath: '/templates/etl.' + $scope.metadata.type + '/sources/' + etlSource
      })
        .then(function(res) {
          $scope.source.name = res.name;
          var obj = {};
          angular.forEach(res.properties, function(property) {
            obj[property.name] = '';
          });
          $scope.source.properties = obj;
          $scope.loadingEtlSourceProps = false;
        });
      $scope.loadingEtlSourceProps = etlSource || false;
    }

    function fetchSinkProperties(etlSink){
      if (!etlSink) return;
      dataSrc.request({
        _cdapPath: '/templates/etl.' + $scope.metadata.type + '/sinks/' + etlSink
      })
        .then(function(res) {
          $scope.sink.name = res.name;
          var obj = {};
          angular.forEach(res.properties, function(property) {
            obj[property.name] = '';
          });
          $scope.sink.properties = obj;
          $scope.loadingEtlSinkProps = false;
        });
      $scope.loadingEtlSinkProps = etlSink || false;
    }

    $scope.$watchCollection('transforms', function(newVal) {
      console.log("Transform Collection Watch", newVal);
    })

    $scope.handleSourceDrop = function(id, dropZone, sourceName) {
      if (dropZone.indexOf('source') === -1) {
        $alert({
          type: 'danger',
          content: 'Boink! You are not adding a source to a Source!'
        });
      } else {
        $alert({
          type: 'success',
          content: 'You have added a Source!!'
        });
        $scope.source.name = sourceName;
        fetchSourceProperties(sourceName);
      }
    };
    $scope.handleTransformDrop = function(id, dropZone, transformName) {
      if (dropZone.indexOf('transform') === -1) {
        $alert({
          type: 'danger',
          content: 'Boink! You are not adding a source to a Transform!'
        });
      } else {
        $alert({
          type: 'success',
          content: 'You have dropped a transform!'
        });
        $scope.transforms.push({
          name: transformName,
          properties: {}
        });
        // fetchSourceProperties(sourceName);
      }
    };
    $scope.handleSinkDrop = function(id, dropZone, sinkName) {
      if (dropZone.indexOf('sink') === -1) {
        $alert({
          type: 'danger',
          content: 'Boink! You are not adding a source to a Sink!'
        });
      } else {
        $alert({
          type: 'success',
          content: 'You have dropped a sink!'
        });
        $scope.sink.name = sinkName;
        fetchSinkProperties(sinkName);
      }
    };

    $scope.editSourceProperties = function() {
      if ($scope.source.name === '') {
        return;
      }
      $bootstrapModal.open({
        templateUrl: '/assets/features/etlapps/templates/create/sourceProperties.html',
        scope: $scope,
        backdrop: true,
        keyboard: true
      });
    };
    $scope.editSinkProperties = function() {
      if ($scope.sink.name === '') {
        return;
      }
      $bootstrapModal.open({
        templateUrl: '/assets/features/etlapps/templates/create/sinkProperties.html',
        scope: $scope,
        backdrop: true,
        keyboard: true

      });
    };
    $scope.editTransformProperties = function() {
      if ($scope.transforms.length === 0) {
        return;
      }
      $bootstrapModal.open({
        templateUrl: '/assets/features/etlapps/templates/create/transformProperties.html',
        scope: $scope,
        size: 'lg',
        backdrop: true,
        keyboard: true

      });
    };
  });
<commit_msg>Adds fetching properties for transform + save adapter to backend (not fully functional yet)<commit_after>angular.module(PKG.name + '.feature.etlapps')
  .controller('ETLAppsCreateController', function($scope, MyDataSource, $filter, $alert, $bootstrapModal, $state) {
    var filterFilter = $filter('filter');
    var dataSrc = new MyDataSource($scope);

    // Loading flag to indicate source & sinks have
    // not been loaded yet (after/before choosing an etl template)
    $scope.loadingEtlSourceProps = false;
    $scope.loadingEtlSinkProps = false;

    // List of ETL Sources, Sinks & Transforms
    // for a particular etl template type fetched from backend.
    $scope.etlSources = [];
    $scope.etlSinks = [];
    $scope.etlTransforms = [];

    // Default ETL Templates
    $scope.etlTypes = [
      {
        name: 'Etl Batch',
        type: 'etlbatch'
      },
      {
        name: 'ETL Real Time',
        type: 'realtime'
      }
    ];

    // Metadata Model
    $scope.metadata = {
        name: '',
        description: '',
        type: ''
    };

    // Source, Sink and Transform Models
    $scope.source = {
      name: '',
      properties: {}
    };

    $scope.sink = {
      name: '',
      properties: {}
    };

    $scope.transforms = [];
    $scope.activePanel = 0;

    $scope.$watch('metadata.type',function(etlType) {
      fetchSources(etlType);
      fetchSinks(etlType);
      fetchTransforms(etlType);
    });

    function fetchSources(etlType) {
      if (!etlType) return;
      dataSrc.request({
        _cdapPath: '/templates/etl.' + etlType + '/sources'
      })
        .then(function(res) {
          $scope.etlSources = res;
        });
    }

    function fetchSinks(etlType) {
      dataSrc.request({
        _cdapPath: '/templates/etl.'+ etlType + '/sinks'
      })
        .then(function(res) {
          $scope.etlSinks = res;
        });
    }

    function fetchTransforms(etlType) {
      dataSrc.request({
        _cdapPath: '/templates/etl.' + etlType + '/transforms'
      })
        .then(function(res) {
          $scope.etlTransforms = res;
        });
    }

    function fetchSourceProperties(etlSource) {
      if (!etlSource) return;
      dataSrc.request({
        _cdapPath: '/templates/etl.' + $scope.metadata.type + '/sources/' + etlSource
      })
        .then(function(res) {
          $scope.source.name = res.name;
          var obj = {};
          angular.forEach(res.properties, function(property) {
            obj[property.name] = '';
          });
          $scope.source.properties = obj;
          $scope.loadingEtlSourceProps = false;
        });
      $scope.loadingEtlSourceProps = etlSource || false;
    }

    function fetchSinkProperties(etlSink){
      if (!etlSink) return;
      dataSrc.request({
        _cdapPath: '/templates/etl.' + $scope.metadata.type + '/sinks/' + etlSink
      })
        .then(function(res) {
          $scope.sink.name = res.name;
          var obj = {};
          angular.forEach(res.properties, function(property) {
            obj[property.name] = '';
          });
          $scope.sink.properties = obj;
          $scope.loadingEtlSinkProps = false;
        });
      $scope.loadingEtlSinkProps = etlSink || false;
    }

    function fetchTransformProperties(etlTransform) {
      if(!etlTransform) return;
      dataSrc.request({
        _cdapPath: '/templates/etl.' + $scope.metadata.type + '/transforms/' + etlTransform
      })
        .then(function(res) {
          var obj = {};
          var match = filterFilter($scope.transforms, {name: res.name});
          if(match.length) {
            angular.forEach(res.properties, function(property) {
              obj[property.name] = '';
            });
            match[0].properties = obj;
          }
          $scope.transforms[$scope.transforms.indexOf(match[0])].properties = obj;
        });
    }

    $scope.handleSourceDrop = function(id, dropZone, sourceName) {
      if (dropZone.indexOf('source') === -1) {
        $alert({
          type: 'danger',
          content: 'Boink! You are not adding a source to a Source!'
        });
      } else {
        $alert({
          type: 'success',
          content: 'You have added a Source!!'
        });
        $scope.source.name = sourceName;
        fetchSourceProperties(sourceName);
      }
    };
    $scope.handleTransformDrop = function(id, dropZone, transformName) {
      if (dropZone.indexOf('transform') === -1) {
        $alert({
          type: 'danger',
          content: 'Boink! You are not adding a source to a Transform!'
        });
      } else {
        $alert({
          type: 'success',
          content: 'You have dropped a transform!'
        });
        $scope.transforms.push({
          name: transformName,
          properties: {}
        });
        fetchTransformProperties(transformName);
      }
    };
    $scope.handleSinkDrop = function(id, dropZone, sinkName) {
      if (dropZone.indexOf('sink') === -1) {
        $alert({
          type: 'danger',
          content: 'Boink! You are not adding a source to a Sink!'
        });
      } else {
        $alert({
          type: 'success',
          content: 'You have dropped a sink!'
        });
        $scope.sink.name = sinkName;
        fetchSinkProperties(sinkName);
      }
    };

    $scope.editSourceProperties = function() {
      if ($scope.source.name === '') {
        return;
      }
      $bootstrapModal.open({
        templateUrl: '/assets/features/etlapps/templates/create/sourceProperties.html',
        scope: $scope,
        backdrop: true,
        keyboard: true
      });
    };
    $scope.editSinkProperties = function() {
      if ($scope.sink.name === '') {
        return;
      }
      $bootstrapModal.open({
        templateUrl: '/assets/features/etlapps/templates/create/sinkProperties.html',
        scope: $scope,
        backdrop: true,
        keyboard: true

      });
    };
    $scope.editTransformProperties = function() {
      if ($scope.transforms.length === 0) {
        return;
      }
      $bootstrapModal.open({
        templateUrl: '/assets/features/etlapps/templates/create/transformProperties.html',
        scope: $scope,
        size: 'lg',
        backdrop: true,
        keyboard: true

      });
    };
    $scope.doSave = function() {
      var data = {
        template: $scope.metadata.type,
        config: {
          source: $scope.source,
          sink: $scope.sink,
          transforms: $scope.transforms
        }
      };

      dataSrc.request({
        method: 'PUT',
        _cdapPath: '/namespaces/'
                    + $state.params.namespace +
                    '/adapters/' +
                    $scope.metadata.name,
        body: data
      })
        .then(function(res) {
          $state.go('etlapps.list', $state.params, {reload: true});
          $alert({
            type: 'success',
            content: 'ETL Template: ' + $scope.metata.name + ' created successfully!'
          });
        });
    }
  });
<|endoftext|>


<commit_before>
Template.insertArticleForm.onRendered(function () {
    this.subscribe("tempArticle", onReady = () => {
        let $text = document.querySelector("#insertArticleForm textarea[name='text']");
        const temp = TempArticles.findOne({authorId: Meteor.userId()});
        if ($text && temp) {
            $text.value = temp.text;
        }
    });
    this.autosaveInterval = setInterval(() => {
        let $text = document.querySelector("#insertArticleForm textarea[name='text']");
        if ($text) {
            Meteor.call("saveTempArticle", $text.value);
        }

    }, 3000);
});

Template.insertArticleForm.onDestroyed(function () {
    clearInterval(this.autosaveInterval);
});

Template.insertArticleForm.events({
    'input #insertArticleForm input[name="title"]': function (e) {
        e.preventDefault();
        let $slug = document.querySelector("#insertArticleForm input[name='slug']");
        let date = new Date();
        $slug.value = URLify2(`${e.target.value}-${moment(date).format('YYYY-MM-DD')}`);
    }
    //'input #insertArticleForm textarea[name="text"]': _.debounce(function (e) {
    //
    //}, 300)
});

AutoForm.addHooks(["insertArticleForm", "updateArticleForm"], {
    onSuccess: function (doc) {
        Router.go("home");
    }

});<commit_msg>fix(client): Fix autosave interval<commit_after>
Template.insertArticleForm.onRendered(function () {
    this.subscribe("tempArticle", onReady = () => {
        let $text = document.querySelector("#insertArticleForm textarea[name='text']");
        const temp = TempArticles.findOne({authorId: Meteor.userId()});
        if ($text && temp) {
            $text.value = temp.text;
        }
    });
    this.autosaveInterval = setInterval(() => {
        let $text = document.querySelector("#insertArticleForm textarea[name='text']");
        if ($text) {
            Meteor.call("saveTempArticle", $text.value);
        }

    }, 30000);
});

Template.insertArticleForm.onDestroyed(function () {
    clearInterval(this.autosaveInterval);
});

Template.insertArticleForm.events({
    'input #insertArticleForm input[name="title"]': function (e) {
        e.preventDefault();
        let $slug = document.querySelector("#insertArticleForm input[name='slug']");
        let date = new Date();
        $slug.value = URLify2(`${e.target.value}-${moment(date).format('YYYY-MM-DD')}`);
    }
    //'input #insertArticleForm textarea[name="text"]': _.debounce(function (e) {
    //
    //}, 300)
});

AutoForm.addHooks(["insertArticleForm", "updateArticleForm"], {
    onSuccess: function (doc) {
        Router.go("home");
    }

});<|endoftext|>


<commit_before>Session.set('categoryName', '');

Meteor.autorun(function () {
    Meteor.subscribe('categories', Session.get('categoryName'));
});

Template.categories.created = function () {
};

Template.categories.helpers({
    categories: function () {
        return Categories.find();
    }
});

Template.categories.rendered = function () {
};

Template.categories.events({
    'submit form': function (event) {
        var text = event.target.text.value;
        event.target.text.value = '';

        var form = event.target.name;
        // create or search
        if (form === 'new-category') {
            var description = event.target.description.value;
            event.target.description.value = '';
            Categories.insert({
                name: text,
                description: description
            });
        } else if (form === 'search-category') {
            Session.set('categoryName', text);
        }
        return false;
    },
    'click button.delete': function (event) {
        Categories.remove(this._id);
    }
});<commit_msg>Search categories while typing<commit_after>Session.set('categoryName', '');

Meteor.autorun(function () {
    Meteor.subscribe('categories', Session.get('categoryName'));
});

Template.categories.created = function () {
};

Template.categories.helpers({
    categories: function () {
        return Categories.find();
    }
});

Template.categories.rendered = function () {
};

Template.categories.events({
    'submit form': function (event) {
        var text = event.target.text.value;
        event.target.text.value = '';

        var form = event.target.name;
        // create or search
        if (form === 'new-category') {
            var description = event.target.description.value;
            event.target.description.value = '';
            Categories.insert({
                name: text,
                description: description
            });
        } else if (form === 'search-category') {
            Session.set('categoryName', text);
        }
        return false;
    },
    'keyup form[name=search-category]': function (event) {
        var text = event.target.value;
        Session.set('categoryName', text);
    },
    'click button.delete': function (event) {
        Categories.remove(this._id);
    }
});<|endoftext|>


<commit_before>/**
 * @author Filipe Caixeta / http://filipecaixeta.com.br
 *
 * Description: A THREE loader for PCD ascii and binary files.
 *
 * Limitations: Compressed binary files are not supported.
 *
 */

THREE.PCDLoader = function ( manager ) {

	this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
	this.littleEndian = true;

};

THREE.PCDLoader.prototype = {

	constructor: THREE.PCDLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var loader = new THREE.FileLoader( scope.manager );
		loader.setResponseType( 'arraybuffer' );
		loader.load( url, function ( data ) {

			onLoad( scope.parse( data, url ) );

		}, onProgress, onError );

	},

	binarryToStr: function ( data ) {

		var charArray = new Uint8Array( data );

		if ( window.TextDecoder !== undefined ) {

			return new TextDecoder().decode( charArray );

		}

		var text = '';
		for ( var i = 0, il = data.byteLength; i < il; i ++ ) {

			text += String.fromCharCode( charArray[ i ] );

		}
		return text;

	},

	parseHeader: function ( data ) {

		var PCDheader = {};
		var result1 = data.search( /[\r\n]DATA\s(\S*)\s/i );
		var result2 = /[\r\n]DATA\s(\S*)\s/i.exec( data.substr( result1 - 1 ) );

		var i, l;

		PCDheader.data = result2[ 1 ];
		PCDheader.headerLen = result2[ 0 ].length + result1;
		PCDheader.str = data.substr( 0, PCDheader.headerLen );

		// remove comments

		PCDheader.str = PCDheader.str.replace( /\#.*/gi, '' );

		// parse

		PCDheader.version = /VERSION (.*)/i.exec( PCDheader.str );
		PCDheader.fields = /FIELDS (.*)/i.exec( PCDheader.str );
		PCDheader.size = /SIZE (.*)/i.exec( PCDheader.str );
		PCDheader.type = /TYPE (.*)/i.exec( PCDheader.str );
		PCDheader.count = /COUNT (.*)/i.exec( PCDheader.str );
		PCDheader.width = /WIDTH (.*)/i.exec( PCDheader.str );
		PCDheader.height = /HEIGHT (.*)/i.exec( PCDheader.str );
		PCDheader.viewpoint = /VIEWPOINT (.*)/i.exec( PCDheader.str );
		PCDheader.points = /POINTS (.*)/i.exec( PCDheader.str );

		// evaluate

		if ( PCDheader.version !== null )
			PCDheader.version = parseFloat( PCDheader.version[ 1 ] );

		if ( PCDheader.fields !== null )
			PCDheader.fields = PCDheader.fields[ 1 ].split( ' ' );

		if ( PCDheader.type !== null )
			PCDheader.type = PCDheader.type[ 1 ].split( ' ' );

		if ( PCDheader.width !== null )
			PCDheader.width = parseInt( PCDheader.width[ 1 ] );

		if ( PCDheader.height !== null )
			PCDheader.height = parseInt( PCDheader.height[ 1 ] );

		if ( PCDheader.viewpoint !== null )
			PCDheader.viewpoint = PCDheader.viewpoint[ 1 ];

		if ( PCDheader.points !== null )
			PCDheader.points = parseInt( PCDheader.points[ 1 ], 10 );

		if ( PCDheader.points === null )
			PCDheader.points = PCDheader.width * PCDheader.height;

		if ( PCDheader.size !== null ) {

			PCDheader.size = PCDheader.size[ 1 ].split( ' ' ).map( function ( x ) {

				return parseInt( x, 10 );

			} );

		}

		if ( PCDheader.count !== null ) {

			PCDheader.count = PCDheader.count[ 1 ].split( ' ' ).map( function ( x ) {

				return parseInt( x, 10 );

			} );

		} else {

			PCDheader.count = [];

			for ( i = 0, l = PCDheader.fields.length; i < l; i ++ ) {

				PCDheader.count.push( 1 );

			}

		}

		PCDheader.offset = {};

		var sizeSum = 0;

		for ( i = 0, l = PCDheader.fields.length; i < l; i ++ ) {

			if ( PCDheader.data === 'ascii' ) {

				PCDheader.offset[ PCDheader.fields[ i ] ] = i;

			} else {

				PCDheader.offset[ PCDheader.fields[ i ] ] = sizeSum;
				sizeSum += PCDheader.size[ i ];

			}

		}

		// for binary only

		PCDheader.rowSize = sizeSum;

		return PCDheader;

	},

	parse: function ( data, url ) {

		var dataView, offset;
		var i, l;

		var textData = this.binarryToStr( data );

		// parse header (always ascii format)

		var PCDheader = this.parseHeader( textData );

		// parse data

		var position = [];
		var normal = [];
		var color = [];

		// ascii

		if ( PCDheader.data === 'ascii' ) {

			offset = PCDheader.offset;
			var pcdData = textData.substr( PCDheader.headerLen );
			var lines = pcdData.split( '\n' );

			for ( i = 0, l = lines.length; i < l; i ++ ) {

				var line = lines[ i ].split( ' ' );

				if ( offset.x !== undefined ) {

					position.push( parseFloat( line[ offset.x ] ) );
					position.push( parseFloat( line[ offset.y ] ) );
					position.push( parseFloat( line[ offset.z ] ) );

				}

				if ( offset.rgb !== undefined ) {

					var c = new Float32Array( [ parseFloat( line[ offset.rgb ] ) ] );
					dataview = new DataView( c.buffer, 0 );
					color.push( dataview.getUint8( 0 ) / 255.0 );
					color.push( dataview.getUint8( 1 ) / 255.0 );
					color.push( dataview.getUint8( 2 ) / 255.0 );

				}

				if ( offset.normal_x !== undefined ) {

					normal.push( parseFloat( line[ offset.normal_x ] ) );
					normal.push( parseFloat( line[ offset.normal_y ] ) );
					normal.push( parseFloat( line[ offset.normal_z ] ) );

				}

			}

		}

		// binary

		if ( PCDheader.data === 'binary_compressed' ) {

			console.error( 'THREE.PCDLoader: binary_compressed files are not supported' );
			return;

		}

		if ( PCDheader.data === 'binary' ) {

			dataview = new DataView( data, PCDheader.headerLen );
			offset = PCDheader.offset;

			for ( i = 0, row = 0; i < PCDheader.points; i ++, row += PCDheader.rowSize ) {

				if ( offset.x !== undefined ) {

					position.push( dataview.getFloat32( row + offset.x, this.littleEndian ) );
					position.push( dataview.getFloat32( row + offset.y, this.littleEndian ) );
					position.push( dataview.getFloat32( row + offset.z, this.littleEndian ) );

				}

				if ( offset.rgb !== undefined ) {

					color.push( dataview.getUint8( row + offset.rgb + 0 ) / 255.0 );
					color.push( dataview.getUint8( row + offset.rgb + 1 ) / 255.0 );
					color.push( dataview.getUint8( row + offset.rgb + 2 ) / 255.0 );

				}

				if ( offset.normal_x !== undefined ) {

					normal.push( dataview.getFloat32( row + offset.normal_x, this.littleEndian ) );
					normal.push( dataview.getFloat32( row + offset.normal_y, this.littleEndian ) );
					normal.push( dataview.getFloat32( row + offset.normal_z, this.littleEndian ) );

				}

			}

		}

		// build geometry

		var geometry = new THREE.BufferGeometry();

		if ( position.length > 0 ) geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( position, 3 ) );
		if ( normal.length > 0 ) geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normal, 3 ) );
		if ( color.length > 0 ) geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( color, 3 ) );

		geometry.computeBoundingSphere();

		// build material

		var material = new THREE.PointsMaterial( { size: 0.005 } );

		if ( color.length > 0 ) {

			material.vertexColors = true;

		} else {

			material.color.setHex( Math.random() * 0xffffff );

		}

		// build mesh

		var mesh = new THREE.Points( geometry, material );
		var name = url.split( '' ).reverse().join( '' );
		name = /([^\/]*)/.exec( name );
		name = name[ 1 ].split( '' ).reverse().join( '' );
		mesh.name = name;

		return mesh;

	}

};
<commit_msg>PCDLoader: Refactoring<commit_after>/**
 * @author Filipe Caixeta / http://filipecaixeta.com.br
 * @author Mugen87 / https://github.com/Mugen87
 *
 * Description: A THREE loader for PCD ascii and binary files.
 *
 * Limitations: Compressed binary files are not supported.
 *
 */

THREE.PCDLoader = function ( manager ) {

	this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
	this.littleEndian = true;

};

THREE.PCDLoader.prototype = {

	constructor: THREE.PCDLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var loader = new THREE.FileLoader( scope.manager );
		loader.setResponseType( 'arraybuffer' );
		loader.load( url, function ( data ) {

			onLoad( scope.parse( data, url ) );

		}, onProgress, onError );

	},

	parse: function ( data, url ) {

		function binarryToStr( data ) {

			var charArray = new Uint8Array( data );

			if ( window.TextDecoder !== undefined ) {

				return new TextDecoder().decode( charArray );

			}

			var text = '';

			for ( var i = 0, il = data.byteLength; i < il; i ++ ) {

				text += String.fromCharCode( charArray[ i ] );

			}

			return text;

		}

		function parseHeader( data ) {

			var PCDheader = {};
			var result1 = data.search( /[\r\n]DATA\s(\S*)\s/i );
			var result2 = /[\r\n]DATA\s(\S*)\s/i.exec( data.substr( result1 - 1 ) );

			var i, l;

			PCDheader.data = result2[ 1 ];
			PCDheader.headerLen = result2[ 0 ].length + result1;
			PCDheader.str = data.substr( 0, PCDheader.headerLen );

			// remove comments

			PCDheader.str = PCDheader.str.replace( /\#.*/gi, '' );

			// parse

			PCDheader.version = /VERSION (.*)/i.exec( PCDheader.str );
			PCDheader.fields = /FIELDS (.*)/i.exec( PCDheader.str );
			PCDheader.size = /SIZE (.*)/i.exec( PCDheader.str );
			PCDheader.type = /TYPE (.*)/i.exec( PCDheader.str );
			PCDheader.count = /COUNT (.*)/i.exec( PCDheader.str );
			PCDheader.width = /WIDTH (.*)/i.exec( PCDheader.str );
			PCDheader.height = /HEIGHT (.*)/i.exec( PCDheader.str );
			PCDheader.viewpoint = /VIEWPOINT (.*)/i.exec( PCDheader.str );
			PCDheader.points = /POINTS (.*)/i.exec( PCDheader.str );

			// evaluate

			if ( PCDheader.version !== null )
				PCDheader.version = parseFloat( PCDheader.version[ 1 ] );

			if ( PCDheader.fields !== null )
				PCDheader.fields = PCDheader.fields[ 1 ].split( ' ' );

			if ( PCDheader.type !== null )
				PCDheader.type = PCDheader.type[ 1 ].split( ' ' );

			if ( PCDheader.width !== null )
				PCDheader.width = parseInt( PCDheader.width[ 1 ] );

			if ( PCDheader.height !== null )
				PCDheader.height = parseInt( PCDheader.height[ 1 ] );

			if ( PCDheader.viewpoint !== null )
				PCDheader.viewpoint = PCDheader.viewpoint[ 1 ];

			if ( PCDheader.points !== null )
				PCDheader.points = parseInt( PCDheader.points[ 1 ], 10 );

			if ( PCDheader.points === null )
				PCDheader.points = PCDheader.width * PCDheader.height;

			if ( PCDheader.size !== null ) {

				PCDheader.size = PCDheader.size[ 1 ].split( ' ' ).map( function ( x ) {

					return parseInt( x, 10 );

				} );

			}

			if ( PCDheader.count !== null ) {

				PCDheader.count = PCDheader.count[ 1 ].split( ' ' ).map( function ( x ) {

					return parseInt( x, 10 );

				} );

			} else {

				PCDheader.count = [];

				for ( i = 0, l = PCDheader.fields.length; i < l; i ++ ) {

					PCDheader.count.push( 1 );

				}

			}

			PCDheader.offset = {};

			var sizeSum = 0;

			for ( i = 0, l = PCDheader.fields.length; i < l; i ++ ) {

				if ( PCDheader.data === 'ascii' ) {

					PCDheader.offset[ PCDheader.fields[ i ] ] = i;

				} else {

					PCDheader.offset[ PCDheader.fields[ i ] ] = sizeSum;
					sizeSum += PCDheader.size[ i ];

				}

			}

			// for binary only

			PCDheader.rowSize = sizeSum;

			return PCDheader;

		}

		var dataView, offset;
		var i, l;

		var textData = binarryToStr( data );

		// parse header (always ascii format)

		var PCDheader = parseHeader( textData );

		// parse data

		var position = [];
		var normal = [];
		var color = [];

		// ascii

		if ( PCDheader.data === 'ascii' ) {

			offset = PCDheader.offset;
			var pcdData = textData.substr( PCDheader.headerLen );
			var lines = pcdData.split( '\n' );

			for ( i = 0, l = lines.length; i < l; i ++ ) {

				var line = lines[ i ].split( ' ' );

				if ( offset.x !== undefined ) {

					position.push( parseFloat( line[ offset.x ] ) );
					position.push( parseFloat( line[ offset.y ] ) );
					position.push( parseFloat( line[ offset.z ] ) );

				}

				if ( offset.rgb !== undefined ) {

					var c = new Float32Array( [ parseFloat( line[ offset.rgb ] ) ] );
					dataview = new DataView( c.buffer, 0 );
					color.push( dataview.getUint8( 0 ) / 255.0 );
					color.push( dataview.getUint8( 1 ) / 255.0 );
					color.push( dataview.getUint8( 2 ) / 255.0 );

				}

				if ( offset.normal_x !== undefined ) {

					normal.push( parseFloat( line[ offset.normal_x ] ) );
					normal.push( parseFloat( line[ offset.normal_y ] ) );
					normal.push( parseFloat( line[ offset.normal_z ] ) );

				}

			}

		}

		// binary

		if ( PCDheader.data === 'binary_compressed' ) {

			console.error( 'THREE.PCDLoader: binary_compressed files are not supported' );
			return;

		}

		if ( PCDheader.data === 'binary' ) {

			dataview = new DataView( data, PCDheader.headerLen );
			offset = PCDheader.offset;

			for ( i = 0, row = 0; i < PCDheader.points; i ++, row += PCDheader.rowSize ) {

				if ( offset.x !== undefined ) {

					position.push( dataview.getFloat32( row + offset.x, this.littleEndian ) );
					position.push( dataview.getFloat32( row + offset.y, this.littleEndian ) );
					position.push( dataview.getFloat32( row + offset.z, this.littleEndian ) );

				}

				if ( offset.rgb !== undefined ) {

					color.push( dataview.getUint8( row + offset.rgb + 0 ) / 255.0 );
					color.push( dataview.getUint8( row + offset.rgb + 1 ) / 255.0 );
					color.push( dataview.getUint8( row + offset.rgb + 2 ) / 255.0 );

				}

				if ( offset.normal_x !== undefined ) {

					normal.push( dataview.getFloat32( row + offset.normal_x, this.littleEndian ) );
					normal.push( dataview.getFloat32( row + offset.normal_y, this.littleEndian ) );
					normal.push( dataview.getFloat32( row + offset.normal_z, this.littleEndian ) );

				}

			}

		}

		// build geometry

		var geometry = new THREE.BufferGeometry();

		if ( position.length > 0 ) geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( position, 3 ) );
		if ( normal.length > 0 ) geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normal, 3 ) );
		if ( color.length > 0 ) geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( color, 3 ) );

		geometry.computeBoundingSphere();

		// build material

		var material = new THREE.PointsMaterial( { size: 0.005 } );

		if ( color.length > 0 ) {

			material.vertexColors = true;

		} else {

			material.color.setHex( Math.random() * 0xffffff );

		}

		// build mesh

		var mesh = new THREE.Points( geometry, material );
		var name = url.split( '' ).reverse().join( '' );
		name = /([^\/]*)/.exec( name );
		name = name[ 1 ].split( '' ).reverse().join( '' );
		mesh.name = name;

		return mesh;

	}

};
<|endoftext|>


<commit_before>var osmTileJSON = {
    "tilejson": "2.0.0",
    "name": "osm-bright-3006",
    "description": "Kartena's rendering, based on MapBox's OSM Bright, of Swedish OpenStreetMap data in SWEREF99 projection.",
    "version": "1.0.0",
    "attribution": "Map data © OpenStreetMap contributors; Imagery © 2013 Kartena",
    "scheme": "xyz",
    "tiles": [
    "http://api.geosition.com/tile/osm-bright-3006/{z}/{x}/{y}.png"
    ],
    "minzoom": 0,
    "maxzoom": 14,
    "crs": "EPSG:3006",
    "projection": "+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs ",
    "transform": [1, 0, -1, 0],
    "resolutions": [
			8192, 4096, 2048, 1024, 512, 256, 128,
			64, 32, 16, 8, 4, 2, 1, 0.5
		],
    "origin": [0, 0],
	"bounds": [218128.7031, 6126002.9379, 1083427.2970, 7692850.9468],
    "center": [ 11.9, 57.7, 8 ]
};

var map = L.TileJSON.createMap('map', osmTileJSON);
<commit_msg>Corrected indentation and bounds<commit_after>var osmTileJSON = {
    "tilejson": "2.0.0",
    "name": "osm-bright-3006",
    "description": "Kartena's rendering, based on MapBox's OSM Bright, of Swedish OpenStreetMap data in SWEREF99 projection.",
    "version": "1.0.0",
    "attribution": "Map data © OpenStreetMap contributors; Imagery © 2013 Kartena",
    "scheme": "xyz",
    "tiles": [
    "http://api.geosition.com/tile/osm-bright-3006/{z}/{x}/{y}.png"
    ],
    "minzoom": 0,
    "maxzoom": 14,
    "crs": "EPSG:3006",
    "projection": "+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs ",
    "transform": [1, 0, -1, 0],
    "resolutions": [
        8192, 4096, 2048, 1024, 512, 256, 128,
        64, 32, 16, 8, 4, 2, 1, 0.5
    ],
    "origin": [0, 0],
    "bounds": [10.570, 55.200, 29.522, 68.723],
    "center": [ 11.9, 57.7, 8 ]
};

var map = L.TileJSON.createMap('map', osmTileJSON);
<|endoftext|>


<commit_before>(function() {
	var
		url,
		originalUrl,
		args  = [],
		debug = false;

	try {
		require('system').args.forEach(function(arg) {
			switch ( arg ) {
				case '-v':
				case '--verbose':
					debug = true;

					break;
				default:
					url = originalUrl = arg;
			}
		});

		if ( !url ) {
			throw new Error('Usage: phantomjs ' + require('system').args[0] + ' <url>');
		}

		if ( !phantom.injectJs('wappalyzer.js') ) {
			throw new Error('Unable to open file js/wappalyzer.js');
		}

		wappalyzer.driver = {
			/**
			 * Log messages to console
			 */
			log: function(args) {
				if ( debug || args.type !== 'debug' ) {
					console.log(args.message);
				}
			},

			/**
			 * Display apps
			 */
			displayApps: function() {
				var
					app, cats,
					apps  = [],
					count = wappalyzer.detected[url] ? Object.keys(wappalyzer.detected[url]).length : 0;

				wappalyzer.log('driver.displayApps');

				if ( count ) {
					for ( app in wappalyzer.detected[url] ) {
						cats = [];

						wappalyzer.apps[app].cats.forEach(function(cat) {
							cats.push(wappalyzer.categories[cat]);
						});

						apps.push({
							name: app,
							confidence:  wappalyzer.detected[url][app].confidenceTotal,
							version:     wappalyzer.detected[url][app].version,
							categories:  cats
						});
					}

					console.log(JSON.stringify({ applications: apps }));
				}
			},

			/**
			 * Initialize
			 */
			init: function() {
				var
					page, hostname,
					headers = {};
					a       = document.createElement('a'),
					json    = JSON.parse(require('fs').read('apps.json'));

				wappalyzer.log('driver.init');

				a.href = url.replace(/#.*$/, '');

				hostname = a.hostname;

				wappalyzer.apps       = json.apps;
				wappalyzer.categories = json.categories;

				page = require('webpage').create();

				page.settings.loadImages      = false;
				page.settings.userAgent       = 'Mozilla/5.0 (compatible; Wappalyzer; +https://github.com/AliasIO/Wappalyzer)';
				page.settings.resourceTimeout = 3000;

				page.onConsoleMessage = function(message) {
					wappalyzer.log(message);
				};

				page.onError = function(message) {
					wappalyzer.log(message, 'error');

					console.log(JSON.stringify({ applications: [] }));

					phantom.exit(1);
				};

				page.onResourceTimeout = function() {
					wappalyzer.log('Resource timeout', 'error');

					console.log(JSON.stringify({ applications: [] }));

					phantom.exit(1);
				};

				page.onResourceReceived = function(response) {
					if ( response.url.replace(/\/$/, '') === url.replace(/\/$/, '') ) {
						if ( response.redirectURL ) {
							url = response.redirectURL;

							return;
						}

						if ( response.stage === 'end' && response.status === 200 && response.contentType.indexOf('text/html') !== -1 ) {
							response.headers.forEach(function(header) {
								headers[header.name.toLowerCase()] = header.value;
							});
						}
					}
				};

				page.open(url, function(status) {
					var html, environmentVars;

					if ( status === 'success' ) {
						html = page.content;

						if ( html.length > 50000 ) {
							html = html.substring(0, 25000) + html.substring(html.length - 25000, html.length);
						}

						// Collect environment variables
						environmentVars = page.evaluate(function() {
							var i, environmentVars;

							for ( i in window ) {
								environmentVars += i + ' ';
							}

							return environmentVars;
						});

						wappalyzer.log({ message: 'environmentVars: ' + environmentVars });

						environmentVars = environmentVars.split(' ').slice(0, 500);

						wappalyzer.analyze(hostname, url, {
							html:    html,
							headers: headers,
							env:     environmentVars
						});
					} else {
						wappalyzer.log('Failed to fetch page');
					}

					phantom.exit(status === 'success' ? 0 : 1);
				});
			}
		};

		wappalyzer.init();
	} catch ( e ) {
		wappalyzer.log(e, 'error');

		console.log(JSON.stringify({ applications: [] }));

		phantom.exit(1);
	}
})();
<commit_msg>Fixed error handling in PhantomJS driver<commit_after>(function() {
	var
		url,
		originalUrl,
		args  = [],
		debug = false;

	try {
		require('system').args.forEach(function(arg) {
			switch ( arg ) {
				case '-v':
				case '--verbose':
					debug = true;

					break;
				default:
					url = originalUrl = arg;
			}
		});

		if ( !url ) {
			throw new Error('Usage: phantomjs ' + require('system').args[0] + ' <url>');
		}

		if ( !phantom.injectJs('wappalyzer.js') ) {
			throw new Error('Unable to open file js/wappalyzer.js');
		}

		wappalyzer.driver = {
			/**
			 * Log messages to console
			 */
			log: function(args) {
				if ( debug || args.type !== 'debug' ) {
					console.log(args.message);
				}
			},

			/**
			 * Display apps
			 */
			displayApps: function() {
				var
					app, cats,
					apps  = [],
					count = wappalyzer.detected[url] ? Object.keys(wappalyzer.detected[url]).length : 0;

				wappalyzer.log('driver.displayApps');

				if ( count ) {
					for ( app in wappalyzer.detected[url] ) {
						cats = [];

						wappalyzer.apps[app].cats.forEach(function(cat) {
							cats.push(wappalyzer.categories[cat]);
						});

						apps.push({
							name: app,
							confidence:  wappalyzer.detected[url][app].confidenceTotal,
							version:     wappalyzer.detected[url][app].version,
							categories:  cats
						});
					}

					console.log(JSON.stringify({ applications: apps }));
				}
			},

			/**
			 * Initialize
			 */
			init: function() {
				var
					page, hostname,
					headers = {};
					a       = document.createElement('a'),
					json    = JSON.parse(require('fs').read('apps.json'));

				wappalyzer.log('driver.init');

				a.href = url.replace(/#.*$/, '');

				hostname = a.hostname;

				wappalyzer.apps       = json.apps;
				wappalyzer.categories = json.categories;

				page = require('webpage').create();

				page.settings.loadImages      = false;
				page.settings.userAgent       = 'Mozilla/5.0 (compatible; Wappalyzer; +https://github.com/AliasIO/Wappalyzer)';
				page.settings.resourceTimeout = 3000;

				page.onConsoleMessage = function(message) {
					wappalyzer.log(message);
				};

				page.onError = function(message) {

					wappalyzer.log('x');
					wappalyzer.log(message, 'error');

					console.log(JSON.stringify({ applications: [] }));

					phantom.exit(1);
				};

				page.onResourceTimeout = function() {
					wappalyzer.log('Resource timeout', 'error');

					console.log(JSON.stringify({ applications: [] }));

					phantom.exit(1);
				};

				page.onResourceReceived = function(response) {
					if ( response.url.replace(/\/$/, '') === url.replace(/\/$/, '') ) {
						if ( response.redirectURL ) {
							url = response.redirectURL;

							return;
						}

						if ( response.stage === 'end' && response.status === 200 && response.contentType.indexOf('text/html') !== -1 ) {
							response.headers.forEach(function(header) {
								headers[header.name.toLowerCase()] = header.value;
							});
						}
					}
				};

				page.open(url, function(status) {
					var html, environmentVars;

					if ( status === 'success' ) {
						html = page.content;

						if ( html.length > 50000 ) {
							html = html.substring(0, 25000) + html.substring(html.length - 25000, html.length);
						}

						// Collect environment variables
						environmentVars = page.evaluate(function() {
							var i, environmentVars;

							for ( i in window ) {
								environmentVars += i + ' ';
							}

							return environmentVars;
						});

						wappalyzer.log({ message: 'environmentVars: ' + environmentVars });

						environmentVars = environmentVars.split(' ').slice(0, 500);

						wappalyzer.analyze(hostname, url, {
							html:    html,
							headers: headers,
							env:     environmentVars
						});

						phantom.exit(0);
					} else {
						wappalyzer.log('Failed to fetch page');

						console.log(JSON.stringify({ applications: [] }));

						phantom.exit(1);
					}
				});
			}
		};

		wappalyzer.init();
	} catch ( e ) {
		wappalyzer.log(e, 'error');

		console.log(JSON.stringify({ applications: [] }));

		phantom.exit(1);
	}
})();
<|endoftext|>