<commit_before>var _ = require('underscore');
var linkLayerInfowindow = require('./deep-insights-integration/link-layer-infowindow');
var linkLayerTooltip = require('./deep-insights-integration/link-layer-tooltip');

/**
 * Integration between various data collections/models with cartodb.js and deep-insights.
 */
var F = function (opts) {
  if (!opts.deepInsightsDashboard) throw new Error('deepInsightsDashboard is required');
  if (!opts.analysisDefinitionNodesCollection) throw new Error('analysisDefinitionNodesCollection is required');
  if (!opts.analysisDefinitionsCollection) throw new Error('analysisDefinitionsCollection is required');
  if (!opts.layerDefinitionsCollection) throw new Error('layerDefinitionsCollection is required');
  if (!opts.widgetDefinitionsCollection) throw new Error('widgetDefinitionsCollection is required');

  this._diDashboard = opts.deepInsightsDashboard;
  this._analysisDefinitionNodesCollection = opts.analysisDefinitionNodesCollection;
  this._analysisDefinitionsCollection = opts.analysisDefinitionsCollection;

  this._analysisDefinitionNodesCollection.on('add', this._analyseDefinitionNode, this);
  this._analysisDefinitionNodesCollection.on('change', this._analyseDefinitionNode, this);
  this._analysisDefinitionNodesCollection.on('remove', this._onAnalysisDefinitionNodeRemoved, this);
  this._analysisDefinitionsCollection.on('add change:node_id sync', this._analyseDefinition, this);

  opts.layerDefinitionsCollection.on('add', this._onLayerDefinitionAdded, this);
  opts.layerDefinitionsCollection.on('sync', this._onLayerDefinitionSynced, this);
  opts.layerDefinitionsCollection.on('change', this._onLayerDefinitionChanged, this);
  opts.layerDefinitionsCollection.on('remove', this._onLayerDefinitionRemoved, this);
  opts.layerDefinitionsCollection.on('layerMoved', this._onLayerDefinitionMoved, this);

  opts.layerDefinitionsCollection.each(function (layerDefModel) {
    linkLayerInfowindow(layerDefModel, this.visMap());
    linkLayerTooltip(layerDefModel, this.visMap());
  }, this);

  opts.widgetDefinitionsCollection.on('add', this._onWidgetDefinitionAdded, this);
  opts.widgetDefinitionsCollection.on('sync', this._onWidgetDefinitionSynced, this);
  opts.widgetDefinitionsCollection.on('change', this._onWidgetDefinitionChanged, this);
  opts.widgetDefinitionsCollection.on('destroy', this._onWidgetDefinitionDestroyed, this);
  opts.widgetDefinitionsCollection.on('add remove reset', this._invalidateSize, this);

  this._analysisDefinitionsCollection.each(this._analyseDefinition, this);
};

F.prototype._onAnalysisDefinitionNodeRemoved = function (m) {
  var node = this._analysis().findNodeById(m.id);
  if (node) {
    node.remove();
  }
};

F.prototype._analyseDefinition = function (m) {
  var id = m.get('node_id');
  var nodeDefModel = this._analysisDefinitionNodesCollection.get(id);
  this._analyseDefinitionNode(nodeDefModel);
};

F.prototype._analyseDefinitionNode = function (nodeDefModel) {
  var attrs = nodeDefModel.toJSON({skipOptions: true});
  this._analysis().analyse(attrs);

  // Unfortunately have to try to setup sync until this point, since a node doesn't exist until after analyse call
  this._analysisDefinitionNodesCollection.each(this._tryToSetupDefinitionNodeSync, this);
};

F.prototype._tryToSetupDefinitionNodeSync = function (m) {
  // Only setup syncing between node-definition and node sync once
  if (!m.__synced) {
    var node = this._analysis().findNodeById(m.id);
    if (node) {
      m.__synced = true;
      var updateAnalysisQuerySchema = function () {
        m.querySchemaModel.set({
          query: node.get('query'),
          may_have_rows: node.get('status') === 'ready'
        });
      };
      updateAnalysisQuerySchema();
      m.listenTo(node, 'change', updateAnalysisQuerySchema);
      m.listenToOnce(node, 'destroy', m.stopListening);
    }
  }
};

F.prototype._onWidgetDefinitionAdded = function (m) {
  var widgetModel = this._diDashboard.getWidget(m.id);
  if (widgetModel) {
    widgetModel.set('show_stats', true);
  }
};

F.prototype._onWidgetDefinitionSynced = function (m) {
  var widgetModel = this._diDashboard.getWidget(m.id);
  if (!widgetModel) {
    this._createWidgetModel(m);
  }
};

F.prototype._onWidgetDefinitionChanged = function (m) {
  var widgetModel = this._diDashboard.getWidget(m.id);

  // Only try to update if there's a corresponding widget model
  // E.g. the change of type will remove the model and provoke change events, which are not of interest (here),
  // since the widget model should be re-created for the new type anyway.
  if (widgetModel) {
    if (m.hasChanged('type')) {
      widgetModel.remove();
      this._createWidgetModel(m);
    } else {
      var attrs = this._formatWidgetAttrs(m.changedAttributes());
      widgetModel.update(attrs);
    }
  }
};

F.prototype._onWidgetDefinitionDestroyed = function (m) {
  var widgetModel = this._diDashboard.getWidget(m.id);

  if (widgetModel) {
    widgetModel.remove();
  }
};

F.prototype._createWidgetModel = function (m) {
  // e.g. 'time-series' => createTimeSeriesWidget
  var infix = m.get('type').replace(/(^\w|-\w)/g, function (match) {
    return match.toUpperCase().replace('-', '');
  });
  var methodName = 'create' + infix + 'Widget';

  var layerModel = this.visMap().getLayerById(m.get('layer_id'));
  var attrs = this._formatWidgetAttrs(m.attributes);

  var widgetModel = this._diDashboard[methodName](attrs, layerModel);

  if (widgetModel) {
    widgetModel.set('show_stats', true);
  }
};

/**
 * Massage some data points to the expected format of deep-insights API
 */
F.prototype._formatWidgetAttrs = function (attrs) {
  if (!_.has(attrs, 'source')) return attrs; // nothing to format

  var formattedAttrs = _.omit(attrs, 'source');
  formattedAttrs.source = {id: attrs.source};

  return formattedAttrs;
};

F.prototype._onLayerDefinitionAdded = function (m, c, opts) {
  // If added but not yet saved, postpone the creation until persisted (see sync listener)
  if (!m.isNew()) {
    if (!this._getLayer(m)) {
      this._createLayer(m);
    }
  }
};

F.prototype._onLayerDefinitionSynced = function (m) {
  if (!this._getLayer(m)) {
    this._createLayer(m);
  }
};

F.prototype._onLayerDefinitionChanged = function (m) {
  if (!m.isNew()) {
    var layer = this._getLayer(m);

    if (!layer) {
      this._createLayer(m);
      return;
    }

    var attrs = m.changedAttributes();
    if (attrs.type) {
      layer.remove();
      this._createLayer(m);
    } else {
      if (m.get('source') && !layer.get('source')) {
        attrs.source = m.get('source');
      }
      layer.update(attrs);
    }
  }
};

F.prototype._onLayerDefinitionRemoved = function (m) {
  if (!m.isNew()) {
    this._getLayer(m).remove();
  }
};

F.prototype._onLayerDefinitionMoved = function (m, at, c) {
  this.visMap().layers.remove(m, { silent: true });
  this._createLayer(m, {
    at: at
  });
};

var LAYER_TYPE_TO_LAYER_CREATE_METHOD;
F.prototype._createLayer = function (layerDefModel, opts) {
  opts = opts || {};
  var attrs = JSON.parse(JSON.stringify(layerDefModel.attributes)); // deep clone;

  if (attrs.source) {
    // Make sure to analysis is created first
    var nodeDefModel = this._analysisDefinitionNodesCollection.get(attrs.source);
    this._analyseDefinitionNode(nodeDefModel);
  }

  LAYER_TYPE_TO_LAYER_CREATE_METHOD = LAYER_TYPE_TO_LAYER_CREATE_METHOD || {
    'cartodb': 'createCartoDBLayer',
    'gmapsbase': 'createGMapsBaseLayer',
    'plain': 'createPlainLayer',
    'tiled': 'createTileLayer',
    'torque': 'createTorqueLayer',
    'wms': 'createWMSLayer'
  };
  var createMethodName = LAYER_TYPE_TO_LAYER_CREATE_METHOD[attrs.type.toLowerCase()];
  if (!createMethodName) throw new Error('no create method name found for type ' + attrs.type);

  var visMap = this.visMap();
  visMap[createMethodName](attrs, opts);

  linkLayerInfowindow(layerDefModel, visMap);
  linkLayerTooltip(layerDefModel, visMap);
};

F.prototype._getLayer = function (m) {
  return this.visMap().getLayerById(m.id);
};

F.prototype.visMap = function () {
  return this._vis().map;
};

F.prototype._analysis = function () {
  return this._vis().analysis;
};

F.prototype._vis = function () {
  return this._diDashboard.getMap();
};

F.prototype._invalidateSize = function () {
  this._vis().invalidateSize();
};

module.exports = F;
<commit_msg>disables autostyle when css changes in the editor<commit_after>var _ = require('underscore');
var linkLayerInfowindow = require('./deep-insights-integration/link-layer-infowindow');
var linkLayerTooltip = require('./deep-insights-integration/link-layer-tooltip');

/**
 * Integration between various data collections/models with cartodb.js and deep-insights.
 */
var F = function (opts) {
  if (!opts.deepInsightsDashboard) throw new Error('deepInsightsDashboard is required');
  if (!opts.analysisDefinitionNodesCollection) throw new Error('analysisDefinitionNodesCollection is required');
  if (!opts.analysisDefinitionsCollection) throw new Error('analysisDefinitionsCollection is required');
  if (!opts.layerDefinitionsCollection) throw new Error('layerDefinitionsCollection is required');
  if (!opts.widgetDefinitionsCollection) throw new Error('widgetDefinitionsCollection is required');

  this._diDashboard = opts.deepInsightsDashboard;
  this._analysisDefinitionNodesCollection = opts.analysisDefinitionNodesCollection;
  this._analysisDefinitionsCollection = opts.analysisDefinitionsCollection;

  this._analysisDefinitionNodesCollection.on('add', this._analyseDefinitionNode, this);
  this._analysisDefinitionNodesCollection.on('change', this._analyseDefinitionNode, this);
  this._analysisDefinitionNodesCollection.on('remove', this._onAnalysisDefinitionNodeRemoved, this);
  this._analysisDefinitionsCollection.on('add change:node_id sync', this._analyseDefinition, this);

  opts.layerDefinitionsCollection.on('add', this._onLayerDefinitionAdded, this);
  opts.layerDefinitionsCollection.on('sync', this._onLayerDefinitionSynced, this);
  opts.layerDefinitionsCollection.on('change', this._onLayerDefinitionChanged, this);
  opts.layerDefinitionsCollection.on('remove', this._onLayerDefinitionRemoved, this);
  opts.layerDefinitionsCollection.on('layerMoved', this._onLayerDefinitionMoved, this);
  opts.layerDefinitionsCollection.on('change:cartocss', this._onLayerChangeCheckWidgetAutoStyling, this);

  opts.layerDefinitionsCollection.each(function (layerDefModel) {
    linkLayerInfowindow(layerDefModel, this.visMap());
    linkLayerTooltip(layerDefModel, this.visMap());
  }, this);

  opts.widgetDefinitionsCollection.on('add', this._onWidgetDefinitionAdded, this);
  opts.widgetDefinitionsCollection.on('sync', this._onWidgetDefinitionSynced, this);
  opts.widgetDefinitionsCollection.on('change', this._onWidgetDefinitionChanged, this);
  opts.widgetDefinitionsCollection.on('destroy', this._onWidgetDefinitionDestroyed, this);
  opts.widgetDefinitionsCollection.on('add remove reset', this._invalidateSize, this);

  this.widgetDefinitionsCollection = opts.widgetDefinitionsCollection;

  this._analysisDefinitionsCollection.each(this._analyseDefinition, this);
};

F.prototype._onAnalysisDefinitionNodeRemoved = function (m) {
  var node = this._analysis().findNodeById(m.id);
  if (node) {
    node.remove();
  }
};

F.prototype._analyseDefinition = function (m) {
  var id = m.get('node_id');
  var nodeDefModel = this._analysisDefinitionNodesCollection.get(id);
  this._analyseDefinitionNode(nodeDefModel);
};

F.prototype._analyseDefinitionNode = function (nodeDefModel) {
  var attrs = nodeDefModel.toJSON({skipOptions: true});
  this._analysis().analyse(attrs);

  // Unfortunately have to try to setup sync until this point, since a node doesn't exist until after analyse call
  this._analysisDefinitionNodesCollection.each(this._tryToSetupDefinitionNodeSync, this);
};

F.prototype._tryToSetupDefinitionNodeSync = function (m) {
  // Only setup syncing between node-definition and node sync once
  if (!m.__synced) {
    var node = this._analysis().findNodeById(m.id);
    if (node) {
      m.__synced = true;
      var updateAnalysisQuerySchema = function () {
        m.querySchemaModel.set({
          query: node.get('query'),
          may_have_rows: node.get('status') === 'ready'
        });
      };
      updateAnalysisQuerySchema();
      m.listenTo(node, 'change', updateAnalysisQuerySchema);
      m.listenToOnce(node, 'destroy', m.stopListening);
    }
  }
};

F.prototype._onWidgetDefinitionAdded = function (m) {
  var widgetModel = this._diDashboard.getWidget(m.id);
  if (widgetModel) {
    widgetModel.set('show_stats', true);
  }
};

F.prototype._onWidgetDefinitionSynced = function (m) {
  var widgetModel = this._diDashboard.getWidget(m.id);
  if (!widgetModel) {
    this._createWidgetModel(m);
  }
};

F.prototype._onLayerChangeCheckWidgetAutoStyling = function (model) {
  var self = this;
  var currentLayerId = model.get('id');
  var widgetsToInvalidate = this.widgetDefinitionsCollection.where({'layer_id': currentLayerId});
  widgetsToInvalidate.forEach(function (widget) {
    var widgetModel = self._diDashboard.getWidget(widget.id);
    if (widgetModel) {
      widgetModel.cancelAutoStyle();
    }
  });
};

F.prototype._onWidgetDefinitionChanged = function (m) {
  var widgetModel = this._diDashboard.getWidget(m.id);

  // Only try to update if there's a corresponding widget model
  // E.g. the change of type will remove the model and provoke change events, which are not of interest (here),
  // since the widget model should be re-created for the new type anyway.
  if (widgetModel) {
    if (m.hasChanged('type')) {
      widgetModel.remove();
      this._createWidgetModel(m);
    } else {
      var attrs = this._formatWidgetAttrs(m.changedAttributes());
      widgetModel.update(attrs);
    }
  }
};

F.prototype._onWidgetDefinitionDestroyed = function (m) {
  var widgetModel = this._diDashboard.getWidget(m.id);

  if (widgetModel) {
    widgetModel.remove();
  }
};

F.prototype._createWidgetModel = function (m) {
  // e.g. 'time-series' => createTimeSeriesWidget
  var infix = m.get('type').replace(/(^\w|-\w)/g, function (match) {
    return match.toUpperCase().replace('-', '');
  });
  var methodName = 'create' + infix + 'Widget';

  var layerModel = this.visMap().getLayerById(m.get('layer_id'));
  var attrs = this._formatWidgetAttrs(m.attributes);

  var widgetModel = this._diDashboard[methodName](attrs, layerModel);

  if (widgetModel) {
    widgetModel.set('show_stats', true);
  }
};

/**
 * Massage some data points to the expected format of deep-insights API
 */
F.prototype._formatWidgetAttrs = function (attrs) {
  if (!_.has(attrs, 'source')) return attrs; // nothing to format

  var formattedAttrs = _.omit(attrs, 'source');
  formattedAttrs.source = {id: attrs.source};

  return formattedAttrs;
};

F.prototype._onLayerDefinitionAdded = function (m, c, opts) {
  // If added but not yet saved, postpone the creation until persisted (see sync listener)
  if (!m.isNew()) {
    if (!this._getLayer(m)) {
      this._createLayer(m);
    }
  }
};

F.prototype._onLayerDefinitionSynced = function (m) {
  if (!this._getLayer(m)) {
    this._createLayer(m);
  }
};

F.prototype._onLayerDefinitionChanged = function (m) {
  if (!m.isNew()) {
    var layer = this._getLayer(m);

    if (!layer) {
      this._createLayer(m);
      return;
    }

    var attrs = m.changedAttributes();
    if (attrs.type) {
      layer.remove();
      this._createLayer(m);
    } else {
      if (m.get('source') && !layer.get('source')) {
        attrs.source = m.get('source');
      }
      layer.update(attrs);
    }
  }
};

F.prototype._onLayerDefinitionRemoved = function (m) {
  if (!m.isNew()) {
    this._getLayer(m).remove();
  }
};

F.prototype._onLayerDefinitionMoved = function (m, at, c) {
  this.visMap().layers.remove(m, { silent: true });
  this._createLayer(m, {
    at: at
  });
};

var LAYER_TYPE_TO_LAYER_CREATE_METHOD;
F.prototype._createLayer = function (layerDefModel, opts) {
  opts = opts || {};
  var attrs = JSON.parse(JSON.stringify(layerDefModel.attributes)); // deep clone;

  if (attrs.source) {
    // Make sure to analysis is created first
    var nodeDefModel = this._analysisDefinitionNodesCollection.get(attrs.source);
    this._analyseDefinitionNode(nodeDefModel);
  }

  LAYER_TYPE_TO_LAYER_CREATE_METHOD = LAYER_TYPE_TO_LAYER_CREATE_METHOD || {
    'cartodb': 'createCartoDBLayer',
    'gmapsbase': 'createGMapsBaseLayer',
    'plain': 'createPlainLayer',
    'tiled': 'createTileLayer',
    'torque': 'createTorqueLayer',
    'wms': 'createWMSLayer'
  };
  var createMethodName = LAYER_TYPE_TO_LAYER_CREATE_METHOD[attrs.type.toLowerCase()];
  if (!createMethodName) throw new Error('no create method name found for type ' + attrs.type);

  var visMap = this.visMap();
  visMap[createMethodName](attrs, opts);

  linkLayerInfowindow(layerDefModel, visMap);
  linkLayerTooltip(layerDefModel, visMap);
};

F.prototype._getLayer = function (m) {
  return this.visMap().getLayerById(m.id);
};

F.prototype.visMap = function () {
  return this._vis().map;
};

F.prototype._analysis = function () {
  return this._vis().analysis;
};

F.prototype._vis = function () {
  return this._diDashboard.getMap();
};

F.prototype._invalidateSize = function () {
  this._vis().invalidateSize();
};

module.exports = F;
<|endoftext|>


<commit_before>var EOL = require('os').EOL;
var SilentError = require('silent-error');
var isPackageMissing = require('ember-cli-is-package-missing');

module.exports = {
  description: 'Generates an Ember Simple Auth authenticator',

  availableOptions: [
    { name: 'base-class', type: String, values: ['oauth2', 'devise', 'torii', 'base'], default: 'base' }
  ],

  locals: function(options) {
    var name      = options.entity.name;
    var baseClass = options.baseClass || 'base';

    if (baseClass === 'torii') {
      return {
        imports: 'import Ember from \'ember\';' + EOL + 'import Torii from \'ember-simple-auth/authenticators/torii\';',
        baseClass: 'Torii',
        body: EOL + '  torii: Ember.inject.service(\'torii\')'
      };
    } else if (baseClass === 'oauth2') {
      return {
        imports: 'import Ember from \'ember\';' + EOL + 'import OAuth2PasswordGrant from \'ember-simple-auth/authenticators/oauth2-password-grant\';',
        baseClass: 'OAuth2PasswordGrant',
        body: ''
      };
    } else if (baseClass === 'devise') {
      return {
        imports: 'import Ember from \'ember\';' + EOL + 'import Devise from \'ember-simple-auth/authenticators/devise\';',
        baseClass: 'Devise',
        body: ''
      };
    } else if (baseClass === 'base') {
      return {
        imports: 'import Ember from \'ember\';' + EOL + 'import Base from \'ember-simple-auth/authenticators/base\';',
        baseClass: 'Base',
        body: EOL + '  restore(data) {' + EOL + '  },' + EOL + EOL + '  authenticate(/*args*/) {' + EOL + '  },' + EOL + EOL + '  invalidate(data) {' + EOL + '  }'
      };
    } else if (name === baseClass) {
      throw new SilentError('Authenticators cannot extend from themself. Remove the --base-class option or specify one of "oauth2", "torii" or "devise".');
    } else {
      throw new SilentError('The authenticator base class "' + baseClass + '" is unknown. Remove the --base-class option or specify one of "oauth2", "torii" or "devise".');
    }
  },

  afterInstall: function(options) {
    if (!options.dryRun && options.torii && isPackageMissing(this, 'torii')) {
      return this.addPackagesToProject([
        { name: 'torii', target: '~0.6.1' }
      ]);
    }
  }
};
<commit_msg>Remove top-level Ember imports from generated authenticators (#1055)<commit_after>var EOL = require('os').EOL;
var SilentError = require('silent-error');
var isPackageMissing = require('ember-cli-is-package-missing');

module.exports = {
  description: 'Generates an Ember Simple Auth authenticator',

  availableOptions: [
    { name: 'base-class', type: String, values: ['oauth2', 'devise', 'torii', 'base'], default: 'base' }
  ],

  locals: function(options) {
    var name      = options.entity.name;
    var baseClass = options.baseClass || 'base';

    if (baseClass === 'torii') {
      return {
        imports: 'import Torii from \'ember-simple-auth/authenticators/torii\';',
        baseClass: 'Torii',
        body: EOL + '  torii: Ember.inject.service(\'torii\')'
      };
    } else if (baseClass === 'oauth2') {
      return {
        imports: 'import OAuth2PasswordGrant from \'ember-simple-auth/authenticators/oauth2-password-grant\';',
        baseClass: 'OAuth2PasswordGrant',
        body: ''
      };
    } else if (baseClass === 'devise') {
      return {
        imports: 'import Devise from \'ember-simple-auth/authenticators/devise\';',
        baseClass: 'Devise',
        body: ''
      };
    } else if (baseClass === 'base') {
      return {
        imports: 'import Base from \'ember-simple-auth/authenticators/base\';',
        baseClass: 'Base',
        body: EOL + '  restore(data) {' + EOL + '  },' + EOL + EOL + '  authenticate(/*args*/) {' + EOL + '  },' + EOL + EOL + '  invalidate(data) {' + EOL + '  }'
      };
    } else if (name === baseClass) {
      throw new SilentError('Authenticators cannot extend from themself. Remove the --base-class option or specify one of "oauth2", "torii" or "devise".');
    } else {
      throw new SilentError('The authenticator base class "' + baseClass + '" is unknown. Remove the --base-class option or specify one of "oauth2", "torii" or "devise".');
    }
  },

  afterInstall: function(options) {
    if (!options.dryRun && options.torii && isPackageMissing(this, 'torii')) {
      return this.addPackagesToProject([
        { name: 'torii', target: '~0.6.1' }
      ]);
    }
  }
};
<|endoftext|>


<commit_before><commit_msg>test(tests): removed components test to make sure travis ci passes on commit push<commit_after><|endoftext|>


<commit_before>/* jshint node: true, loopfunc: true, undef: true, unused: true */
///* global */

module.exports = {};

<commit_msg>add more template code<commit_after>/* jshint node: true, loopfunc: true, undef: true, unused: true */
///* global */

var path = require('path');
var Middleware = require('zfinder-middleware');
var Route = require('zfinder-route');
var objectUtils = require('zero-lang-object');
var zfinderUtils = require('zfinder-utils');

var defaultConfig = zfinderUtils.loadYamlConfig(path.resolve(__dirname, '../config.yaml'));

var mw = new Middleware()
    .addRoute(new Route({
        // properties
        name: '',
        method: 'get',
        url: '*',
        priority: 1,

        // methods
        serve: function(options) {
            options = objectUtils.extend({}, defaultConfig, options);
            // your code goes here
            return function(req, res, next) {
                next();
            };
        },
    }));

module.exports = mw;

<|endoftext|>


<commit_before>import { getSize, pad, runBenchmark } from './utils.js';
import * as THREE from '../node_modules/three/build/three.module.js';
import '../index.js';

const geometry = new THREE.TorusBufferGeometry( 5, 5, 100, 25 );
const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
const raycaster = new THREE.Raycaster();
raycaster.ray.origin.set( 0, 0, - 10 );
raycaster.ray.direction.set( 0, 0, 1 );

runBenchmark(

	'Compute Bounds Tree',
	() => {

		geometry.computeBoundsTree();
		geometry.boundsTree = null;

	},
	3000,
	50

);

geometry.boundsTree = null;
raycaster.firstHitOnly = false;
runBenchmark(

	'Default Raycast',
	() => mesh.raycast( raycaster, [] ),
	3000

);

geometry.computeBoundsTree();
raycaster.firstHitOnly = false;
runBenchmark(

	'BVH Raycast',
	() => mesh.raycast( raycaster, [] ),
	3000

);

geometry.computeBoundsTree();
raycaster.firstHitOnly = true;
runBenchmark(

	'First Hit Raycast',
	() => mesh.raycast( raycaster, [] ),
	3000

);

console.log( '' );

geometry.computeBoundsTree();
const bvhSize = getSize( geometry.boundsTree );
console.log( `${ pad( 'Total Memory Usage', 25 ) }: ${ bvhSize / 1000 } kb` );

// NOTE: There is a reference to the geometry in the bounds tree so the
// geometry will get rolled up with the tree. Subtract it out here.
// If the reference is removed then this will no longer be valid.
geometry.boundsTree = null;
const geoSize = getSize( geometry );
console.log( `${ pad( 'Geometry Memory Usage', 25 ) }: ${ geoSize / 1000 } kb` );

console.log( `${ pad( 'Bounds Tree Memory Usage', 25 ) }: ${ ( bvhSize - geoSize ) / 1000 } kb` );
<commit_msg>Make benchmark geometry larger<commit_after>import { getSize, pad, runBenchmark } from './utils.js';
import * as THREE from '../node_modules/three/build/three.module.js';
import '../index.js';

const geometry = new THREE.TorusBufferGeometry( 5, 5, 1000, 25 );
const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
const raycaster = new THREE.Raycaster();
raycaster.ray.origin.set( 0, 0, - 10 );
raycaster.ray.direction.set( 0, 0, 1 );

runBenchmark(

	'Compute Bounds Tree',
	() => {

		geometry.computeBoundsTree();
		geometry.boundsTree = null;

	},
	3000,
	50

);

geometry.boundsTree = null;
raycaster.firstHitOnly = false;
runBenchmark(

	'Default Raycast',
	() => mesh.raycast( raycaster, [] ),
	3000

);

geometry.computeBoundsTree();
raycaster.firstHitOnly = false;
runBenchmark(

	'BVH Raycast',
	() => mesh.raycast( raycaster, [] ),
	3000

);

geometry.computeBoundsTree();
raycaster.firstHitOnly = true;
runBenchmark(

	'First Hit Raycast',
	() => mesh.raycast( raycaster, [] ),
	3000

);

console.log( '' );

geometry.computeBoundsTree();
const bvhSize = getSize( geometry.boundsTree );
console.log( `${ pad( 'Total Memory Usage', 25 ) }: ${ bvhSize / 1000 } kb` );

// NOTE: There is a reference to the geometry in the bounds tree so the
// geometry will get rolled up with the tree. Subtract it out here.
// If the reference is removed then this will no longer be valid.
geometry.boundsTree = null;
const geoSize = getSize( geometry );
console.log( `${ pad( 'Geometry Memory Usage', 25 ) }: ${ geoSize / 1000 } kb` );

console.log( `${ pad( 'Bounds Tree Memory Usage', 25 ) }: ${ ( bvhSize - geoSize ) / 1000 } kb` );
<|endoftext|>


<commit_before>var
	config = require('../config'),
	gulp = require('gulp'),
	notification = require('../utils/notification'),
	paths = require('../utils/paths'),
	bitmapPaths = paths('bitmap'),
	svgPaths = paths('svg'),
	options = config.tasks.bitmap.tinypngCompress,
	task,

	path = require('path'),
	svgmin = require('gulp-svgmin'),
	tinypngCompress = require('gulp-tinypng-compress'),

	svg = function() {
		return gulp
			.src(svgPaths.src)
			.pipe(svgmin())
			.pipe(gulp.dest(svgPaths.dest));
	},

	bitmap = function() {
		return gulp
			.src(bitmapPaths.src)
			.pipe(
				tinypngCompress(options)
					.on('error', notification({
						title: 'Images Error',
						message: '<%= error.message %>',
					}))
			)
			.pipe(gulp.dest(bitmapPaths.dest));
	};

options.key = options.key || process.env.TINYPNG_KEY;
options.sigFile = options.sigFile || path.join(bitmapPaths.dest, '.tinypng');

gulp.task('images.bitmap', bitmap);
gulp.task('images.svg', svg);

task = gulp.parallel('images.svg', 'images.bitmap');
gulp.task('images', task);
module.exports = task;
<commit_msg>Restore image task naming<commit_after>var
	config = require('../config'),
	gulp = require('gulp'),
	notification = require('../utils/notification'),
	paths = require('../utils/paths'),
	bitmapPaths = paths('bitmap'),
	svgPaths = paths('svg'),
	options = config.tasks.bitmap.tinypngCompress,
	task,

	path = require('path'),
	svgmin = require('gulp-svgmin'),
	tinypngCompress = require('gulp-tinypng-compress'),

	svg = function() {
		return gulp
			.src(svgPaths.src)
			.pipe(svgmin())
			.pipe(gulp.dest(svgPaths.dest));
	},

	bitmap = function() {
		return gulp
			.src(bitmapPaths.src)
			.pipe(
				tinypngCompress(options)
					.on('error', notification({
						title: 'Images Error',
						message: '<%= error.message %>',
					}))
			)
			.pipe(gulp.dest(bitmapPaths.dest));
	};

options.key = options.key || process.env.TINYPNG_KEY;
options.sigFile = options.sigFile || path.join(bitmapPaths.dest, '.tinypng');

gulp.task('bitmap', bitmap);
gulp.task('svg', svg);

task = gulp.parallel('svg', 'bitmap');
gulp.task('images', task);
module.exports = task;
<|endoftext|>


<commit_before>(function() {
  'use strict';

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function smoothScroll(target, time) {
    // time when scroll starts
    console.log(target);

    var start = new Date().getTime(),

    // set an interval to update scrollTop attribute every 25 ms
    timer = setInterval(function() {

        // calculate the step, i.e the degree of completion of the smooth scroll
        var step = Math.min(1, (new Date().getTime() - start) / time);

        // calculate the scroll distance and update the scrollTop
        document.body['scrollTop'] = (step * target.offsetTop);

        // end interval if the scroll is completed
        if (step == 1) clearInterval(timer);
    }, 25);
  }

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  };

  $(document).ready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    // scrollElements = $('[data-scroll-element]');
    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      console.log("Set visibility");
      console.log("nextOffset", nextOffset);
      console.log("limit", limit);
      if(inValidRange(nextOffset, limit)) {
        // element.removeClass('disabled');
        my_removeClass(element, 'disabled');
      } else {
        // element.addClass('disabled');
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      console.log("setVisibilityAll");
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    $('[data-clipboard-target]').each(function() {
      var
          clipboard,
          notification;

      clipboard = new Clipboard(this);

      var notify = function(clipboardNotification, notificationText) {
          notification = $($(clipboardNotification));
          notification.text(notificationText);
          notification.addClass('in').delay(1400).queue(function() {
              notification.removeClass('in');
              $(this).dequeue();
          })
      };

      var notifySuccess = function(e) {
          notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
          //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
          notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
    });

    each(scrollElements, function(el) {
      var
        $this,
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      // console.log("increment", increment);
      // console.log("limit", limit);
      // console.log("offset", offset);

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;
      // console.log(nextOffset);
      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      el.addEventListener('click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        console.log("ELEMENT scroll top", element);
        if (inValidRange(newOffset, limit)) {
          // element.animate({
          //     scrollTop: document.getElementById(newOffset).offsetTop
          // }, 400);
          smoothScroll(element, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });

      // $this.on('click', function() {
      //   offset = element.dataset.scrollOffset;
      //
      //   newOffset = offset + increment;
      //
      //   console.log("newOffset", newOffset);
      //   if (inValidRange(newOffset, limit)) {
      //     element.animate({
      //         scrollTop: $('#' + newOffset).position().top
      //     }, 400);
      //     element.data('scroll-offset', newOffset);
      //
      //     setVisibilityAll(scrollElements, newOffset);
      //   }
      // });
    })
    // scrollElements.each();

    $('[data-open-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('open-panel'));

      $this.on('click', function() {
        element.addClass('open');
      });
    });

    $('[data-close-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('close-panel'));

      $this.on('click', function() {
        element
          .one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() {
            $this.trigger('panel:closed');
          }).removeClass('open');
      });
    });

    $('[data-scroll-reset]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('scroll-reset'));

      $this.on('click', function() {
        $this.one('panel:closed', function() {
          resetScroll(element);
          setVisibilityAll(scrollElements, 0);
        });
      });
    });

    $('[data-moment]').each(function() {
      var $this;

      $this = $(this);

      var time = moment(parseInt($this.text()));
      $this.text(time.fromNow());
    });
  });

  var setContainerHeight = function(containerEl) {
    // TODO: Refactor this to make simpler
    var
      bodyEl,
      bodyHeight,
      bodyHeightWithoutTitle,
      titleEl,
      panelEl,
      referralsEl,
      referralsTitleEl,
      panelHeight,
      css,
      stylesheet;

    bodyEl           = $('.squatch-body');
    titleEl          = bodyEl.find('.squatch-title');
    panelEl          = $('#squatch-panel');
    referralsEl      = $('.squatch-referrals');
    referralsTitleEl = $('.squatch-referrals-title');

    bodyHeight = bodyEl.outerHeight();
    bodyHeightWithoutTitle = bodyHeight - titleEl.outerHeight(true) - titleEl.position().top;
    panelHeight = panelEl.outerHeight();

    if (referralsEl.is(':visible')) {
      panelHeight -= referralsEl.outerHeight();
    }

    if (referralsTitleEl.is(':visible')) {
      panelHeight -= referralsTitleEl.outerHeight();
    }

    containerEl.css('height', bodyHeight + panelHeight);

    stylesheet = document.createElement('style');
    stylesheet.type = 'text/css';

    css = '#squatch-panel.open {' +
      '-webkit-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-ms-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-o-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      'transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '}' +
      'html.lt-ie9 #squatch-panel.open {' +
      'top: -' + bodyHeightWithoutTitle + 'px;' +
      '}';

    if (stylesheet.styleSheet){
      // IE
      stylesheet.styleSheet.cssText = css;
    } else {
      // W3C Standard
      stylesheet.appendChild(document.createTextNode(css));
    }

    document.querySelector('head').appendChild(stylesheet);
  };

  var containerEl = $('.squatch-container-popup');
  if (containerEl.length) {
    var setContainerHeightForPopup = setContainerHeight.bind(undefined, containerEl);
    var windowEl = $(window);

    // Workaround for popup height being incorrectly set during iframe resizing.
    // This is due to the popup being displayed inconsistently - with responsive styles activated, sometimes the mobile view will be displayed, even on a desktop monitor with more than 500 pixels width. The solution may be to set the iframe width to the full browser width, rather than the width of the widget theme.
    // There is another hack in _popup.less as well
    // TODO: Find a solution for this and enable responsive styles again.
    windowEl.on('load', function (i) {
      var setContainerHeightIfWideEnough = function () {
        var width = windowEl.width();

        if (width === 500) {
          setContainerHeightForPopup();
        } else {
          setTimeout(function() {
            setContainerHeightIfWideEnough();
          }, 50);
        }
      };

      setContainerHeightIfWideEnough();
    });

    // The content has a different height in mobile
    // TODO: Find a a solution for responsive in popups and re-enable this
    // var mql = window.matchMedia('(max-width: 500px)');
    // mql.addListener(setContainerHeightForPopup);
  }
})();
<commit_msg>new scroll top<commit_after>(function() {
  'use strict';

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function smoothScroll(target, time) {
    // time when scroll starts
    console.log(target);

    var start = new Date().getTime(),

    // set an interval to update scrollTop attribute every 25 ms
    timer = setInterval(function() {

        // calculate the step, i.e the degree of completion of the smooth scroll
        var step = Math.min(1, (new Date().getTime() - start) / time);

        // calculate the scroll distance and update the scrollTop
        document.body['scrollTop'] = (step * target.offsetTop);
        console.log(document.body['scrollTop']);

        // end interval if the scroll is completed
        if (step == 1) clearInterval(timer);
    }, 25);
  }

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  };

  $(document).ready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    // scrollElements = $('[data-scroll-element]');
    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      console.log("Set visibility");
      console.log("nextOffset", nextOffset);
      console.log("limit", limit);
      if(inValidRange(nextOffset, limit)) {
        // element.removeClass('disabled');
        my_removeClass(element, 'disabled');
      } else {
        // element.addClass('disabled');
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      console.log("setVisibilityAll");
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    $('[data-clipboard-target]').each(function() {
      var
          clipboard,
          notification;

      clipboard = new Clipboard(this);

      var notify = function(clipboardNotification, notificationText) {
          notification = $($(clipboardNotification));
          notification.text(notificationText);
          notification.addClass('in').delay(1400).queue(function() {
              notification.removeClass('in');
              $(this).dequeue();
          })
      };

      var notifySuccess = function(e) {
          notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
          //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
          notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
    });

    each(scrollElements, function(el) {
      var
        $this,
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      // console.log("increment", increment);
      // console.log("limit", limit);
      // console.log("offset", offset);

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;
      // console.log(nextOffset);
      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      el.addEventListener('click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        console.log("ELEMENT scroll top", element);
        if (inValidRange(newOffset, limit)) {
          // element.animate({
          //     scrollTop: document.getElementById(newOffset).offsetTop
          // }, 400);
          smoothScroll(element, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });

      // $this.on('click', function() {
      //   offset = element.dataset.scrollOffset;
      //
      //   newOffset = offset + increment;
      //
      //   console.log("newOffset", newOffset);
      //   if (inValidRange(newOffset, limit)) {
      //     element.animate({
      //         scrollTop: $('#' + newOffset).position().top
      //     }, 400);
      //     element.data('scroll-offset', newOffset);
      //
      //     setVisibilityAll(scrollElements, newOffset);
      //   }
      // });
    })
    // scrollElements.each();

    $('[data-open-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('open-panel'));

      $this.on('click', function() {
        element.addClass('open');
      });
    });

    $('[data-close-panel]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('close-panel'));

      $this.on('click', function() {
        element
          .one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() {
            $this.trigger('panel:closed');
          }).removeClass('open');
      });
    });

    $('[data-scroll-reset]').each(function() {
      var
        $this,
        element;

      $this   = $(this);
      element = $($this.data('scroll-reset'));

      $this.on('click', function() {
        $this.one('panel:closed', function() {
          resetScroll(element);
          setVisibilityAll(scrollElements, 0);
        });
      });
    });

    $('[data-moment]').each(function() {
      var $this;

      $this = $(this);

      var time = moment(parseInt($this.text()));
      $this.text(time.fromNow());
    });
  });

  var setContainerHeight = function(containerEl) {
    // TODO: Refactor this to make simpler
    var
      bodyEl,
      bodyHeight,
      bodyHeightWithoutTitle,
      titleEl,
      panelEl,
      referralsEl,
      referralsTitleEl,
      panelHeight,
      css,
      stylesheet;

    bodyEl           = $('.squatch-body');
    titleEl          = bodyEl.find('.squatch-title');
    panelEl          = $('#squatch-panel');
    referralsEl      = $('.squatch-referrals');
    referralsTitleEl = $('.squatch-referrals-title');

    bodyHeight = bodyEl.outerHeight();
    bodyHeightWithoutTitle = bodyHeight - titleEl.outerHeight(true) - titleEl.position().top;
    panelHeight = panelEl.outerHeight();

    if (referralsEl.is(':visible')) {
      panelHeight -= referralsEl.outerHeight();
    }

    if (referralsTitleEl.is(':visible')) {
      panelHeight -= referralsTitleEl.outerHeight();
    }

    containerEl.css('height', bodyHeight + panelHeight);

    stylesheet = document.createElement('style');
    stylesheet.type = 'text/css';

    css = '#squatch-panel.open {' +
      '-webkit-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-ms-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '-o-transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      'transform: translate(0, -' + bodyHeightWithoutTitle + 'px);' +
      '}' +
      'html.lt-ie9 #squatch-panel.open {' +
      'top: -' + bodyHeightWithoutTitle + 'px;' +
      '}';

    if (stylesheet.styleSheet){
      // IE
      stylesheet.styleSheet.cssText = css;
    } else {
      // W3C Standard
      stylesheet.appendChild(document.createTextNode(css));
    }

    document.querySelector('head').appendChild(stylesheet);
  };

  var containerEl = $('.squatch-container-popup');
  if (containerEl.length) {
    var setContainerHeightForPopup = setContainerHeight.bind(undefined, containerEl);
    var windowEl = $(window);

    // Workaround for popup height being incorrectly set during iframe resizing.
    // This is due to the popup being displayed inconsistently - with responsive styles activated, sometimes the mobile view will be displayed, even on a desktop monitor with more than 500 pixels width. The solution may be to set the iframe width to the full browser width, rather than the width of the widget theme.
    // There is another hack in _popup.less as well
    // TODO: Find a solution for this and enable responsive styles again.
    windowEl.on('load', function (i) {
      var setContainerHeightIfWideEnough = function () {
        var width = windowEl.width();

        if (width === 500) {
          setContainerHeightForPopup();
        } else {
          setTimeout(function() {
            setContainerHeightIfWideEnough();
          }, 50);
        }
      };

      setContainerHeightIfWideEnough();
    });

    // The content has a different height in mobile
    // TODO: Find a a solution for responsive in popups and re-enable this
    // var mql = window.matchMedia('(max-width: 500px)');
    // mql.addListener(setContainerHeightForPopup);
  }
})();
<|endoftext|>


<commit_before>(function() {
    'use strict';
    var timeParsePatterns = [
        // 9
        {
            re: /^\d{1,2}$/i,
            handler: function(bits) {
                if (bits[0].length === 1) {
                    return '0' + bits[0] + ':00';
                } else {
                    return bits[0] + ':00';
                }
            }
        },
        // 13:00
        {
            re: /^\d{2}[:.]\d{2}$/i,
            handler: function(bits) {
                return bits[0].replace('.', ':');
            }
        },
        // 9:00
        {
            re: /^\d[:.]\d{2}$/i,
            handler: function(bits) {
                return '0' + bits[0].replace('.', ':');
            }
        },
        // 3 am / 3 a.m. / 3am
        {
            re: /^(\d+)\s*([ap])(?:.?m.?)?$/i,
            handler: function(bits) {
                var hour = parseInt(bits[1]);
                if (hour === 12) {
                    hour = 0;
                }
                if (bits[2].toLowerCase() === 'p') {
                    if (hour === 12) {
                        hour = 0;
                    }
                    return (hour + 12) + ':00';
                } else {
                    if (hour < 10) {
                        return '0' + hour + ':00';
                    } else {
                        return hour + ':00';
                    }
                }
            }
        },
        // 3.30 am / 3:15 a.m. / 3.00am
        {
            re: /^(\d+)[.:](\d{2})\s*([ap]).?m.?$/i,
            handler: function(bits) {
                var hour = parseInt(bits[1]);
                var mins = parseInt(bits[2]);
                if (mins < 10) {
                    mins = '0' + mins;
                }
                if (hour === 12) {
                    hour = 0;
                }
                if (bits[3].toLowerCase() === 'p') {
                    if (hour === 12) {
                        hour = 0;
                    }
                    return (hour + 12) + ':' + mins;
                } else {
                    if (hour < 10) {
                        return '0' + hour + ':' + mins;
                    } else {
                        return hour + ':' + mins;
                    }
                }
            }
        },
        // noon
        {
            re: /^no/i,
            handler: function(bits) {
                return '12:00';
            }
        },
        // midnight
        {
            re: /^mid/i,
            handler: function(bits) {
                return '00:00';
            }
        }
    ];

    function parseTimeString(s) {
        for (var i = 0; i < timeParsePatterns.length; i++) {
            var re = timeParsePatterns[i].re;
            var handler = timeParsePatterns[i].handler;
            var bits = re.exec(s);
            if (bits) {
                return handler(bits);
            }
        }
        return s;
    }

    window.parseTimeString = parseTimeString;
})();
<commit_msg>Update public/admin/js/timeparse.js<commit_after><|endoftext|>


<commit_before>angular.module('orderCloud')
    .factory('ocAppName', function($cookies, appname) {
        var appName = appname;
        var service = {
            Watch: _watch,
            Update: _update
        };

        function _update(newAppName) {
            appName = newAppName;
        }

        function _watch() {
            return appName;
        }

        return service;

    })
;

<commit_msg>remove unused $cookies dependancy<commit_after>angular.module('orderCloud')
    .factory('ocAppName', function(appname) {
        var appName = appname;
        var service = {
            Watch: _watch,
            Update: _update
        };

        function _update(newAppName) {
            appName = newAppName;
        }

        function _watch() {
            return appName;
        }

        return service;

    })
;

<|endoftext|>


<commit_before>//-----------------------------------
//
// DOJO.Stack: Stack some tileSources
// New DOJO.Source
//     DOJO.Source.init
// -- Made by main.js
// -- Init by main.js
//-----------------------------------
log = console.log.bind(window.console);

DOJO.Stack = function(src_terms){

    // Setup
    var channels = src_terms.channel || ['i'];
    this.preset = channels.split('').map(this.layerer);
    this.nLayers = this.preset.length;
    this.depth = src_terms.depth;
    // Prepare the sources
    var protoSource = new DOJO.Source(src_terms);
    this.source = this.sourcer(protoSource);
    this.maxLevel = this.source[0].tileSource.maxLevel;
}

DOJO.Stack.prototype = {
    w: null,
    vp: null,
    maxBuff: 10,
    level: 0,
    now: 0,
    index: {
      up: 1,
      down: -1
    },
    layerer: function(char){
        var layers = {
            i: {gl:0, mod:''},
            s: {gl:0, mod:'&segmentation=y&segcolor=y'},
            g: {gl:1, target: true, mod:'&segmentation=y'},
            y: {gl:1, target: true, mod:'&synapse=y'},
            dojo: {gl:0, dojo:true}
        };
        var src = layers[char] || layers.i;
        return {src:src, set:{}}
    },
    share: DOJO.Source.prototype.share.bind(null),
    make: function(protoSource,preset,src,alpha){
        var source = protoSource.init(this.share(preset.src, src));
        return this.share({opacity: alpha}, source);
    },
    sourcer: function(proto){
        var sources = [];
        for (var preset of this.preset){
          for (var level = 0; level < this.depth; level++){
            var alp = Number(level == this.now);
            var src = {z:level,minLevel:this.level};
            sources.push(this.make(proto,preset,src,alp));
          }
        }
        var src = {z:-1,minLevel:this.level};
        var dojosource = this.layerer('dojo');
        sources.push(this.make(proto,dojosource,src,1));
        return sources;
    },
    init: function(osd){
        this.vp = osd.viewport;
        this.w = osd.world;
        return this;
    },
    findIndex: function(z){
        var found = []
        for (var layi in this.preset){
            found.push(layi*this.depth + this.now + z);
        }
        return found;
    },
    findLayer: function(z){
        return this.findIndex(z).map(this.w.getItemAt,this.w);
    },
    setOpacity: function(image){
      image.setOpacity(this);
    },
    showLayer: function(z){
        this.findLayer(z).map(this.setOpacity,1);
    },
    hideLayer: function(z){
        this.findLayer(z).map(this.setOpacity,0);
    },
    check: function(event){
        return this.findLayer(this.index[event]);
    },
    getDojo: function(){
        var index = this.w.getItemCount()-1;
        return this.w.getItemAt(index);
    },
    refresher: function(e){
        e.item.addHandler('fully-loaded-change',function(e){
            var event = e.eventSource;
            var source = event.source;
            if(e.fullyLoaded){
                source.minLevel = 0;
                event.draw();
                return;
            }
        }.bind(this));
    },
    zoomer: function(e){
        var z = Math.max(e.zoom,1);
        var level = Math.ceil(Math.log(z)/Math.LN2);
        this.level = Math.min(level, this.maxLevel);
    }
};<commit_msg>basic caching<commit_after>//-----------------------------------
//
// DOJO.Stack: Stack some tileSources
// New DOJO.Source
//     DOJO.Source.init
// -- Made by main.js
// -- Init by main.js
//-----------------------------------
log = console.log.bind(window.console);

DOJO.Stack = function(src_terms){

    // Setup
    var channels = src_terms.channel || ['i'];
    this.preset = channels.split('').map(this.layerer);
    this.nLayers = this.preset.length;
    this.depth = src_terms.depth;
    // Prepare the sources
    var protoSource = new DOJO.Source(src_terms);
    this.source = this.sourcer(protoSource);
    this.maxLevel = this.source[0].tileSource.maxLevel;
}

DOJO.Stack.prototype = {
    w: null,
    vp: null,
    maxBuff: 10,
    level: 0,
    now: 0,
    index: {
      up: 1,
      down: -1
    },
    zBuff: {
      up: 0,
      down: 0
    },
    layerer: function(char){
        var layers = {
            i: {gl:0, mod:''},
            s: {gl:0, mod:'&segmentation=y&segcolor=y'},
            g: {gl:1, target: true, mod:'&segmentation=y'},
            y: {gl:1, target: true, mod:'&synapse=y'},
            dojo: {gl:0, dojo:true}
        };
        var src = layers[char] || layers.i;
        return {src:src, set:{}}
    },
    share: DOJO.Source.prototype.share.bind(null),
    make: function(protoSource,preset,src,alpha){
        var source = protoSource.init(this.share(preset.src, src));
        return this.share({opacity: alpha}, source);
    },
    sourcer: function(proto){
        var sources = [];
        for (var preset of this.preset){
          for (var level = 0; level < this.depth; level++){
            var alp = Number(level == this.now);
            var src = {z:level,minLevel:this.level};
            sources.push(this.make(proto,preset,src,alp));
          }
        }
        var src = {z:-1,minLevel:this.level};
        var dojosource = this.layerer('dojo');
        sources.push(this.make(proto,dojosource,src,1));
        return sources;
    },
    init: function(osd){
        this.vp = osd.viewport;
        this.w = osd.world;
        return this;
    },
    findIndex: function(z){
        var found = []
        for (var layi in this.preset){
            found.push(layi*this.depth + this.now + z);
        }
        return found;
    },
    findLayer: function(z){
        return this.findIndex(z).map(this.w.getItemAt,this.w);
    },
    findBuffer: function(zBuff,dojo){
        var buffer = []
        for (var zb = zBuff.down; zb <= zBuff.up; zb++){
          [].push.apply(buffer,this.findLayer(zb));
        }
        if (dojo){
          buffer.push(this.getDojo());
        }
        return buffer;
    },
    getDojo: function(){
        var index = this.w.getItemCount()-1;
        return this.w.getItemAt(index);
    },
    setPreload: function(image){
        image.setPreload(this);
    },
    setOpacity: function(image){
        image.setOpacity(this);
    },
    showLayer: function(z){
        this.findLayer(z).map(this.setOpacity,1);
    },
    hideLayer: function(z){
        this.findLayer(z).map(this.setOpacity,0);
    },
    check: function(event){
        return this.findLayer(this.index[event]);
    },
    needsDraw: function(zBuff){
        var needsDraw = OpenSeadragon.TiledImage.prototype.needsDraw;
        return this.findBuffer(zBuff,1).some(Function.call.bind(needsDraw));
    },
    updateBuff: function(zBuff){
        var newBuff = {
          up: zBuff.up,
          down: zBuff.down
        }
        if(zBuff.down > -this.maxBuff && this.now + zBuff.down > 0){
          newBuff.down --;
          this.findLayer(newBuff.down).map(this.setPreload,true);
        }
        if(zBuff.up < this.maxBuff && this.now + zBuff.up < this.depth-1){
          newBuff.up ++;
          this.findLayer(newBuff.up).map(this.setPreload,true);
        }
        log(newBuff);
        return newBuff;
    },
    refresher: function(e){
        e.item.addHandler('fully-loaded-change',function(e){
            var event = e.eventSource;
            var source = event.source;
            if(e.fullyLoaded){
                if(!this.needsDraw(this.zBuff)){
                    this.zBuff = this.updateBuff(this.zBuff)
                }
                source.minLevel = 0;
                event.draw();
                return;
            }
        }.bind(this));
    },
    zoomer: function(e){
        var z = Math.max(e.zoom,1);
        var level = Math.ceil(Math.log(z)/Math.LN2);
        this.level = Math.min(level, this.maxLevel);
    }
};<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.View.extend({
  didInsertElement: function () {
    this.updateDomStuff();
  },

  updateDomStuff: Ember.observer('controller.model.compiled', function () {
    Ember.run.scheduleOnce('afterRender', this, function() {
      // Render tex
      this.$('script').each(function (i, e) {
        var t = e.getAttribute('type');
        if (t.search('math/tex') === 0) {
          katex.render(e.textContent,
                       e.parentElement,
                       {
                         displayMode: t.search('mode=display') !== -1
                       });
        }
      });

      // Fix internal links
      this.$('a').each((i, el) => {
        var href = el.getAttribute('href');
        if (href[0] === '/') {
          Ember.$(el).click((ev) => {
            var router = this.get('controller.target.router');
            router.transitionTo(href);
            ev.preventDefault();
          });
        }
      });
    });
  }),
});
<commit_msg>fix math sometimes not working<commit_after>import Ember from 'ember';

export default Ember.View.extend({
  didInsertElement: function () {
    this.updateDomStuff();
  },

  updateDomStuff: Ember.observer('controller.model.compiled', function () {
    Ember.run.scheduleOnce('afterRender', this, function() {
      // This is a workaround for #37.
      // For some reason this.$ is sometimes undefined.
      var el = this.get('element');
      if (!el) {
        return;
      }

      // Render tex
      Ember.$(el).find('script').each(function (i, e) {
        var t = e.getAttribute('type');
        if (t.search('math/tex') === 0) {
          katex.render(e.textContent,
                       e.parentElement,
                       {
                         displayMode: t.search('mode=display') !== -1
                       });
        }
      });

      // Fix internal links
      Ember.$(el).find('a').each((i, el) => {
        var href = el.getAttribute('href');
        if (href[0] === '/') {
          Ember.$(el).click((ev) => {
            var router = this.get('controller.target.router');
            router.transitionTo(href);
            ev.preventDefault();
          });
        }
      });
    });
  }),
});
<|endoftext|>


<commit_before>'use strict'

const querystring = require('querystring')

const httpValidation = require('../../lib/http/validation')
const httpEncryption = require('../../lib/http/encryption')
const httpRoute = require('../../lib/http/route')

module.exports.getParams = function (event) {
  let data = Object.assign({}, querystring.parse(event.body), event.pathParameters, event.queryStringParameters)
  if (hasEncryptedToEmail(data)) {
    data['_to'] = httpEncryption.decrypt(data['_to'])
  }
  if ('_cc' in data) {
    data['_cc'] = data['_cc'].split(';')
  } else {
    data['_cc'] = []
  }
  return data
}

module.exports.validate = function (data, callback) {
  return hasNoHoneypot(data, callback) && hasValidEmail(data, callback)
}

function hasEncryptedToEmail (data) {
  return '_to' in data && httpValidation.isEmail(httpEncryption.decrypt(data['_to']))
}

function hasNoHoneypot (data, callback) {
  if ('_honeypot' in data && data['_honeypot'] !== '') {
    httpRoute.render('receive-honeypot', data, callback)
    return false
  }
  return true
}

function hasValidEmail (data, callback) {
  if (!('_to' in data)) {
    httpRoute.render('receive-no-email', data, callback)
    return false
  }
  if ('_to' in data && !httpValidation.isEmail(data['_to'])) {
    httpRoute.render('receive-bad-email', data, callback)
    return false
  }
  return true
}
<commit_msg>refactor receive get to/cc code<commit_after>'use strict'

const querystring = require('querystring')

const httpValidation = require('../../lib/http/validation')
const httpEncryption = require('../../lib/http/encryption')
const httpRoute = require('../../lib/http/route')

module.exports.getParams = function (event) {
  let data = Object.assign({}, querystring.parse(event.body), event.pathParameters, event.queryStringParameters)
  parseToParam(data)
  parseCcParam(data)
  return data
}

module.exports.validate = function (data, callback) {
  return hasNoHoneypot(data, callback) && hasValidEmail(data, callback)
}

function parseToParam (data) {
  if (hasEncryptedToEmail(data)) {
    data['_to'] = httpEncryption.decrypt(data['_to'])
  }
}

function parseCcParam (data) {
  if ('_cc' in data) {
    let emails = data['_cc'].split(';')
    data['_cc'] = emails.filter(function (email) {
      return httpValidation.isEmail(email)
    })
  } else {
    data['_cc'] = []
  }
}

function hasEncryptedToEmail (data) {
  return '_to' in data && httpValidation.isEmail(httpEncryption.decrypt(data['_to']))
}

function hasNoHoneypot (data, callback) {
  if ('_honeypot' in data && data['_honeypot'] !== '') {
    httpRoute.render('receive-honeypot', data, callback)
    return false
  }
  return true
}

function hasValidEmail (data, callback) {
  if (!('_to' in data)) {
    httpRoute.render('receive-no-email', data, callback)
    return false
  }
  if ('_to' in data && !httpValidation.isEmail(data['_to'])) {
    httpRoute.render('receive-bad-email', data, callback)
    return false
  }
  return true
}
<|endoftext|>


<commit_before>var AWS = require('aws-sdk');

exports.handler = function(params, context) {
    context.succeed(params);
};<commit_msg>updated base lambda code<commit_after>var AWS = require('aws-sdk');

exports.handler = (event, context, callback) {
    callback(null, event);
};
<|endoftext|>


<commit_before>import SPELLS from 'common/SPELLS';

export const ABILITIES_AFFECTED_BY_HEALING_INCREASES = [
  SPELLS.HEALING_WAVE.id,
  SPELLS.CHAIN_HEAL.id,
  SPELLS.HEALING_SURGE_RESTORATION.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.RIPTIDE.id,
  SPELLS.QUEENS_DECREE.id,
  SPELLS.TIDAL_TOTEM.id,
  SPELLS.GIFT_OF_THE_QUEEN.id,
  SPELLS.HEALING_RAIN_HEAL.id,
  SPELLS.WELLSPRING_TALENT.id,
  // While the following spells don't double dip in healing increases, they gain the same percentual bonus from the transfer
  SPELLS.ANCESTRAL_GUIDANCE_HEAL.id,
  SPELLS.CLOUDBURST_TOTEM_HEAL.id,
  SPELLS.ASCENDANCE_HEAL.id,
  SPELLS.LEECH.id,
];

export const ABILITIES_AFFECTED_BY_MASTERY = [
  SPELLS.WELLSPRING_TALENT.id,
  SPELLS.CHAIN_HEAL.id,
  SPELLS.HEALING_WAVE.id,
  SPELLS.RIPTIDE.id,
  SPELLS.HEALING_SURGE_RESTORATION.id,
  SPELLS.GIFT_OF_THE_QUEEN.id,
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.QUEENS_DECREE.id,
  SPELLS.TIDAL_TOTEM.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  // While the following spells don't double dip in healing increases, they gain the same percentual bonus from the transfer
  SPELLS.ANCESTRAL_GUIDANCE_HEAL.id,
  SPELLS.CLOUDBURST_TOTEM_HEAL.id,
  SPELLS.LEECH.id,
];

export const ABILITIES_NOT_FEEDING_INTO_CBT = [
  SPELLS.CLOUDBURST_TOTEM_HEAL.id,
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  SPELLS.TIDAL_TOTEM.id,
  SPELLS.SPIRIT_LINK_TOTEM_REDISTRIBUTE.id,
  SPELLS.LEECH.id,
  SPELLS.VELENS_FUTURE_SIGHT_HEAL.id,
];

export const ABILITIES_NOT_FEEDING_INTO_AG = [
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  SPELLS.TIDAL_TOTEM.id,
  SPELLS.SPIRIT_LINK_TOTEM_REDISTRIBUTE.id,
  SPELLS.LEECH.id,
  SPELLS.VELENS_FUTURE_SIGHT_HEAL.id,
  SPELLS.ANCESTRAL_GUIDANCE_HEAL.id,
];

export const ABILITIES_NOT_FEEDING_INTO_ASCENDANCE = [
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  SPELLS.TIDAL_TOTEM.id,
  SPELLS.SPIRIT_LINK_TOTEM_REDISTRIBUTE.id,
  SPELLS.LEECH.id,
  SPELLS.VELENS_FUTURE_SIGHT_HEAL.id,
  SPELLS.ANCESTRAL_GUIDANCE_HEAL.id,
  SPELLS.ASCENDANCE_HEAL.id,
  SPELLS.CLOUDBURST_TOTEM_HEAL.id,
];
<commit_msg>Updated Resto Shaman Constants<commit_after>import SPELLS from 'common/SPELLS';

export const ABILITIES_AFFECTED_BY_HEALING_INCREASES = [
  SPELLS.HEALING_WAVE.id,
  SPELLS.CHAIN_HEAL.id,
  SPELLS.HEALING_SURGE_RESTORATION.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.RIPTIDE.id,
  SPELLS.QUEENS_DECREE.id,
  SPELLS.TIDAL_TOTEM.id,
  SPELLS.GIFT_OF_THE_QUEEN.id,
  SPELLS.HEALING_RAIN_HEAL.id,
  SPELLS.WELLSPRING_TALENT.id,
  // While the following spells don't double dip in healing increases, they gain the same percentual bonus from the transfer
  SPELLS.ANCESTRAL_GUIDANCE_HEAL.id,
  SPELLS.CLOUDBURST_TOTEM_HEAL.id,
  SPELLS.ASCENDANCE_HEAL.id,
  SPELLS.DOWNPOUR.id,
  SPELLS.LEECH.id,
];

export const ABILITIES_AFFECTED_BY_MASTERY = [
  SPELLS.WELLSPRING_TALENT.id,
  SPELLS.CHAIN_HEAL.id,
  SPELLS.HEALING_WAVE.id,
  SPELLS.RIPTIDE.id,
  SPELLS.HEALING_SURGE_RESTORATION.id,
  SPELLS.GIFT_OF_THE_QUEEN.id,
  SPELLS.GIFT_OF_THE_QUEEN_DUPLICATE.id,
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.QUEENS_DECREE.id,
  SPELLS.TIDAL_TOTEM.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  SPELLS.HEALING_RAIN_HEAL.id,
  // While the following spells don't double dip in healing increases, they gain the same percentual bonus from the transfer
  SPELLS.ANCESTRAL_GUIDANCE_HEAL.id,
  SPELLS.CLOUDBURST_TOTEM_HEAL.id,
  SPELLS.ASCENDANCE_HEAL.id,
  SPELLS.DOWNPOUR.id,
  SPELLS.LEECH.id,
];

export const ABILITIES_NOT_FEEDING_INTO_CBT = [
  SPELLS.CLOUDBURST_TOTEM_HEAL.id,
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  SPELLS.SPIRIT_LINK_TOTEM_REDISTRIBUTE.id,
  SPELLS.LEECH.id,
  SPELLS.VELENS_FUTURE_SIGHT_HEAL.id,
];

export const ABILITIES_NOT_FEEDING_INTO_AG = [
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  SPELLS.SPIRIT_LINK_TOTEM_REDISTRIBUTE.id,
  SPELLS.LEECH.id,
  SPELLS.VELENS_FUTURE_SIGHT_HEAL.id,
  SPELLS.ANCESTRAL_GUIDANCE_HEAL.id,
];

export const ABILITIES_NOT_FEEDING_INTO_ASCENDANCE = [
  SPELLS.HEALING_TIDE_TOTEM_HEAL.id,
  SPELLS.HEALING_STREAM_TOTEM_HEAL.id,
  SPELLS.SPIRIT_LINK_TOTEM_REDISTRIBUTE.id,
  SPELLS.LEECH.id,
  SPELLS.VELENS_FUTURE_SIGHT_HEAL.id,
  SPELLS.ANCESTRAL_GUIDANCE_HEAL.id,
  SPELLS.ASCENDANCE_HEAL.id,
  SPELLS.CLOUDBURST_TOTEM_HEAL.id,
];
<|endoftext|>


<commit_before>'use strict';

let path = require('path');
let fs = require('fs-extra');

import Logger from '../../services/logger';
import Util from '../../model/helpers/util';
import Platform from '../../services/platform';

class StartController {

  constructor(installerDataSvc, electron) {
    this.installerDataSvc = installerDataSvc;
    this.electron = electron;
    this.devstudioInstall = this.installerDataSvc.getInstallable('devstudio');
    this.electron.remote.getCurrentWindow().removeAllListeners('close');
    this.launchDevstudio = this['launchDevstudio_' + Platform.OS];
  }

  learnCDK() {
    this.electron.shell.openExternal(StartController.LEARN_CDK_URL);
  }

  static get LEARN_CDK_URL () {
    return 'http://developers.redhat.com/devstudio-preview';
  }

  start() {
    if(this.devstudioInstall.isSkipped()) {
      this.exit();
    } else {
      this.launchDevstudio();
    }
  }

  launchDevstudio_darwin() {
    let devStudioAppPath = path.join(this.installerDataSvc.devstudioDir(), 'Devstudio.app');
    let options = {
      env : Object.assign({}, Platform.ENV)
    };
    options.env['rhel.subscription.password'] = this.installerDataSvc.password;
    return Util.executeCommand(`open ${devStudioAppPath}`, 1, options).then(()=>{
      Logger.info('devstudio started sucessfully');
      this.exit();
    }).catch((error)=>{
      Logger.error(`devstudio start failed with error code '${error}'`);
      this.exit();
      return Promise.reject(error);
    });
  }

  launchDevstudio_win32() {
    Logger.info('devstudio Start - Write temp files...');
    let devstudioBat = path.join(this.installerDataSvc.devstudioDir());

    let resetvarsBatFile = path.join(this.installerDataSvc.tempDir(), 'resetvars.bat');
    let resetvarsVbsFile = path.join(this.installerDataSvc.tempDir(), 'resetvars.vbs');
    let resetvarsVbsFileData = [
      'Set oShell = WScript.CreateObject("WScript.Shell")',
      'filename = oShell.ExpandEnvironmentStrings("' + resetvarsBatFile + '")',
      'Set objFileSystem = CreateObject("Scripting.fileSystemObject")',
      'Set oFile = objFileSystem.CreateTextFile(filename, TRUE)',

      'set oEnv=oShell.Environment("System")',
      'for each sitem in oEnv',
      'oFile.WriteLine("SET " & sitem)',
      'next',
      'path = oEnv("PATH")',

      'set oEnv=oShell.Environment("User")',
      'for each sitem in oEnv',
      'oFile.WriteLine("SET " & sitem)',
      'next',

      'path = path & ";" & oEnv("PATH")',
      'oFile.WriteLine("SET PATH=" & path)',
      'oFile.Close'
    ].join('\r\n');
    Logger.info('devstudio Start - Write resetvarsVbsFile: ' + resetvarsVbsFile);
    fs.writeFileSync(resetvarsVbsFile, resetvarsVbsFileData);
    Logger.info('devstudio Start - Write resetvarsVbsFile: ' + resetvarsVbsFile + ' - SUCCESS');

    let runDevstudioFile = path.join(this.installerDataSvc.tempDir(), 'rundevstudio.bat');
    let runDevstudioFileData = [
      '"' + resetvarsVbsFile + '"',
      'call "' + resetvarsBatFile + '"',
      'call "' + devstudioBat + '"'
    ].join('\r\n');
    Logger.info('devstudio Start - Write runDevstudioFile: ' + runDevstudioFile);
    fs.writeFileSync(runDevstudioFile, runDevstudioFileData);

    Logger.info('devstudio Start - Write runDevstudioFile: ' + runDevstudioFile + ' - SUCCESS');
    Logger.info('devstudio Start - Write temp file SUCCESS');
    Logger.info('devstudio Start - Run runDevstudioFile: ' + runDevstudioFile);

    let env = Platform.ENV;
    env['rhel.subscription.password'] = this.installerDataSvc.password;
    let runDevstudioBat = require('child_process').spawn(
      'cmd.exe', ['/c', runDevstudioFile], { env, timeout: 2000 });

    runDevstudioBat.stdout.on('data',
      (data) => {
        Logger.info(`devstudio Start - [${runDevstudioFile}]: ${data}`);
      });
    runDevstudioBat.stderr.on('data',
      (data) => {
        Logger.info(`devstudio Start ERROR - [${runDevstudioFile}]: ${data}`);
      });
    runDevstudioBat.on('exit',
      (code) => {
        Logger.info(`devstudio Start Exit - Code: ${code}`);
        this.exit();
      });
  }

  launchDevstudio_linux() {
    // TBD
  }

  exit() {
    Logger.info('Closing the installer window');
    this.electron.remote.getCurrentWindow().close();
  }
}

StartController.$inject = ['installerDataSvc', 'electron'];

export default StartController;
<commit_msg>JBDS-4338 DevStudio does not start when button is pressed<commit_after>'use strict';

let path = require('path');
let fs = require('fs-extra');

import Logger from '../../services/logger';
import Util from '../../model/helpers/util';
import Platform from '../../services/platform';

class StartController {

  constructor(installerDataSvc, electron) {
    this.installerDataSvc = installerDataSvc;
    this.electron = electron;
    this.devstudioInstall = this.installerDataSvc.getInstallable('devstudio');
    this.electron.remote.getCurrentWindow().removeAllListeners('close');
    this.launchDevstudio = this['launchDevstudio_' + Platform.OS];
  }

  learnCDK() {
    this.electron.shell.openExternal(StartController.LEARN_CDK_URL);
  }

  static get LEARN_CDK_URL () {
    return 'http://developers.redhat.com/devstudio-preview';
  }

  start() {
    if(this.devstudioInstall.isSkipped()) {
      this.exit();
    } else {
      this.launchDevstudio();
    }
  }

  launchDevstudio_darwin() {
    let devStudioAppPath = path.join(this.installerDataSvc.devstudioDir(), 'Devstudio.app');
    let options = {
      env : Object.assign({}, Platform.ENV)
    };
    options.env['rhel.subscription.password'] = this.installerDataSvc.password;
    return Util.executeCommand(`open ${devStudioAppPath}`, 1, options).then(()=>{
      Logger.info('devstudio started sucessfully');
      this.exit();
    }).catch((error)=>{
      Logger.error(`devstudio start failed with error code '${error}'`);
      this.exit();
      return Promise.reject(error);
    });
  }

  launchDevstudio_win32() {
    Logger.info('devstudio Start - Write temp files...');
    let devstudioBat = path.join(this.installerDataSvc.devstudioDir(), 'devstudio.bat');

    let resetvarsBatFile = path.join(this.installerDataSvc.tempDir(), 'resetvars.bat');
    let resetvarsVbsFile = path.join(this.installerDataSvc.tempDir(), 'resetvars.vbs');
    let resetvarsVbsFileData = [
      'Set oShell = WScript.CreateObject("WScript.Shell")',
      'filename = oShell.ExpandEnvironmentStrings("' + resetvarsBatFile + '")',
      'Set objFileSystem = CreateObject("Scripting.fileSystemObject")',
      'Set oFile = objFileSystem.CreateTextFile(filename, TRUE)',

      'set oEnv=oShell.Environment("System")',
      'for each sitem in oEnv',
      'oFile.WriteLine("SET " & sitem)',
      'next',
      'path = oEnv("PATH")',

      'set oEnv=oShell.Environment("User")',
      'for each sitem in oEnv',
      'oFile.WriteLine("SET " & sitem)',
      'next',

      'path = path & ";" & oEnv("PATH")',
      'oFile.WriteLine("SET PATH=" & path)',
      'oFile.Close'
    ].join('\r\n');
    Logger.info('devstudio Start - Write resetvarsVbsFile: ' + resetvarsVbsFile);
    fs.writeFileSync(resetvarsVbsFile, resetvarsVbsFileData);
    Logger.info('devstudio Start - Write resetvarsVbsFile: ' + resetvarsVbsFile + ' - SUCCESS');

    let runDevstudioFile = path.join(this.installerDataSvc.tempDir(), 'rundevstudio.bat');
    let runDevstudioFileData = [
      '"' + resetvarsVbsFile + '"',
      'call "' + resetvarsBatFile + '"',
      'call "' + devstudioBat + '"'
    ].join('\r\n');
    Logger.info('devstudio Start - Write runDevstudioFile: ' + runDevstudioFile);
    fs.writeFileSync(runDevstudioFile, runDevstudioFileData);

    Logger.info('devstudio Start - Write runDevstudioFile: ' + runDevstudioFile + ' - SUCCESS');
    Logger.info('devstudio Start - Write temp file SUCCESS');
    Logger.info('devstudio Start - Run runDevstudioFile: ' + runDevstudioFile);

    let env = Platform.ENV;
    env['rhel.subscription.password'] = this.installerDataSvc.password;
    let runDevstudioBat = require('child_process').spawn(
      'cmd.exe', ['/c', runDevstudioFile], { env, timeout: 2000 });

    runDevstudioBat.stdout.on('data',
      (data) => {
        Logger.info(`devstudio Start - [${runDevstudioFile}]: ${data}`);
      });
    runDevstudioBat.stderr.on('data',
      (data) => {
        Logger.info(`devstudio Start ERROR - [${runDevstudioFile}]: ${data}`);
      });
    runDevstudioBat.on('exit',
      (code) => {
        Logger.info(`devstudio Start Exit - Code: ${code}`);
        this.exit();
      });
  }

  launchDevstudio_linux() {
    // TBD
  }

  exit() {
    Logger.info('Closing the installer window');
    this.electron.remote.getCurrentWindow().close();
  }
}

StartController.$inject = ['installerDataSvc', 'electron'];

export default StartController;
<|endoftext|>


<commit_before><commit_msg>Add angular controller/module<commit_after>angular.module("flooshie", [])
.controller("toiletCtrl", ["$scope",function($scope){

}]);<|endoftext|>