<commit_before>var util = require('util'),
  AbstractGeocoder = require('./abstractgeocoder');

/**
 * Constructor
 * @param <object> httpAdapter Http Adapter
 * @param <object> options     Options (appId, appCode, language, politicalView, country, state)
 */
var HereGeocoder = function HereGeocoder(httpAdapter, options) {
  this.options = ['appId', 'appCode', 'language', 'politicalView', 'country', 'state'];

  HereGeocoder.super_.call(this, httpAdapter, options);

  if (!this.options.appId || !this.options.appCode) {
    throw new Error('You must specify appId and appCode to use Here Geocoder');
  }
};

util.inherits(HereGeocoder, AbstractGeocoder);

// Here geocoding API endpoint
HereGeocoder.prototype._geocodeEndpoint = 'https://geocoder.cit.api.here.com/6.2/geocode.json';

// Here reverse geocoding API endpoint
HereGeocoder.prototype._reverseEndpoint = 'https://reverse.geocoder.api.here.com/6.2/reversegeocode.json';

/**
 * Geocode
 * @param <string>   value    Value ton geocode (Address)
 * @param <function> callback Callback method
 */
HereGeocoder.prototype._geocode = function (value, callback) {

  var _this = this;
  var params = this._prepareQueryString();

  if (value.address) {
    if (value.language) {
        params.language = value.language;
    }
    if (value.politicalView) {
        params.politicalview = value.politicalView;
    }
    if (value.country) {
        params.country = value.country;
        if (value.state) {
            params.state = value.state;
        } else {
            delete params.state;
        }
    }
    if (value.zipcode) {
        params.postalcode = value.zipcode;
    }
    params.searchtext = value.address;
  } else {
    params.searchtext = value;
  }

  this.httpAdapter.get(this._geocodeEndpoint, params, function (err, result) {
    var results = [];
    results.raw = result;

    if (err) {
      return callback(err, results);
    } else {
      var view = result.Response.View[0];
      if (!view) {
        return callback(false, results);
      }

      // Format each geocoding result
      results = view.Result.map(_this._formatResult);
      results.raw = result;

      callback(false, results);
    }
  });
};

HereGeocoder.prototype._prepareQueryString = function () {
  var params = {
    'additionaldata': 'Country2,true',
    'gen': 8
  };

  if (this.options.appId) {
    params.app_id = this.options.appId;
  }
  if (this.options.appCode) {
    params.app_code = this.options.appCode;
  }
  if (this.options.language) {
    params.language = this.options.language;
  }
  if (this.options.politicalView) {
    params.politicalview = this.options.politicalView;
  }
  if (this.options.country) {
    params.country = this.options.country;
  }
  if (this.options.state) {
    params.state = this.options.state;
  }

  return params;
};

HereGeocoder.prototype._formatResult = function (result) {
  var location = result.Location || {};
  var address = location.Address || {};
  var i;

  var extractedObj = {
    formattedAddress: address.Label || null,
    latitude: location.DisplayPosition.Latitude,
    longitude: location.DisplayPosition.Longitude,
    country: null,
    countryCode: address.Country || null,
    state: address.State || null,
    county: address.County || null,
    city: address.City || null,
    zipcode: address.PostalCode || null,
    district: address.District || null,
    streetName: address.Street || null,
    streetNumber: address.HouseNumber || null,
    building: address.Building || null,
    extra: {
      herePlaceId: location.LocationId || null,
      confidence: result.Relevance || 0
    },
    administrativeLevels: {}
  };

  for (i = 0; i < address.AdditionalData.length; i++) {
    var additionalData = address.AdditionalData[i];
    switch (additionalData.key) {
      //Country 2-digit code
      case 'Country2':
        extractedObj.countryCode = additionalData.value;
        break;
      //Country name
      case 'CountryName':
        extractedObj.country = additionalData.value;
        break;
      //State name
      case 'StateName':
        extractedObj.administrativeLevels.level1long = additionalData.value;
        extractedObj.state = additionalData.value;
        break;
      //County name
      case 'CountyName':
        extractedObj.administrativeLevels.level2long = additionalData.value;
        extractedObj.county = additionalData.value;
    }
  }

  return extractedObj;
};

/**
 * Reverse geocoding
 * @param {lat:<number>,lon:<number>}  lat: Latitude, lon: Longitude
 * @param <function> callback Callback method
 */
HereGeocoder.prototype._reverse = function (query, callback) {
  var lat = query.lat;
  var lng = query.lon;

  var _this = this;
  var params = this._prepareQueryString();
  params.pos = lat + ',' + lng;
  params.mode = 'trackPosition';

  this.httpAdapter.get(this._reverseEndpoint, params, function (err, result) {
    var results = [];
    results.raw = result;

    if (err) {
      return callback(err, results);
    } else {
      var view = result.Response.View[0];
      if (!view) {
        return callback(false, results);
      }

      // Format each geocoding result
      results = view.Result.map(_this._formatResult);
      results.raw = result;

      callback(false, results);
    }
  });
};

module.exports = HereGeocoder;
<commit_msg>Support production or CIT environment endpoint for HERE geocoder<commit_after>var util = require('util'),
  AbstractGeocoder = require('./abstractgeocoder');

/**
 * Constructor
 * @param <object> httpAdapter Http Adapter
 * @param <object> options     Options (appId, appCode, language, politicalView, country, state, production)
 */
var HereGeocoder = function HereGeocoder(httpAdapter, options) {
  this.options = ['appId', 'appCode', 'language', 'politicalView', 'country', 'state', 'production'];

  HereGeocoder.super_.call(this, httpAdapter, options);

  if (!this.options.appId || !this.options.appCode) {
    throw new Error('You must specify appId and appCode to use Here Geocoder');
  }
};

util.inherits(HereGeocoder, AbstractGeocoder);

Object.defineProperties(HereGeocoder.prototype, {
  // Here geocoding API endpoint
  "_geocodeEndpoint": {
    get: function() {
      return this.options.production ? 'https://geocoder.api.here.com/6.2/geocode.json' : 'https://geocoder.cit.api.here.com/6.2/geocode.json';
    }
  },

  // Here reverse geocoding API endpoint
  "_reverseEndpoint": {
    get: function() {
      return this.options.production ? 'https://reverse.geocoder.api.here.com/6.2/reversegeocode.json' : 'https://reverse.geocoder.cit.api.here.com/6.2/reversegeocode.json';
    }
  }
})

/**
 * Geocode
 * @param <string>   value    Value to geocode (Address)
 * @param <function> callback Callback method
 */
HereGeocoder.prototype._geocode = function (value, callback) {

  var _this = this;
  var params = this._prepareQueryString();

  if (value.address) {
    if (value.language) {
        params.language = value.language;
    }
    if (value.politicalView) {
        params.politicalview = value.politicalView;
    }
    if (value.country) {
        params.country = value.country;
        if (value.state) {
            params.state = value.state;
        } else {
            delete params.state;
        }
    }
    if (value.zipcode) {
        params.postalcode = value.zipcode;
    }
    params.searchtext = value.address;
  } else {
    params.searchtext = value;
  }

  this.httpAdapter.get(this._geocodeEndpoint, params, function (err, result) {
    var results = [];
    results.raw = result;

    if (err) {
      return callback(err, results);
    } else {
      var view = result.Response.View[0];
      if (!view) {
        return callback(false, results);
      }

      // Format each geocoding result
      results = view.Result.map(_this._formatResult);
      results.raw = result;

      callback(false, results);
    }
  });
};

HereGeocoder.prototype._prepareQueryString = function () {
  var params = {
    'additionaldata': 'Country2,true',
    'gen': 8
  };

  if (this.options.appId) {
    params.app_id = this.options.appId;
  }
  if (this.options.appCode) {
    params.app_code = this.options.appCode;
  }
  if (this.options.language) {
    params.language = this.options.language;
  }
  if (this.options.politicalView) {
    params.politicalview = this.options.politicalView;
  }
  if (this.options.country) {
    params.country = this.options.country;
  }
  if (this.options.state) {
    params.state = this.options.state;
  }

  return params;
};

HereGeocoder.prototype._formatResult = function (result) {
  var location = result.Location || {};
  var address = location.Address || {};
  var i;

  var extractedObj = {
    formattedAddress: address.Label || null,
    latitude: location.DisplayPosition.Latitude,
    longitude: location.DisplayPosition.Longitude,
    country: null,
    countryCode: address.Country || null,
    state: address.State || null,
    county: address.County || null,
    city: address.City || null,
    zipcode: address.PostalCode || null,
    district: address.District || null,
    streetName: address.Street || null,
    streetNumber: address.HouseNumber || null,
    building: address.Building || null,
    extra: {
      herePlaceId: location.LocationId || null,
      confidence: result.Relevance || 0
    },
    administrativeLevels: {}
  };

  for (i = 0; i < address.AdditionalData.length; i++) {
    var additionalData = address.AdditionalData[i];
    switch (additionalData.key) {
      //Country 2-digit code
      case 'Country2':
        extractedObj.countryCode = additionalData.value;
        break;
      //Country name
      case 'CountryName':
        extractedObj.country = additionalData.value;
        break;
      //State name
      case 'StateName':
        extractedObj.administrativeLevels.level1long = additionalData.value;
        extractedObj.state = additionalData.value;
        break;
      //County name
      case 'CountyName':
        extractedObj.administrativeLevels.level2long = additionalData.value;
        extractedObj.county = additionalData.value;
    }
  }

  return extractedObj;
};

/**
 * Reverse geocoding
 * @param {lat:<number>,lon:<number>}  lat: Latitude, lon: Longitude
 * @param <function> callback Callback method
 */
HereGeocoder.prototype._reverse = function (query, callback) {
  var lat = query.lat;
  var lng = query.lon;

  var _this = this;
  var params = this._prepareQueryString();
  params.pos = lat + ',' + lng;
  params.mode = 'trackPosition';

  this.httpAdapter.get(this._reverseEndpoint, params, function (err, result) {
    var results = [];
    results.raw = result;

    if (err) {
      return callback(err, results);
    } else {
      var view = result.Response.View[0];
      if (!view) {
        return callback(false, results);
      }

      // Format each geocoding result
      results = view.Result.map(_this._formatResult);
      results.raw = result;

      callback(false, results);
    }
  });
};

module.exports = HereGeocoder;
<|endoftext|>


<commit_before>(function() {
  var c = window.console || function() {};
  c.log = c.log || function(){};
  c.warn = c.warn || function(){};

  if (history.pushState) return;

  // if hashbang not found then convert link to hashbang mode
  if (window.location.hash.charAt(1) !== "!") {
    var base = window.basePath;
    var pathname = window.location.pathname + '';
    var path = base === '/' ? base : pathname.replace(base, '');
    if (path === '') path = '/';
    if (base.charAt(base.length-1) !== '/') base += '/';
    window.location.replace(base + '#!' + path + window.location.search + window.location.hash);
  }
})();
<commit_msg>add HTMLElement polyfill<commit_after>(function() {
  var c = window.console || function() {};
  c.log = c.log || function(){};
  c.warn = c.warn || function(){};

  if (history.pushState) return;

  if (!window.HTMLElement) window.HTMLElement = window.Element;

  // if hashbang not found then convert link to hashbang mode
  if (window.location.hash.charAt(1) !== "!") {
    var base = window.basePath;
    var pathname = window.location.pathname + '';
    var path = base === '/' ? base : pathname.replace(base, '');
    if (path === '') path = '/';
    if (base.charAt(base.length-1) !== '/') base += '/';
    window.location.replace(base + '#!' + path + window.location.search + window.location.hash);
  }
})();
<|endoftext|>


<commit_before>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var Fields = require('oae-config/lib/fields');

module.exports = {
    'title': 'OAE Google Analytics Module',
    'google-analytics': {
        'name': 'Google Analytics configuration',
        'description': 'Google Analytics configuration',
        'elements': {
            'enabled': new Fields.Bool('GA enabled', 'Google Analytics enabled', true, {'tenantOverride': false}),
            'id': new Fields.Text('GA tracking-ID', 'The Google Analytics tracking-ID', 'UA-40243987-3', {'tenantOverride': false}),
            'tentantEnabled': new Fields.Bool('GA tenant enabled', 'Google Analytics enabled for tenant', false),
            'tenantId': new Fields.Text('GA tenant tracking-ID', 'The Google Analytics tenant tracking-ID', '')
        }
    }
};
<commit_msg>fix typo<commit_after>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var Fields = require('oae-config/lib/fields');

module.exports = {
    'title': 'OAE Google Analytics Module',
    'google-analytics': {
        'name': 'Google Analytics configuration',
        'description': 'Google Analytics configuration',
        'elements': {
            'enabled': new Fields.Bool('GA enabled', 'Google Analytics enabled', true, {'tenantOverride': false}),
            'id': new Fields.Text('GA tracking-ID', 'The Google Analytics tracking-ID', 'UA-40243987-3', {'tenantOverride': false}),
            'tenantEnabled': new Fields.Bool('GA tenant enabled', 'Google Analytics enabled for tenant', false),
            'tenantId': new Fields.Text('GA tenant tracking-ID', 'The Google Analytics tenant tracking-ID', '')
        }
    }
};
<|endoftext|>


<commit_before>import assert from 'assert';
import { path as chromedriverPath } from 'chromedriver';
import { path as geckodriverPath } from 'geckodriver';
import { path as iedriverPath } from 'iedriver';

const browsers = [
  {
    id: 'chrome',
    capability: {
      browserName: 'chrome',
      javascriptEnabled: true,
      chrome_binary: process.env.CHROME_BIN
    },
    driver: {
      name: 'Chromedriver',
      path: chromedriverPath,
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'chrome-headless',
    capability: {
      browserName: 'chrome',
      javascriptEnabled: true,
      chromeOptions: {
        args: ['incognito', 'headless', 'no-sandbox', 'disable-gpu']
      },
      chrome_binary: process.env.CHROME_BIN
    },
    driver: {
      name: 'Chromedriver',
      path: chromedriverPath,
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'firefox',
    capability: {
      browserName: 'firefox',
      marionette: true,
      javascriptEnabled: true
    },
    driver: {
      name: 'Geckodriver',
      path: geckodriverPath,
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'firefox-headless',
    capability: {
      browserName: 'firefox',
      marionette: true,
      javascriptEnabled: true,
      'moz:firefoxOptions': {
        args: ['-headless']
      }
    },
    driver: {
      name: 'Geckodriver',
      path: geckodriverPath,
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'safari',
    capability: {
      browserName: 'safari',
      javascriptEnabled: true
    },
    driver: {
      name: 'SafariDriver',
      path: 'safaridriver',
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'internet-explorer',
    capability: {
      browserName: 'internet explorer',
      ignoreProtectedModeSettings: true,
      ignoreZoomSetting: true,
      'ie.ensureCleanSession': true,
      logLevel: 'INFO'
    },
    driver: {
      name: 'InternetExplorerDriver',
      path: iedriverPath,
      args: ({ port }) => [`--port=${port}`, '--log-level=INFO']
    }
  }
];

const selectedBrowser = browsers.find(browser => browser.id === process.env.BROWSER);

assert(
  selectedBrowser,
  'Environment variable BROWSER is not set or is not matching the supported browsers.'
);

export default selectedBrowser;

export const name = selectedBrowser.capability.browserName;
<commit_msg>Migrate to new capabiity API<commit_after>import assert from 'assert';
import { path as chromedriverPath } from 'chromedriver';
import { path as geckodriverPath } from 'geckodriver';
import { path as iedriverPath } from 'iedriver';

const browsers = [
  {
    id: 'chrome',
    capability: {
      browserName: 'chrome',
      'goog:chromeOptions': {
        binary: process.env.CHROME_BIN
      }
    },
    driver: {
      name: 'Chromedriver',
      path: chromedriverPath,
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'chrome-headless',
    capability: {
      browserName: 'chrome',
      'goog:chromeOptions': {
        args: ['--headless', '--disable-gpu'],
        binary: process.env.CHROME_BIN
      }
    },
    driver: {
      name: 'Chromedriver',
      path: chromedriverPath,
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'firefox',
    capability: {
      browserName: 'firefox'
    },
    driver: {
      name: 'Geckodriver',
      path: geckodriverPath,
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'firefox-headless',
    capability: {
      browserName: 'firefox',
      'moz:firefoxOptions': {
        args: ['-headless'],
        log: {
          level: 'trace'
        }
      }
    },
    driver: {
      name: 'Geckodriver',
      path: geckodriverPath,
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'safari',
    capability: {
      browserName: 'safari'
    },
    driver: {
      name: 'SafariDriver',
      path: 'safaridriver',
      args: ({ port }) => [`--port=${port}`]
    }
  },
  {
    id: 'internet-explorer',
    capability: {
      browserName: 'internet explorer',
      ignoreProtectedModeSettings: true,
      ignoreZoomSetting: true,
      'ie.ensureCleanSession': true,
      logLevel: 'INFO'
    },
    driver: {
      name: 'InternetExplorerDriver',
      path: iedriverPath,
      args: ({ port }) => [`--port=${port}`, '--log-level=INFO']
    }
  }
];

const selectedBrowser = browsers.find(browser => browser.id === process.env.BROWSER);

assert(
  selectedBrowser,
  'Environment variable BROWSER is not set or is not matching the supported browsers.'
);

export default selectedBrowser;

export const name = selectedBrowser.capability.browserName;
<|endoftext|>


<commit_before>const quat = require('pex-math/quat')
const vec3 = require('pex-math/vec3')
const vec4 = require('pex-math/vec4')
const utils = require('pex-math/utils')
const Signal = require('signals')

let currentOutputVec3 = vec3.create()
let currentOutputQuat = quat.create()

// Assumptions:
// - all channels have the same time length
// - animation channels can reference other entities
// - currently all animations track time by themselves
function Animation(opts) {
  this.type = 'Animation'
  this.entity = null
  this.enabled = true
  this.playing = false
  this.loop = false
  this.time = 0 // seconds
  this.prevTime = Date.now() // ms
  this.channels = opts.channels || []
  this.changed = new Signal()
  this.set(opts)
}

Animation.prototype.init = function(entity) {
  this.entity = entity
}

Animation.prototype.set = function(opts) {
  Object.assign(this, opts)
  Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))

  if (opts.autoplay || opts.playing) {
    this.playing = true
    // reset timer to avoid jumps
    this.time = 0
    this.prevTime = Date.now()
  }
}

Animation.prototype.update = function() {
  if (!this.playing || !this.enabled) return

  const animationLength = this.channels[0].input[
    this.channels[0].input.length - 1
  ]
  const now = Date.now()
  const deltaTime = (now - this.prevTime) / 1000

  this.prevTime = now
  this.time += deltaTime

  if (this.time > animationLength) {
    if (this.loop) {
      this.time %= animationLength
    } else {
      this.time = 0
      this.set({ playing: false })
    }
  }

  for (let i = 0; i < this.channels.length; i++) {
    const channel = this.channels[i]
    const inputData = channel.input

    let prevIndex
    let nextIndex

    for (let j = 0; j < inputData.length; j++) {
      nextIndex = j
      if (inputData[j] >= this.time) {
        break
      }
      prevIndex = nextIndex
    }

    const isRotation = channel.path === 'rotation'
    const outputData = channel.output
    const prevInput = inputData[prevIndex]
    const nextInput = inputData[nextIndex]
    const scale = nextInput - prevInput

    const t = (this.time - prevInput) / scale

    if (prevIndex !== undefined) {
      switch (channel.interpolation) {
        case 'STEP':
          if (isRotation) {
            quat.set(currentOutputQuat, outputData[prevIndex])
          } else {
            vec3.set(currentOutputVec3, outputData[prevIndex])
          }
          break
        case 'CUBICSPLINE': {
          const vec = isRotation ? vec4 : vec3
          const tt = t * t
          const ttt = tt * t

          // Each input value corresponds to three output values of the same type: in-tangent, data point, and out-tangent.
          // p0
          const prevPosition = vec.copy(outputData[prevIndex * 3 + 1])

          // p1
          const nextPos = vec.copy(outputData[nextIndex * 3 + 1])

          // m0 = (tk+1 - tk)bk
          const prevOutTangent = prevIndex
            ? vec.scale(vec.copy(outputData[prevIndex * 3 + 2]), scale)
            : vec.create()

          // m1 = (tk+1 - tk)ak+1
          const nextInTangent =
            nextIndex !== inputData.length - 1
              ? vec.scale(vec.copy(outputData[prevIndex * 3]), scale)
              : vec.create()

          // p(t) = (2t³ - 3t² + 1)p0 + (t³ - 2t² + t)m0 + (-2t³ + 3t²)p1 + (t³ - t²)m1
          const p0 = vec.scale(prevPosition, 2 * ttt - 3 * tt + 1)
          const m0 = vec.scale(prevOutTangent, ttt - 2 * tt + t)
          const p1 = vec.scale(nextPos, -2 * ttt + 3 * tt)
          const m1 = vec.scale(nextInTangent, ttt - tt)

          if (isRotation) {
            quat.set(
              currentOutputQuat,
              quat.normalize([
                p0[0] + m0[0] + p1[0] + m1[0],
                p0[1] + m0[1] + p1[1] + m1[1],
                p0[2] + m0[2] + p1[2] + m1[2],
                p0[3] + m0[3] + p1[3] + m1[3]
              ])
            )
          } else {
            vec3.set(
              currentOutputVec3,
              vec3.add(vec3.add(vec3.add(p0, m0), p1), m1)
            )
          }

          break
        }
        default:
          // LINEAR
          if (isRotation) {
            quat.slerp(
              quat.set(currentOutputQuat, outputData[prevIndex]),
              outputData[nextIndex],
              t
            )
          } else {
            vec3.set(
              currentOutputVec3,
              outputData[nextIndex].map((output, index) =>
                utils.lerp(outputData[prevIndex][index], output, t)
              )
            )
          }
      }

      if (isRotation) {
        channel.target.transform.set({
          rotation: quat.copy(currentOutputQuat)
        })
      } else if (channel.path === 'translation') {
        channel.target.transform.set({
          position: vec3.copy(currentOutputVec3)
        })
      } else if (channel.path === 'scale') {
        channel.target.transform.set({
          scale: vec3.copy(currentOutputVec3)
        })
      } else if (channel.path === 'weights') {
        channel.target.getComponent('Morph').set({
          weights: outputData[nextIndex].slice()
        })
      }
    }
  }
}

module.exports = function createMorph(opts) {
  return new Animation(opts)
}
<commit_msg>Update animation if time changes even if not playing<commit_after>const quat = require('pex-math/quat')
const vec3 = require('pex-math/vec3')
const vec4 = require('pex-math/vec4')
const utils = require('pex-math/utils')
const Signal = require('signals')

let currentOutputVec3 = vec3.create()
let currentOutputQuat = quat.create()

// Assumptions:
// - all channels have the same time length
// - animation channels can reference other entities
// - currently all animations track time by themselves
function Animation(opts) {
  this.type = 'Animation'
  this.entity = null
  this.enabled = true
  this.playing = false
  this.loop = false
  this.time = 0 // seconds
  this.prevTime = Date.now() // ms
  this.channels = opts.channels || []
  this.changed = new Signal()
  this.needsUpdate = true
  this.set(opts)
}

Animation.prototype.init = function(entity) {
  this.entity = entity
}

Animation.prototype.set = function(opts) {
  Object.assign(this, opts)
  Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))

  if (opts.autoplay || opts.playing) {
    this.playing = true
    // reset timer to avoid jumps
    this.time = 0
    this.prevTime = Date.now()
  }

  this.needsUpdate = true
}

Animation.prototype.update = function() {
  if (!this.enabled) return

  if (this.playing) {
    const animationLength = this.channels[0].input[
      this.channels[0].input.length - 1
    ]
    const now = Date.now()
    const deltaTime = (now - this.prevTime) / 1000

    this.prevTime = now
    this.time += deltaTime

    if (this.time > animationLength) {
      if (this.loop) {
        this.time %= animationLength
      } else {
        this.time = 0
        this.set({ playing: false })
      }
    }

    this.needsUpdate = true
  }

  if (!this.needsUpdate) return

  this.needsUpdate = false

  for (let i = 0; i < this.channels.length; i++) {
    const channel = this.channels[i]
    const inputData = channel.input

    let prevIndex
    let nextIndex

    for (let j = 0; j < inputData.length; j++) {
      nextIndex = j
      if (inputData[j] >= this.time) {
        break
      }
      prevIndex = nextIndex
    }

    const isRotation = channel.path === 'rotation'
    const outputData = channel.output
    const prevInput = inputData[prevIndex]
    const nextInput = inputData[nextIndex]
    const scale = nextInput - prevInput

    const t = (this.time - prevInput) / scale

    if (prevIndex !== undefined) {
      switch (channel.interpolation) {
        case 'STEP':
          if (isRotation) {
            quat.set(currentOutputQuat, outputData[prevIndex])
          } else {
            vec3.set(currentOutputVec3, outputData[prevIndex])
          }
          break
        case 'CUBICSPLINE': {
          const vec = isRotation ? vec4 : vec3
          const tt = t * t
          const ttt = tt * t

          // Each input value corresponds to three output values of the same type: in-tangent, data point, and out-tangent.
          // p0
          const prevPosition = vec.copy(outputData[prevIndex * 3 + 1])

          // p1
          const nextPos = vec.copy(outputData[nextIndex * 3 + 1])

          // m0 = (tk+1 - tk)bk
          const prevOutTangent = prevIndex
            ? vec.scale(vec.copy(outputData[prevIndex * 3 + 2]), scale)
            : vec.create()

          // m1 = (tk+1 - tk)ak+1
          const nextInTangent =
            nextIndex !== inputData.length - 1
              ? vec.scale(vec.copy(outputData[prevIndex * 3]), scale)
              : vec.create()

          // p(t) = (2t³ - 3t² + 1)p0 + (t³ - 2t² + t)m0 + (-2t³ + 3t²)p1 + (t³ - t²)m1
          const p0 = vec.scale(prevPosition, 2 * ttt - 3 * tt + 1)
          const m0 = vec.scale(prevOutTangent, ttt - 2 * tt + t)
          const p1 = vec.scale(nextPos, -2 * ttt + 3 * tt)
          const m1 = vec.scale(nextInTangent, ttt - tt)

          if (isRotation) {
            quat.set(
              currentOutputQuat,
              quat.normalize([
                p0[0] + m0[0] + p1[0] + m1[0],
                p0[1] + m0[1] + p1[1] + m1[1],
                p0[2] + m0[2] + p1[2] + m1[2],
                p0[3] + m0[3] + p1[3] + m1[3]
              ])
            )
          } else {
            vec3.set(
              currentOutputVec3,
              vec3.add(vec3.add(vec3.add(p0, m0), p1), m1)
            )
          }

          break
        }
        default:
          // LINEAR
          if (isRotation) {
            quat.slerp(
              quat.set(currentOutputQuat, outputData[prevIndex]),
              outputData[nextIndex],
              t
            )
          } else {
            vec3.set(
              currentOutputVec3,
              outputData[nextIndex].map((output, index) =>
                utils.lerp(outputData[prevIndex][index], output, t)
              )
            )
          }
      }

      if (isRotation) {
        channel.target.transform.set({
          rotation: quat.copy(currentOutputQuat)
        })
      } else if (channel.path === 'translation') {
        channel.target.transform.set({
          position: vec3.copy(currentOutputVec3)
        })
      } else if (channel.path === 'scale') {
        channel.target.transform.set({
          scale: vec3.copy(currentOutputVec3)
        })
      } else if (channel.path === 'weights') {
        channel.target.getComponent('Morph').set({
          weights: outputData[nextIndex].slice()
        })
      }
    }
  }
}

module.exports = function createMorph(opts) {
  return new Animation(opts)
}
<|endoftext|>


<commit_before>(function(){
/*
Logic Gate - An idealized or physical device implementing a Boolean function,
that is, it performs a logical operation on one or more logical inputs,
and produces a single logical output.

https://en.wikipedia.org/wiki/Logic_gates
https://en.wikipedia.org/wiki/AND_gate

Most gates take two inputs, however the NOT gate has only
one input.

*/

window.NotGate = function() {
    var that = this;
    that.getInputFn = function() {
        return function(signal) {
            if ('number' !== typeof signal) {
                throw new Error('Invalid input, expected number signal');
            }
            that._signal = signal === 0 ? 1 : 0;
            if (that._outputFn) that._outputFn(that._signal);
        };
    };
    that.setOutputFn = function(output) {
        if ('function' !== typeof output) {
            var e = new Error('Invalid output, expected function');
            console.log(e.stack);
                throw new Error('Invalid output, expected function');
        }
        that._outputFn = output;
    };
    return that;
};

var AND_GATE_MAP = [[0, 0],[0, 1]];

window.AndGate = function() {
    var that = this;
    that.super = new BaseGate(function(a, b) {
        return AND_GATE_MAP[a][b];
    });
    inherit(that);
    return that;
};

var OR_GATE_MAP = [[0, 1], [1,1]];

window.OrGate = function() {
    var that = this;
    that.super = new BaseGate(function(a, b) {
        return OR_GATE_MAP[a][b];
    });
    inherit(that);
    return that;
};

var NOR_GATE_MAP = [[1, 0],[0, 0]];

window.NorGate = function() {
    var that = this;
    that.super = new BaseGate(function(a, b) {
        return NOR_GATE_MAP[a][b];
    });
    inherit(that);return that;
};

function BaseGate(evaluateInputsFn) {
    var that = this;
    // NO-OP
    that._outputFn = function() {};

    /**
     * Get an input callback function from this transistor
     */
    that.getInputAFn = function() {
        return function(signal) {
            that._signalA = signal;
            that._evaluateInputs();
        };
    };

    /**
     * Get an input callback function from this transistor
     */
    that.getInputBFn = function() {
        return function(signal) {
            that._signalB = signal;
            that._evaluateInputs();
        };
    };

    /**
     * Connect an output callback function to this gate
     */
    that.setOutputFn = function(output) {
        if ('function' !== typeof output) {
                throw new Error('Invalid output, expected function');
        }
        that._outputFn = output;
    };

    that._evaluateInputs = function() {
        if ('function' === typeof that._outputFn &&
                'number'   === typeof that._signalA &&
                'number'   === typeof that._signalB) {
            if ((that._signalA !== 0 && that._signalA !== 1) ||
                (that._signalB !== 0 && that._signalB !== 1)) {
                throw new Error('Bad signal, expected 0 or 1 got ' + a + ', ' + b);
            }
            that._outputFn(
                evaluateInputsFn(that._signalA, that._signalB));

        } else {
            that._outputFn(0);
        }
    };

    return that;
}

function inherit(that) {
    that.getInputAFn = function(o) { return that.super.getInputAFn(o); };
    that.getInputBFn = function(o) { return that.super.getInputBFn(o); };
    that.setOutputFn = function(o) { return that.super.setOutputFn(o); };
}

})();<commit_msg>Adding NAND and XOR gates<commit_after>(function(){
/*
Logic Gate - An idealized or physical device implementing a Boolean function,
that is, it performs a logical operation on one or more logical inputs,
and produces a single logical output.

https://en.wikipedia.org/wiki/Logic_gates
https://en.wikipedia.org/wiki/AND_gate

Most gates take two inputs, however the NOT gate has only
one input.

*/

window.NotGate = function() {
    var that = this;
    that.getInputFn = function() {
        return function(signal) {
            if ('number' !== typeof signal) {
                throw new Error('Invalid input, expected number signal');
            }
            that._signal = signal === 0 ? 1 : 0;
            if (that._outputFn) that._outputFn(that._signal);
        };
    };
    that.setOutputFn = function(output) {
        if ('function' !== typeof output) {
            var e = new Error('Invalid output, expected function');
            console.log(e.stack);
                throw new Error('Invalid output, expected function');
        }
        that._outputFn = output;
    };
    return that;
};

var AND_GATE_MAP = [[0, 0],[0, 1]];

window.AndGate = function() {
    var that = this;
    that.super = new BaseGate(function(a, b) {
        return AND_GATE_MAP[a][b];
    });
    inherit(that);
    return that;
};

var OR_GATE_MAP = [[0, 1], [1,1]];

window.OrGate = function() {
    var that = this;
    that.super = new BaseGate(function(a, b) {
        return OR_GATE_MAP[a][b];
    });
    inherit(that);
    return that;
};

var NOR_GATE_MAP = [[1, 0],[0, 0]];

window.NOrGate = function() {
    var that = this;
    that.super = new BaseGate(function(a, b) {
        return NOR_GATE_MAP[a][b];
    });
    inherit(that);return that;
};

var NAND_GATE_MAP = [[1, 1],[1, 0]];

window.NAndGate = function() {
    var that = this;
    that.super = new BaseGate(function(a, b) {
        return NAND_GATE_MAP[a][b];
    });
    inherit(that);return that;
};

var XOR_GATE_MAP = [[0, 1],[1, 0]];

window.XOrGate = function() {
    var that = this;
    that.super = new BaseGate(function(a, b) {
        return XOR_GATE_MAP[a][b];
    });
    inherit(that);return that;
};

var XNOR_GATE_MAP = [[1, 0],[0, 1]];

window.XNOrGate = function() {
    var that = this;
    that.super = new BaseGate(function(a, b) {
        return XNOR_GATE_MAP[a][b];
    });
    inherit(that);return that;
};

function BaseGate(evaluateInputsFn) {
    var that = this;
    // NO-OP
    that._outputFn = function() {};

    /**
     * Get an input callback function from this transistor
     */
    that.getInputAFn = function() {
        return function(signal) {
            that._signalA = signal;
            that._evaluateInputs();
        };
    };

    /**
     * Get an input callback function from this transistor
     */
    that.getInputBFn = function() {
        return function(signal) {
            that._signalB = signal;
            that._evaluateInputs();
        };
    };

    /**
     * Connect an output callback function to this gate
     */
    that.setOutputFn = function(output) {
        if ('function' !== typeof output) {
                throw new Error('Invalid output, expected function');
        }
        that._outputFn = output;
    };

    that._evaluateInputs = function() {
        if ('function' === typeof that._outputFn &&
                'number'   === typeof that._signalA &&
                'number'   === typeof that._signalB) {
            if ((that._signalA !== 0 && that._signalA !== 1) ||
                (that._signalB !== 0 && that._signalB !== 1)) {
                throw new Error('Bad signal, expected 0 or 1 got ' + a + ', ' + b);
            }
            that._outputFn(
                evaluateInputsFn(that._signalA, that._signalB));

        } else {
            that._outputFn(0);
        }
    };

    return that;
}

function inherit(that) {
    that.getInputAFn = function(o) { return that.super.getInputAFn(o); };
    that.getInputBFn = function(o) { return that.super.getInputBFn(o); };
    that.setOutputFn = function(o) { return that.super.setOutputFn(o); };
}

})();<|endoftext|>


<commit_before>var gulp = require('gulp');
var filter = require('gulp-filter');
var cleancss = require('gulp-clean-css');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var confirm = require('gulp-prompt').confirm;
var rsync = require('gulp-rsync');
var replace = require('gulp-replace');
var octophant = require('octophant');
var inquirer = require('inquirer');
var exec = require('child_process').execSync;
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');

var CONFIG = require('../config.js');
var CURRENT_VERSION = require('../../package.json').version;
var NEXT_VERSION;

gulp.task('deploy', gulp.series('deploy:prompt', 'deploy:version', 'deploy:dist', 'deploy:plugins', 'deploy:settings', 'deploy:commit', 'deploy:templates'));

gulp.task('deploy:prep', gulp.series('deploy:prompt', 'deploy:version', 'deploy:dist', 'deploy:plugins', 'deploy:settings'));
gulp.task('deploy:dist', gulp.series('sass:foundation', 'javascript:foundation', 'deploy:dist:files'));

gulp.task('deploy:prompt', function(cb) {
  inquirer.prompt([{
    type: 'input',
    name: 'version',
    message: 'What version are we moving to? (Current version is ' + CURRENT_VERSION + ')'
  }])
  .then(function(res) {
    NEXT_VERSION = res.version;
    cb();
  });
});

// Bumps the version number in any file that has one
gulp.task('deploy:version', function() {
  return gulp.src(CONFIG.VERSIONED_FILES, { base: process.cwd() })
  .pipe(replace(CURRENT_VERSION, NEXT_VERSION))
  .pipe(gulp.dest('.'));
});

// Generates compiled CSS and JS files and sourcemaps and puts them in the dist/ folder
gulp.task('deploy:dist:files', function() {
  var cssFilter = filter(['**/*.css'], { restore: true });
  var jsFilter  = filter(['**/*.js'], { restore: true });
  var cssSourcemapFilter = filter(['**/*.css.map'], { restore: true });
  var jsSourcemapFilter = filter(['**/*.js.map'], { restore: true });
  var tsFilter  = filter(['**/*.ts'], { restore: true });

  return gulp.src(CONFIG.DIST_FILES)
    .pipe(plumber())

    // --- Source maps ---
    // * Copy sourcemaps to the dist folder
    // This is done first to avoid collision with minified-sourcemaps.
    .pipe(cssSourcemapFilter)
      .pipe(gulp.dest('./dist/css'))
      .pipe(cssSourcemapFilter.restore)
    .pipe(jsSourcemapFilter)
      .pipe(gulp.dest('./dist/js'))
      .pipe(jsSourcemapFilter.restore)

    // --- Source files ---
    // * Copy source files to dist folder
    // * Create minified files
    // * Create minified-sourcemaps based on standard sourcemaps.
    //   Sourcemaps are initialized before the ".min" renaming to be able retrieve
    //   original sourcemaps from source names.
    .pipe(cssFilter)
      .pipe(gulp.dest('./dist/css'))
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(rename({ suffix: '.min' }))
      .pipe(cleancss({ compatibility: 'ie9' }))
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest('./dist/css'))
      .pipe(cssFilter.restore)

    .pipe(jsFilter)
      .pipe(gulp.dest('./dist/js'))
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(rename({ suffix: '.min' }))
      .pipe(uglify())
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest('./dist/js'))
      .pipe(jsFilter.restore)

    // --- TypeScript files ---
    // * Copy typescript files to the dist folder
    .pipe(tsFilter)
      .pipe(gulp.dest('./dist/js'))
      .pipe(tsFilter.restore);
});

// Copies standalone JavaScript plugins to dist/ folder
gulp.task('deploy:plugins', function() {
  return gulp.src('_build/assets/js/plugins/*.js')
    .pipe(gulp.dest('dist/js/plugins'))
    .pipe(uglify())
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest('dist/js/plugins'));
});

// Generates a settings file
gulp.task('deploy:settings', function(done) {
  var options = {
    title: 'Foundation for Sites Settings',
    output: './scss/settings/_settings.scss',
    groups: {
      'grid': 'The Grid',
      'off-canvas': 'Off-canvas',
      'typography-base': 'Base Typography'
    },
    sort: [
      'global',
      'breakpoints',
      'grid',
      'typography-base',
      'typography-helpers'
    ],
    imports: ['util/util'],
    _foundationShim: true
  }

  octophant('./scss', options, done);
});

// Writes a commit with the changes to the version numbers
gulp.task('deploy:commit', function() {
  exec('git commit -am "Bump to version "' + NEXT_VERSION);
  exec('git tag v' + NEXT_VERSION);
  exec('git push origin develop --follow-tags');
});

// Uploads the documentation to the live server
gulp.task('deploy:docs', gulp.series('build', function() {
  return gulp.src('./_build/**')
    .pipe(confirm('Make sure everything looks right before you deploy.'))
    .pipe(rsync({
      root: './_build',
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/foundation-sites-6-docs'
    }));
}));

// Uploads the documentation to the live server in beta env
gulp.task('deploy:beta', gulp.series('build', function() {
  return gulp.src('./_build/**')
    .pipe(confirm('Make sure everything looks right before you deploy.'))
    .pipe(rsync({
      root: './_build',
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/scalingsexiness/foundation-sites-6-docs'
    }));
}));

// This part of the deploy process hasn't been tested! It should be done manually for now
gulp.task('deploy:templates', function(done) {
  // exec('git clone https://github.com/zurb/foundation-sites-template');
  // exec('cp scss/settings/_settings.scss foundation-sites-template/scss/_settings.scss');
  // exec('cd foundation-sites-template');
  // exec('git commit -am "Update settings file to match Foundation "' + NEXT_VERSION);
  // exec('git push origin master');
  // exec('cd ..');
  // exec('rm -rf foundation-sites-template');
  //
  // exec('git clone https://github.com/zurb/foundation-zurb-template');
  // exec('cp scss/settings/_settings.scss foundation-zurb-template/src/assets/scss/_settings.scss');
  // exec('cd foundation-zurb-template');
  // exec('git commit -am "Update settings file to match Foundation "' + NEXT_VERSION);
  // exec('git push origin master');
  // exec('cd ..');
  // exec('rm -rf foundation-zurb-template');
  done();
});

// The Customizer runs this function to generate files it needs
gulp.task('deploy:custom', gulp.series('sass:foundation', 'javascript:foundation', gulp.parallel(
  function () {
    return gulp.src('./_build/assets/css/foundation.css')
      .pipe(cleancss({ compatibility: 'ie9' }))
      .pipe(rename('foundation.min.css'))
      .pipe(gulp.dest('./_build/assets/css'));
  },
  function () {
    return gulp.src('_build/assets/js/foundation.js')
      .pipe(uglify())
      .pipe(rename('foundation.min.js'))
      .pipe(gulp.dest('./_build/assets/js'));
  }
)));
<commit_msg>chore: update sourcemaps of distributed JS plugins<commit_after>var gulp = require('gulp');
var filter = require('gulp-filter');
var cleancss = require('gulp-clean-css');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var confirm = require('gulp-prompt').confirm;
var rsync = require('gulp-rsync');
var replace = require('gulp-replace');
var octophant = require('octophant');
var inquirer = require('inquirer');
var exec = require('child_process').execSync;
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');

var CONFIG = require('../config.js');
var CURRENT_VERSION = require('../../package.json').version;
var NEXT_VERSION;

gulp.task('deploy', gulp.series('deploy:prompt', 'deploy:version', 'deploy:dist', 'deploy:plugins', 'deploy:settings', 'deploy:commit', 'deploy:templates'));

gulp.task('deploy:prep', gulp.series('deploy:prompt', 'deploy:version', 'deploy:dist', 'deploy:plugins', 'deploy:settings'));
gulp.task('deploy:dist', gulp.series('sass:foundation', 'javascript:foundation', 'deploy:dist:files'));
gulp.task('deploy:plugins', gulp.series('deploy:plugins:sources', 'deploy:plugins:sourcemaps'));

gulp.task('deploy:prompt', function(cb) {
  inquirer.prompt([{
    type: 'input',
    name: 'version',
    message: 'What version are we moving to? (Current version is ' + CURRENT_VERSION + ')'
  }])
  .then(function(res) {
    NEXT_VERSION = res.version;
    cb();
  });
});

// Bumps the version number in any file that has one
gulp.task('deploy:version', function() {
  return gulp.src(CONFIG.VERSIONED_FILES, { base: process.cwd() })
  .pipe(replace(CURRENT_VERSION, NEXT_VERSION))
  .pipe(gulp.dest('.'));
});

// Generates compiled CSS and JS files and sourcemaps and puts them in the dist/ folder
gulp.task('deploy:dist:files', function() {
  var cssFilter = filter(['**/*.css'], { restore: true });
  var jsFilter  = filter(['**/*.js'], { restore: true });
  var cssSourcemapFilter = filter(['**/*.css.map'], { restore: true });
  var jsSourcemapFilter = filter(['**/*.js.map'], { restore: true });
  var tsFilter  = filter(['**/*.ts'], { restore: true });

  return gulp.src(CONFIG.DIST_FILES)
    .pipe(plumber())

    // --- Source maps ---
    // * Copy sourcemaps to the dist folder
    // This is done first to avoid collision with minified-sourcemaps.
    .pipe(cssSourcemapFilter)
      .pipe(gulp.dest('./dist/css'))
      .pipe(cssSourcemapFilter.restore)
    .pipe(jsSourcemapFilter)
      .pipe(gulp.dest('./dist/js'))
      .pipe(jsSourcemapFilter.restore)

    // --- Source files ---
    // * Copy source files to dist folder
    // * Create minified files
    // * Create minified-sourcemaps based on standard sourcemaps.
    //   Sourcemaps are initialized before the ".min" renaming to be able retrieve
    //   original sourcemaps from source names.
    .pipe(cssFilter)
      .pipe(gulp.dest('./dist/css'))
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(rename({ suffix: '.min' }))
      .pipe(cleancss({ compatibility: 'ie9' }))
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest('./dist/css'))
      .pipe(cssFilter.restore)

    .pipe(jsFilter)
      .pipe(gulp.dest('./dist/js'))
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(rename({ suffix: '.min' }))
      .pipe(uglify())
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest('./dist/js'))
      .pipe(jsFilter.restore)

    // --- TypeScript files ---
    // * Copy typescript files to the dist folder
    .pipe(tsFilter)
      .pipe(gulp.dest('./dist/js'))
      .pipe(tsFilter.restore);
});

// Copies standalone JavaScript plugins to dist/ folder
gulp.task('deploy:plugins:sources', function () {
  return gulp.src('_build/assets/js/plugins/*.js')
    .pipe(gulp.dest('dist/js/plugins'))
    .pipe(sourcemaps.init({ loadMaps: true }))
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist/js/plugins'));
});

// Copies standalone JavaScript plugins sourcemaps to dist/ folder
gulp.task('deploy:plugins:sourcemaps', function () {
  return gulp.src('_build/assets/js/plugins/*.js.map')
    .pipe(gulp.dest('dist/js/plugins'));
});

// Generates a settings file
gulp.task('deploy:settings', function(done) {
  var options = {
    title: 'Foundation for Sites Settings',
    output: './scss/settings/_settings.scss',
    groups: {
      'grid': 'The Grid',
      'off-canvas': 'Off-canvas',
      'typography-base': 'Base Typography'
    },
    sort: [
      'global',
      'breakpoints',
      'grid',
      'typography-base',
      'typography-helpers'
    ],
    imports: ['util/util'],
    _foundationShim: true
  }

  octophant('./scss', options, done);
});

// Writes a commit with the changes to the version numbers
gulp.task('deploy:commit', function() {
  exec('git commit -am "Bump to version "' + NEXT_VERSION);
  exec('git tag v' + NEXT_VERSION);
  exec('git push origin develop --follow-tags');
});

// Uploads the documentation to the live server
gulp.task('deploy:docs', gulp.series('build', function() {
  return gulp.src('./_build/**')
    .pipe(confirm('Make sure everything looks right before you deploy.'))
    .pipe(rsync({
      root: './_build',
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/foundation-sites-6-docs'
    }));
}));

// Uploads the documentation to the live server in beta env
gulp.task('deploy:beta', gulp.series('build', function() {
  return gulp.src('./_build/**')
    .pipe(confirm('Make sure everything looks right before you deploy.'))
    .pipe(rsync({
      root: './_build',
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/scalingsexiness/foundation-sites-6-docs'
    }));
}));

// This part of the deploy process hasn't been tested! It should be done manually for now
gulp.task('deploy:templates', function(done) {
  // exec('git clone https://github.com/zurb/foundation-sites-template');
  // exec('cp scss/settings/_settings.scss foundation-sites-template/scss/_settings.scss');
  // exec('cd foundation-sites-template');
  // exec('git commit -am "Update settings file to match Foundation "' + NEXT_VERSION);
  // exec('git push origin master');
  // exec('cd ..');
  // exec('rm -rf foundation-sites-template');
  //
  // exec('git clone https://github.com/zurb/foundation-zurb-template');
  // exec('cp scss/settings/_settings.scss foundation-zurb-template/src/assets/scss/_settings.scss');
  // exec('cd foundation-zurb-template');
  // exec('git commit -am "Update settings file to match Foundation "' + NEXT_VERSION);
  // exec('git push origin master');
  // exec('cd ..');
  // exec('rm -rf foundation-zurb-template');
  done();
});

// The Customizer runs this function to generate files it needs
gulp.task('deploy:custom', gulp.series('sass:foundation', 'javascript:foundation', gulp.parallel(
  function () {
    return gulp.src('./_build/assets/css/foundation.css')
      .pipe(cleancss({ compatibility: 'ie9' }))
      .pipe(rename('foundation.min.css'))
      .pipe(gulp.dest('./_build/assets/css'));
  },
  function () {
    return gulp.src('_build/assets/js/foundation.js')
      .pipe(uglify())
      .pipe(rename('foundation.min.js'))
      .pipe(gulp.dest('./_build/assets/js'));
  }
)));
<|endoftext|>


<commit_before>var R = require('ramda')
var fa = require('fluent-arguments')
var sinon = require('sinon')
var ARG_RETURN_VAL = 'returnVal'
var ARG_RETURN_THIS = 'returnThis'

var setMethodToStub = R.curry(function (object, methodName) {
  object[ methodName ] = sinon.stub()
})

function configureStub (object, params) {
  if (params.hasOwnProperty(ARG_RETURN_THIS)) {
    object[ params.value ].returnsThis()
  } else if (params.hasOwnProperty(ARG_RETURN_VAL)) {
    object[ params.value ].returns(params[ ARG_RETURN_VAL ])
  }
}
var setMethodToStubWithParams = R.curry(function (object, params) {
  setMethodToStub(object, params.value)
  configureStub(object, params)
})

var stubMethodWithParams = R.curry(function (object, params) {
  object[ params.value ] && object[ params.value ].restore && object[ params.value ].restore()
  sinon.stub(object, params.value)
  configureStub(object, params)
})

var spyOnMethod = R.curry(function (object, methodName) {
  if (!(object[ methodName ] && object[ methodName ].isSinonProxy)) {
    sinon.spy(object, methodName)
  }
})

var copyAndSpyOnMethod = R.curry(function (object, source, methodName) {
  if (source[ methodName ].isSinonProxy) {
    object[ methodName ] = source[ methodName ]
  } else {
    object[ methodName ] = sinon.spy(source[ methodName ])
  }
})

var isPropFunction = R.curry(function (object, prop) {
  return !Object.getOwnPropertyDescriptor(object, prop).get && typeof object[ prop ] === 'function'
})

var applyToEachFunctionKeyInObject = function (appliedFunction, object) {
  R.compose(
    R.forEach(appliedFunction),
    R.filter(isPropFunction(object))
  )(Object.getOwnPropertyNames(object))
}

var applyToEachFunctionKeyInPrototypeChain = function (appliedFunction, object) {
  if (object) {
    applyToEachFunctionKeyInObject(appliedFunction, object)
    applyToEachFunctionKeyInPrototypeChain(appliedFunction, Object.getPrototypeOf(object))
  }
}

function getArrayFromArrayLikeObject (args) {
  return Array.prototype.slice.call(args)
}

var getInstanceIndexWithValidation = function (index, numInstances) {
  var instanceIndex = index || 0

  if (typeof index === 'undefined') {
    if (numInstances > 1) {
      throw new Error('Tried to access only instance of StubConstructor, but there were ' +
        numInstances + ' instances.')
    }
  }
  if (numInstances <= instanceIndex) {
    throw new Error('Tried to access StubConstructor instance ' + instanceIndex + ', but there were only ' +
      numInstances + ' instances.')
  }
  return instanceIndex
}

function getConstructorInstanceWithArgs (Constructor, constructorArgs) {
  function HelpConstructor (args) {
    return Constructor.apply(this, args)
  }

  HelpConstructor.prototype = Constructor.prototype
  return new HelpConstructor(constructorArgs)
}

function getStubConstructor (Target) {
  var instances = []
  var instanceArgs = []
  var methodParams = []
  var afterCreation

  function StubConstructor () {
    var instance = getConstructorInstanceWithArgs(function () {}, [])
    instanceArgs.push(getArrayFromArrayLikeObject(arguments))
    instances.push(instance)

    Target && applyToEachFunctionKeyInPrototypeChain(setMethodToStub(instance), Target.prototype)
    methodParams.forEach(setMethodToStubWithParams(instance))
    afterCreation && afterCreation(instance)
    return instance
  }

  function withMethods (methods) {
    methodParams = methods
    return this
  }

  StubConstructor.withMethods = fa.createFunc(withMethods)

  StubConstructor.afterCreation = function (onAfterCreation) {
    afterCreation = onAfterCreation
    return this
  }

  StubConstructor.getInstances = function () {
    return instances
  }

  StubConstructor.getInstance = function (index) {
    return instances[ getInstanceIndexWithValidation(index, instances.length) ]
  }

  StubConstructor.getInstancesArgs = function () {
    return instanceArgs
  }

  StubConstructor.getInstanceArgs = function (index) {
    return instanceArgs[ getInstanceIndexWithValidation(index, instances.length) ]
  }

  Target && applyToEachFunctionKeyInObject(setMethodToStub(StubConstructor), Target)
  return StubConstructor
}

function getSpyConstructor (Target) {
  var instances = []
  var instanceArgs = []
  var methodParams = []
  var afterCreation

  function SpyConstructor () {
    var instance = getConstructorInstanceWithArgs(Target, arguments)
    instanceArgs.push(getArrayFromArrayLikeObject(arguments))
    instances.push(instance)

    Target && applyToEachFunctionKeyInPrototypeChain(spyOnMethod(instance), instance)
    methodParams.forEach(stubMethodWithParams(instance))
    afterCreation && afterCreation(instance)
    return instance
  }

  function withStubs (methods) {
    methodParams = methods
    return this
  }

  SpyConstructor.withStubs = fa.createFunc(withStubs)

  SpyConstructor.afterCreation = function (onAfterCreation) {
    afterCreation = onAfterCreation
    return this
  }

  SpyConstructor.getInstances = function () {
    return instances
  }

  SpyConstructor.getInstance = function (index) {
    return instances[ getInstanceIndexWithValidation(index, instances.length) ]
  }

  SpyConstructor.getInstancesArgs = function () {
    return instanceArgs
  }

  SpyConstructor.getInstanceArgs = function (index) {
    return instanceArgs[ getInstanceIndexWithValidation(index, instances.length) ]
  }

  Target && applyToEachFunctionKeyInObject(copyAndSpyOnMethod(SpyConstructor, Target), Target)
  return SpyConstructor
}

function getMethodStubs (methodParams) {
  var result = {}

  methodParams.forEach(setMethodToStubWithParams(result))
  return result
}

module.exports = {
  getStubConstructor: getStubConstructor,
  getSpyConstructor: getSpyConstructor,
  getMethodStubs: fa.createFunc(getMethodStubs),
  returning: fa.createArg({ args: [ ARG_RETURN_VAL ], extendsPrevious: true }),
  returningThis: fa.createArg({ extra: { returnThis: true }, extendsPrevious: true })
}
<commit_msg>refactor(Constructors): Unify Constructors<commit_after>var R = require('ramda')
var fa = require('fluent-arguments')
var sinon = require('sinon')
var ARG_RETURN_VAL = 'returnVal'
var ARG_RETURN_THIS = 'returnThis'

var setMethodToStub = R.curry(function (object, methodName) {
  object[ methodName ] = sinon.stub()
})

function configureStub (object, params) {
  if (params.hasOwnProperty(ARG_RETURN_THIS)) {
    object[ params.value ].returnsThis()
  } else if (params.hasOwnProperty(ARG_RETURN_VAL)) {
    object[ params.value ].returns(params[ ARG_RETURN_VAL ])
  }
}
var setMethodToStubWithParams = R.curry(function (object, params) {
  setMethodToStub(object, params.value)
  configureStub(object, params)
})

var stubMethodWithParams = R.curry(function (object, params) {
  object[ params.value ] && object[ params.value ].restore && object[ params.value ].restore()
  sinon.stub(object, params.value)
  configureStub(object, params)
})

var spyOnMethod = R.curry(function (object, methodName) {
  if (!(object[ methodName ] && object[ methodName ].isSinonProxy)) {
    sinon.spy(object, methodName)
  }
})

var copyAndSpyOnMethod = R.curry(function (object, source, methodName) {
  if (source[ methodName ].isSinonProxy) {
    object[ methodName ] = source[ methodName ]
  } else {
    object[ methodName ] = sinon.spy(source[ methodName ])
  }
})

var isPropFunction = R.curry(function (object, prop) {
  return !Object.getOwnPropertyDescriptor(object, prop).get && typeof object[ prop ] === 'function'
})

var applyToEachFunctionKeyInObject = function (appliedFunction, object) {
  R.compose(
    R.forEach(appliedFunction),
    R.filter(isPropFunction(object))
  )(Object.getOwnPropertyNames(object))
}

var applyToEachFunctionKeyInPrototypeChain = function (appliedFunction, object) {
  if (object) {
    applyToEachFunctionKeyInObject(appliedFunction, object)
    applyToEachFunctionKeyInPrototypeChain(appliedFunction, Object.getPrototypeOf(object))
  }
}

function getArrayFromArrayLikeObject (args) {
  return Array.prototype.slice.call(args)
}

var getInstanceIndexWithValidation = function (index, numInstances) {
  var instanceIndex = index || 0

  if (typeof index === 'undefined') {
    if (numInstances > 1) {
      throw new Error('Tried to access only instance of StubConstructor, but there were ' +
        numInstances + ' instances.')
    }
  }
  if (numInstances <= instanceIndex) {
    throw new Error('Tried to access StubConstructor instance ' + instanceIndex + ', but there were only ' +
      numInstances + ' instances.')
  }
  return instanceIndex
}

function getConstructorInstanceWithArgs (Constructor, constructorArgs) {
  function HelpConstructor (args) {
    return Constructor.apply(this, args)
  }

  HelpConstructor.prototype = Constructor.prototype
  return new HelpConstructor(constructorArgs)
}

function getStubConstructorProperties (Target) {
  return {
    SourceConstructor: function () {},
    processInstanceMethod: setMethodToStub,
    getInstanceMethodNameSource: function () { return Target.prototype },
    processClassMethod: function (StubOrSpyConstructor) { return setMethodToStub(StubOrSpyConstructor) },
    configureMethodsKey: 'withMethods',
    configureMethod: setMethodToStubWithParams
  }
}

function getSpyConstructorProperties (Target) {
  return {
    SourceConstructor: Target,
    processInstanceMethod: spyOnMethod,
    getInstanceMethodNameSource: function (instance) { return instance },
    processClassMethod: function (StubOrSpyConstructor) { return copyAndSpyOnMethod(StubOrSpyConstructor, Target) },
    configureMethodsKey: 'withStubs',
    configureMethod: stubMethodWithParams
  }
}

function getStubOrSpyConstructor (getConstructorProperties) {
  return function (Target) {
    var constructorProps = getConstructorProperties(Target)
    var instances = []
    var instanceArgs = []
    var methodParams = []
    var afterCreation

    function StubOrSpyConstructor () {
      var instance = getConstructorInstanceWithArgs(constructorProps.SourceConstructor, arguments)
      instanceArgs.push(getArrayFromArrayLikeObject(arguments))
      instances.push(instance)

      Target && applyToEachFunctionKeyInPrototypeChain(
        constructorProps.processInstanceMethod(instance), constructorProps.getInstanceMethodNameSource(instance))
      methodParams.forEach(constructorProps.configureMethod(instance))
      afterCreation && afterCreation(instance)
      return instance
    }

    function configureMethods (methods) {
      methodParams = methods
      return this
    }

    StubOrSpyConstructor[ constructorProps.configureMethodsKey ] = fa.createFunc(configureMethods)

    StubOrSpyConstructor.afterCreation = function (onAfterCreation) {
      afterCreation = onAfterCreation
      return this
    }

    StubOrSpyConstructor.getInstances = function () {
      return instances
    }

    StubOrSpyConstructor.getInstance = function (index) {
      return instances[ getInstanceIndexWithValidation(index, instances.length) ]
    }

    StubOrSpyConstructor.getInstancesArgs = function () {
      return instanceArgs
    }

    StubOrSpyConstructor.getInstanceArgs = function (index) {
      return instanceArgs[ getInstanceIndexWithValidation(index, instances.length) ]
    }

    Target && applyToEachFunctionKeyInObject(constructorProps.processClassMethod(StubOrSpyConstructor), Target)
    return StubOrSpyConstructor
  }
}

function getMethodStubs (methodParams) {
  var result = {}

  methodParams.forEach(setMethodToStubWithParams(result))
  return result
}

module.exports = {
  getStubConstructor: getStubOrSpyConstructor(getStubConstructorProperties),
  getSpyConstructor: getStubOrSpyConstructor(getSpyConstructorProperties),
  getMethodStubs: fa.createFunc(getMethodStubs),
  returning: fa.createArg({ args: [ ARG_RETURN_VAL ], extendsPrevious: true }),
  returningThis: fa.createArg({ extra: { returnThis: true }, extendsPrevious: true })
}
<|endoftext|>


<commit_before>module.exports = (function() {
  return {
    toTokenStream: toTokenStream
  }

  function getToken(stream, source) {
    var rx_token = /^((\s+)|([a-zA-Z][a-zA-Z0-9_]*)|(\()|(\))|(!=|==|<=|>=|<|>)|(-|\+)|(\*|\/|,))(.*)$/;

    // 0 source
    // 1 match
    // 2 whitespace
    // 3 identifier
    // 4 open bracket
    // 5 close bracket
    // 6 relational operators
    // 7 unary or binary operators (+ or -)
    // 8 binary operators (* or / or ,)
    // 9 the rest

    var results = source.match(rx_token);
    var value = results[1];
    var rest = results[9];
    stream.push(value);

    return rest;
  }

  function toTokenStream(source) {
    var stream = [];
    var safety = 0;
    var len = source.length;

    while (source.length > 0 && safety < len) {
      source = getToken(stream, source);
      safety++;
    }

    return stream;
  }
})();
<commit_msg>style cleanup<commit_after>module.exports = (function() {
  return {
    toTokenStream: toTokenStream
  }

  function getToken(stream, source) {
    var rx_token = /^((\s+)|([a-zA-Z][a-zA-Z0-9_]*)|(\()|(\))|(!=|==|<=|>=|<|>)|(-|\+)|(\*|\/|,))(.*)$/;
    var results;
    var value;
    var rest;

    // 0 source
    // 1 match
    // 2 whitespace
    // 3 identifier
    // 4 open bracket
    // 5 close bracket
    // 6 relational operators
    // 7 unary or binary operators (+ or -)
    // 8 binary operators (* or / or ,)
    // 9 the rest

    results = source.match(rx_token);
    value = results[1];
    rest = results[9];

    stream.push(value);

    return rest;
  }

  function toTokenStream(source) {
    var stream = [];
    var safety = 0;
    var len = source.length;

    while (source.length > 0 && safety < len) {
      source = getToken(stream, source);
      safety++;
    }

    return stream;
  }
})();
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name ocwUiApp.controller:DatasetSelectCtrl
 * @description
 * # DatasetSelectCtrl
 * Controller of the ocwUiApp
 */
angular.module('ocwUiApp')
  .controller('DatasetSelectCtrl', ['$scope', 'selectedDatasetInformation',
    function($scope, selectedDatasetInformation) {
      // Grab a copy of the datasets so we can display a count to the user!
      $scope.datasetCount = selectedDatasetInformation.getDatasets();

      $scope.shouldDisableClearButton = function() {
        return (selectedDatasetInformation.getDatasetCount() === 0);
      };

      $scope.clearDatasets = function() {
        selectedDatasetInformation.clearDatasets();
      };

      $scope.open = function () {
        $scope.datasetSelect = true;
      };

      $scope.close = function () {
        $scope.datasetSelect = false;
      };

      $scope.opts = {
        backdropFade: true,
        dialogFade: true,
      };

      $scope.templates = [
        {title:'Local File', url: 'partials/selectObservation.html'},
        {title:'RCMED', url: 'partials/selectRcmed.html'},
        {title:'ESG', disabled: true}
      ];

      $scope.template = $scope.templates[0];
    }
  ]);
<commit_msg>Fix view routing in DatasetSelectCtrl<commit_after>'use strict';

/**
 * @ngdoc function
 * @name ocwUiApp.controller:DatasetSelectCtrl
 * @description
 * # DatasetSelectCtrl
 * Controller of the ocwUiApp
 */
angular.module('ocwUiApp')
  .controller('DatasetSelectCtrl', ['$scope', 'selectedDatasetInformation',
    function($scope, selectedDatasetInformation) {
      // Grab a copy of the datasets so we can display a count to the user!
      $scope.datasetCount = selectedDatasetInformation.getDatasets();

      $scope.shouldDisableClearButton = function() {
        return (selectedDatasetInformation.getDatasetCount() === 0);
      };

      $scope.clearDatasets = function() {
        selectedDatasetInformation.clearDatasets();
      };

      $scope.open = function () {
        $scope.datasetSelect = true;
      };

      $scope.close = function () {
        $scope.datasetSelect = false;
      };

      $scope.opts = {
        backdropFade: true,
        dialogFade: true,
      };

      $scope.templates = [
        {title:'Local File', url: 'views/selectObservation.html'},
        {title:'RCMED', url: 'views/selectRcmed.html'},
        {title:'ESG', disabled: true}
      ];

      $scope.template = $scope.templates[0];
    }
  ]);
<|endoftext|>


<commit_before>var should = require("should");
var path = require("path");

var webpack = require("../lib/webpack");

var base = path.join(__dirname, "fixtures", "errors");

describe("Errors", function() {
	function getErrors(options, callback) {
		options.context = base;
		var c = webpack(options);
		var files = {};
		c.outputFileSystem = {
			join: path.join.bind(path),
			mkdirp: function(path, callback) {
				callback();
			},
			writeFile: function(name, content, callback) {
				files[name] = content.toString("utf-8");
				callback();
			}
		};
		c.run(function(err, stats) {
			if(err) throw err;
			should.strictEqual(typeof stats, "object");
			stats = stats.toJson({ errorDetails: false });
			should.strictEqual(typeof stats, "object");
			stats.should.have.property("errors");
			stats.should.have.property("warnings");
			Array.isArray(stats.errors).should.be.ok;
			Array.isArray(stats.warnings).should.be.ok;
			callback(stats.errors, stats.warnings);
		});
	}
	it("should throw an error if file doesn't exist", function(done) {
		getErrors({
			entry: "./missingFile"
		}, function(errors, warnings) {
			errors.length.should.be.eql(2);
			warnings.length.should.be.eql(0);
			var lines = errors[0].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/missing/);
			lines[2].should.match(/missingFile.js 4:0/);
			var lines = errors[1].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/dir\/missing2/);
			lines[2].should.match(/missingFile.js 12:9/);
			done();
		});
	});
	it("should report require.extensions as unsupported", function(done) {
		getErrors({
			entry: "./require.extensions"
		}, function(errors, warnings) {
			errors.length.should.be.eql(0);
			warnings.length.should.be.eql(1);
			var lines = warnings[0].split("\n");
			lines[0].should.match(/require.extensions\.js/);
			lines[1].should.match(/require.extensions is not supported by webpack/);
			done();
		});
	});
	it("should throw an error if you try to require an entry point", function(done) {
		getErrors({
			entry: {
				a: "./require-entry-point",
				b: "./entry-point",
				c: ["./entry-point2"]
			}
		}, function(errors, warnings) {
			errors.length.should.be.eql(2);
			warnings.length.should.be.eql(0);
			var lines = errors[0].split("\n");
			lines[0].should.match(/require-entry-point\.js/);
			lines[1].should.match(/a dependency to an entry point is not allowed/);
			lines = errors[1].split("\n");
			lines[0].should.match(/require-entry-point\.js/);
			lines[1].should.match(/a dependency to an entry point is not allowed/);
			done();
		});
	});
	it("should warn about case-sensitive module names", function(done) {
		getErrors({
			entry: "./case-sensitive"
		}, function(errors, warnings) {
			if(errors.length === 0) {
				warnings.length.should.be.eql(2);
				var lines = warnings[0].split("\n");
				lines[0].should.match(/file\.js/);
				lines = warnings[1].split("\n");
				lines[0].should.match(/FILE\.js/);
			} else {
				errors.length.should.be.eql(1);
				warnings.length.should.be.eql(0);
			}
			done();
		});
	});
});<commit_msg>fixes errors test<commit_after>var should = require("should");
var path = require("path");

var webpack = require("../lib/webpack");

var base = path.join(__dirname, "fixtures", "errors");

describe("Errors", function() {
	function getErrors(options, callback) {
		options.context = base;
		var c = webpack(options);
		var files = {};
		c.outputFileSystem = {
			join: path.join.bind(path),
			mkdirp: function(path, callback) {
				callback();
			},
			writeFile: function(name, content, callback) {
				files[name] = content.toString("utf-8");
				callback();
			}
		};
		c.run(function(err, stats) {
			if(err) throw err;
			should.strictEqual(typeof stats, "object");
			stats = stats.toJson({ errorDetails: false });
			should.strictEqual(typeof stats, "object");
			stats.should.have.property("errors");
			stats.should.have.property("warnings");
			Array.isArray(stats.errors).should.be.ok;
			Array.isArray(stats.warnings).should.be.ok;
			callback(stats.errors, stats.warnings);
		});
	}
	it("should throw an error if file doesn't exist", function(done) {
		getErrors({
			entry: "./missingFile"
		}, function(errors, warnings) {
			errors.length.should.be.eql(2);
			warnings.length.should.be.eql(0);
			errors.sort();
			var lines = errors[0].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/dir\/missing2/);
			lines[2].should.match(/missingFile.js 12:9/);
			var lines = errors[1].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/missing/);
			lines[2].should.match(/missingFile.js 4:0/);
			done();
		});
	});
	it("should report require.extensions as unsupported", function(done) {
		getErrors({
			entry: "./require.extensions"
		}, function(errors, warnings) {
			errors.length.should.be.eql(0);
			warnings.length.should.be.eql(1);
			var lines = warnings[0].split("\n");
			lines[0].should.match(/require.extensions\.js/);
			lines[1].should.match(/require.extensions is not supported by webpack/);
			done();
		});
	});
	it("should throw an error if you try to require an entry point", function(done) {
		getErrors({
			entry: {
				a: "./require-entry-point",
				b: "./entry-point",
				c: ["./entry-point2"]
			}
		}, function(errors, warnings) {
			errors.length.should.be.eql(2);
			warnings.length.should.be.eql(0);
			var lines = errors[0].split("\n");
			lines[0].should.match(/require-entry-point\.js/);
			lines[1].should.match(/a dependency to an entry point is not allowed/);
			lines = errors[1].split("\n");
			lines[0].should.match(/require-entry-point\.js/);
			lines[1].should.match(/a dependency to an entry point is not allowed/);
			done();
		});
	});
	it("should warn about case-sensitive module names", function(done) {
		getErrors({
			entry: "./case-sensitive"
		}, function(errors, warnings) {
			if(errors.length === 0) {
				warnings.length.should.be.eql(2);
				var lines = warnings[0].split("\n");
				lines[0].should.match(/file\.js/);
				lines = warnings[1].split("\n");
				lines[0].should.match(/FILE\.js/);
			} else {
				errors.length.should.be.eql(1);
				warnings.length.should.be.eql(0);
			}
			done();
		});
	});
});<|endoftext|>


<commit_before>/**
 * Not type checking this file because flow doesn't like attaching
 * properties to Elements.
 */

import { warn } from 'core/util/index'
import { isAndroid, isIE9 } from 'web/util/index'

/* istanbul ignore if */
if (isIE9) {
  // http://www.matts411.com/post/internet-explorer-9-oninput/
  document.addEventListener('selectionchange', () => {
    const el = document.activeElement
    if (el && el.vmodel) {
      trigger(el, 'input')
    }
  })
}

export default {
  bind (el, binding, vnode) {
    if (process.env.NODE_ENV !== 'production') {
      if (!vnode.tag.match(/input|select|textarea/)) {
        warn(
          `v-model is not supported on element type: <${vnode.tag}>. ` +
          'If you are working with contenteditable, it\'s recommended to ' +
          'wrap a library dedicated for that purpose inside a custom component.',
          vnode.context
        )
      }
    }
    if (vnode.tag === 'select') {
      setSelected(el, binding.value)
    } else {
      if (!isAndroid) {
        el.addEventListener('compositionstart', onCompositionStart)
        el.addEventListener('compositionend', onCompositionEnd)
      }
      /* istanbul ignore if */
      if (isIE9) {
        el.vmodel = true
      }
    }
  },
  postupdate (el, binding, vnode) {
    const val = binding.value
    if (vnode.tag === 'select') {
      setSelected(el, val)
      // in case the options rendered by v-for have changed,
      // it's possible that the value is out-of-sync with the rendered options.
      // detect such cases and filter out values that no longer has a matchig
      // option in the DOM.
      const needReset = el.multiple
        ? val.some(v => hasNoMatchingOption(v, el.options))
        : hasNoMatchingOption(val, el.options)
      if (needReset) {
        trigger(el, 'change')
      }
    }
  },
  unbind (el, binding, vnode) {
    if (vnode.tag !== 'select' && !isAndroid) {
      el.removeEventListener('compositionstart', onCompositionStart)
      el.removeEventListener('compositionend', onCompositionEnd)
    }
  }
}

function setSelected (el, value) {
  const isMultiple = el.multiple
  if (!isMultiple) {
    el.selectedIndex = -1
  }
  for (let i = 0, l = el.options.length; i < l; i++) {
    const option = el.options[i]
    if (isMultiple) {
      option.selected = value.indexOf(getValue(option)) > -1
    } else {
      if (getValue(option) === value) {
        el.selectedIndex = i
        break
      }
    }
  }
}

function hasNoMatchingOption (value, options) {
  for (let i = 0, l = options.length; i < l; i++) {
    if (getValue(options[i]) === value) {
      return false
    }
  }
  return true
}

function getValue (option) {
  return '_value' in option
    ? option._value
    : option.value || option.text
}

function onCompositionStart (e) {
  e.target.composing = true
}

function onCompositionEnd (e) {
  e.target.composing = false
  trigger(e.target, 'input')
}

function trigger (el, type) {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}
<commit_msg>no need for unbind in model runtime<commit_after>/**
 * Not type checking this file because flow doesn't like attaching
 * properties to Elements.
 */

import { warn } from 'core/util/index'
import { isAndroid, isIE9 } from 'web/util/index'

/* istanbul ignore if */
if (isIE9) {
  // http://www.matts411.com/post/internet-explorer-9-oninput/
  document.addEventListener('selectionchange', () => {
    const el = document.activeElement
    if (el && el.vmodel) {
      trigger(el, 'input')
    }
  })
}

export default {
  bind (el, binding, vnode) {
    if (process.env.NODE_ENV !== 'production') {
      if (!vnode.tag.match(/input|select|textarea/)) {
        warn(
          `v-model is not supported on element type: <${vnode.tag}>. ` +
          'If you are working with contenteditable, it\'s recommended to ' +
          'wrap a library dedicated for that purpose inside a custom component.',
          vnode.context
        )
      }
    }
    if (vnode.tag === 'select') {
      setSelected(el, binding.value)
    } else {
      if (!isAndroid) {
        el.addEventListener('compositionstart', onCompositionStart)
        el.addEventListener('compositionend', onCompositionEnd)
      }
      /* istanbul ignore if */
      if (isIE9) {
        el.vmodel = true
      }
    }
  },
  postupdate (el, binding, vnode) {
    const val = binding.value
    if (vnode.tag === 'select') {
      setSelected(el, val)
      // in case the options rendered by v-for have changed,
      // it's possible that the value is out-of-sync with the rendered options.
      // detect such cases and filter out values that no longer has a matchig
      // option in the DOM.
      const needReset = el.multiple
        ? val.some(v => hasNoMatchingOption(v, el.options))
        : hasNoMatchingOption(val, el.options)
      if (needReset) {
        trigger(el, 'change')
      }
    }
  }
}

function setSelected (el, value) {
  const isMultiple = el.multiple
  if (!isMultiple) {
    el.selectedIndex = -1
  }
  for (let i = 0, l = el.options.length; i < l; i++) {
    const option = el.options[i]
    if (isMultiple) {
      option.selected = value.indexOf(getValue(option)) > -1
    } else {
      if (getValue(option) === value) {
        el.selectedIndex = i
        break
      }
    }
  }
}

function hasNoMatchingOption (value, options) {
  for (let i = 0, l = options.length; i < l; i++) {
    if (getValue(options[i]) === value) {
      return false
    }
  }
  return true
}

function getValue (option) {
  return '_value' in option
    ? option._value
    : option.value || option.text
}

function onCompositionStart (e) {
  e.target.composing = true
}

function onCompositionEnd (e) {
  e.target.composing = false
  trigger(e.target, 'input')
}

function trigger (el, type) {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var path = require('path');
var Ekko = require('availity-ekko');
var proxy = require('proxy-middleware');
var _ = require('lodash');

var config = require('../config');

var servers = {
  web: {
    host: '0.0.0.0',
    port: 9999
  }
};

gulp.task('server:rest', function () {
  var ekko = new Ekko();
  return ekko.start({
    development: {
      data: path.join(config.project.path, '/data'),
      routes: path.join(config.project.path, './routes.json'),
      servers: servers
    }
  });
});

gulp.task('server:sync', ['server:rest'], function(cb) {
  var browserSync = require('browser-sync');
  var url = require('url');
  var path = require('path');
  var fs = require('fs');
  var config = require('../config');

  // Parse out url and create the following config:
  //
  // EX:
  //
  // {
  //  host: localhost,
  //  port: 3000
  //  route: /api
  //
  // }
  var _url = _.template('http://localhost:<%= port %>/');
  var proxyOptions = url.parse(_url({port: servers.web.port}));
  proxyOptions.route = '/api';

  browserSync({
    notify: true,
    logPrefix: 'browersync',
    server: {
      baseDir: config.sync.src,
      middleware: [
        // Middleware #1: Allow web page requests without .html file extension in URLs
        function(req, res, next) {
          var uri = url.parse(req.url);
          if(uri.pathname.length > 1 && path.extname(uri.pathname) === '' && fs.existsSync('./dest' + uri.pathname + '.html')) {
            req.url = uri.pathname + '.html' + (uri.search || '');
          }
          next();
        },
        // Middleware #2: Proxy request to availity-ekko server
        proxy(proxyOptions)
      ]
    }
  }, cb);

});

<commit_msg>update proxy configuration to Ekko server<commit_after>var gulp = require('gulp');
var path = require('path');
var Ekko = require('availity-ekko');
var proxyMiddleware = require('http-proxy-middleware');
var _ = require('lodash');

var config = require('../config');

var servers = {
  web: {
    host: '0.0.0.0',
    port: 9999
  }
};

gulp.task('server:rest', function () {
  var ekko = new Ekko();
  return ekko.start({
    development: {
      data: path.join(config.project.path, '/data'),
      routes: path.join(config.project.path, './routes.json'),
      servers: servers
    }
  });
});

gulp.task('server:sync', ['server:rest'], function(cb) {
  var browserSync = require('browser-sync');
  var url = require('url');
  var path = require('path');
  var fs = require('fs');
  var config = require('../config');

  // Parse out url and create the following config:
  //
  // EX:
  //
  // {
  //  host: localhost,
  //  port: 3000
  //  route: /api
  //
  // }

  var _url = _.template('http://localhost:<%= port %>/');
  var proxyUrl = _url({port: servers.web.port});
  var apiProxy = proxyMiddleware('/api', {target: proxyUrl});

  browserSync({
    notify: true,
    logPrefix: 'browersync',
    server: {
      baseDir: config.sync.src,
      middleware: [
        // Middleware #1: proxy
        apiProxy,

        // Middleware #2: Allow web page requests without .html file extension in URLs
        function(req, res, next) {
          var uri = url.parse(req.url);
          if(uri.pathname.length > 1 && path.extname(uri.pathname) === '' && fs.existsSync('./dest' + uri.pathname + '.html')) {
            req.url = uri.pathname + '.html' + (uri.search || '');
          }
          next();
        }
      ]
    }
  }, cb);

});

<|endoftext|>


<commit_before>import { WidthSpriteSheetHero, HeightSpriteSheetHero, Size, CursorSize, Width, Height, HudText, HudTextX, HudTextY } from '../Constants.js';
import { Tileset, Level1, Levels, HeroSprite } from '../ConstantsKey.js';
import Character from 'objects/Character';
import InformationString from 'objects/InformationString';

import MapManager from "objects/MapManager";
import Controls from "objects/Controls";

class MainView extends Phaser.State {

  constructor() {
    super();
  }

  init(indexLevel) {
    this.indexLevel = indexLevel || 1;
    this.hasLevel = Object.keys(Levels).length >= this.indexLevel;
    if(!this.game.controls) {
      let controls = new Controls();
      controls.PostMortemDefaultConfig();
      this.game.controls = controls;
    }
    //no more levels :|
  }

  create() {
    if(!this.hasLevel) {
      this.game.goToMenu();
    } else {

      this.game.physics.startSystem(Phaser.Physics.ARCADE);
      // Add the physics engine to all game objects
      this.game.world.enableBody = true;

      this.map = this.game.add.tilemap(Levels[`Level${this.indexLevel}`].key);
      this.map.addTilesetImage(Levels[`Level${this.indexLevel}`].key, Tileset.key);

      this.map.createLayer('thirdLayer');
      this.map.createLayer('secondLayer');
      this.map.createLayer('firstLayer');
      // This resizes the game world to match the layer dimensions
      this.collisionLayer = this.map.createLayer('colissionLayer');
      this.map.setCollisionByExclusion([], true, this.collisionLayer);

      this.collisionLayer.resizeWorld();

      this.hero = new Character(this.game, Levels[`Level${this.indexLevel}`].playerPosition.x , Levels[`Level${this.indexLevel}`].playerPosition.y, HeroSprite.key, 0);
      this.game.add.existing(this.hero);
      this.game.camera.follow(this.hero);

      this.marker = null;
      this.createTileSelector();
      this.game.input.addMoveCallback(this.updateMarker, this);

      this.mapManager = new MapManager(this.map, Levels[`Level${this.indexLevel}`].lastLayer);
      this.mapManager.setUpCollisionLayer(this.collisionLayer);

      this.text = new InformationString(this.game, Width/2, Levels[`Level${this.indexLevel}`].text );
      this.game.add.existing(this.text);
      this.text.blink();

      this.hud = this.game.add.text(400, 400, HudText, { font: "bold 22px Arial", fill: '#FFFFFF' });
      this.hud.x = this.game.camera.x + HudTextX;
      this.hud.y = this.game.camera.y + HudTextY;

      this.keyRemoveLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("undoLayer"));
      this.keyRemoveLayer.onDown.add(this.eraseBlockKeyboard, this);
      this.keyUndoLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("removeLayer"));
      this.keyUndoLayer.onDown.add(this.undoBlockKeyboard, this);

      this.keyUpLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("moveUpCursor"));
      this.keyUpLayer.onDown.add(this.moveUp, this);
      this.keyDownLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("moveDownCursor"));
      this.keyDownLayer.onDown.add(this.moveDown, this);
      this.keyLeftLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("moveLeftCursor"));
      this.keyLeftLayer.onDown.add(this.moveLeft, this);
      this.keyRightLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("moveRightCursor"));
      this.keyRightLayer.onDown.add(this.moveRight, this);

      this.game.time.advancedTiming = true;
    }
  }

  update() {
    this.game.physics.arcade.collide(this.hero, this.collisionLayer, this.additionalCheck, this.hasPortal , this);
    if(this.hero.y > Height + this.hero.height) {
      this.game.reset();
    }

    this.updateGui();
  }

  updateGui() {
    this.hud.setText(HudText + this.mapManager.currentGems + " / " + this.mapManager.nbGems);
    this.hud.x = this.game.camera.x + HudTextX;
    this.hud.y = this.game.camera.y + HudTextY;

  }

  hasPortal(tile1, tile2) {
    if(tile2.properties && tile2.properties.portal == 1 && !this.mapManager.portalEnable()) {
      return false;
    }
    return true;
  }

  additionalCheck(tile1, tile2) {
    if(!tile2.properties) {
      return;
    }

    if(tile2.properties.layer_gem == 1) {
      if(tile2.properties.layer_destroy) {
        this.mapManager.removeLayer();
      } else if (tile2.properties.layer_rollback) {
        this.mapManager.undoLayer();
      }
    }

    if(tile2.properties.is_gem == 1) {
      this.map.removeTile(tile2.x, tile2.y, "colissionLayer").destroy();
      this.mapManager.killGem();
      return;
    }

    if(tile2.properties.portal == 1 && this.mapManager.portalEnable()) {
      //maybe make an animation
      this.game.nextLevel();
    }
  }

  preload() {
    this.game.load.spritesheet(HeroSprite.key, `res/${HeroSprite.path}`, WidthSpriteSheetHero, HeightSpriteSheetHero);
    this.game.load.image(Tileset.key, `res/${Tileset.path}`);
    if(this.hasLevel) {
      this.game.load.tilemap(Levels[`Level${this.indexLevel}`].key, `res/${Levels[`Level${this.indexLevel}`].path}` , null, Phaser.Tilemap.TILED_JSON);
    }
  }

  render() {
    //this.game.debug.text(this.game.time.fps, 2, 16, "#00ff00");
  }

  eraseBlockKeyboard() {
    this.mapManager.eraseBlock(this.marker.x / Size, this.marker.y / Size);
    this.hero.eraseBlocksAnimation(this.marker);
  }

  undoBlockKeyboard() {
    this.mapManager.undoBlock(this.marker.x / Size, this.marker.y / Size);
    this.hero.eraseBlocksAnimation(this.marker);
  }

  updateMarker() {
    this.marker.x = this.game.math.snapToFloor(this.game.input.activePointer.worldX, CursorSize, 0);
    this.marker.y = this.game.math.snapToFloor(this.game.input.activePointer.worldY, CursorSize, 0);

    if (this.game.input.mousePointer.isDown && this.marker.y > Size) {
      this.mapManager.eraseBlock(this.marker.x / Size, this.marker.y / Size);
      this.hero.eraseBlocksAnimation(this.marker);
    }
  }

  createTileSelector() {
    //Our painting marker
    this.marker = this.game.add.graphics();
    this.marker.lineStyle(2, 0xea4335, 1);
    this.marker.drawRect(0, 0, CursorSize, CursorSize);
    this.marker.x = 4 * CursorSize;
    this.marker.y = 4 * CursorSize;
  }

  moveUp() {
    this.marker.y -= CursorSize;
    if(this.marker.y < 0) {
      this.marker.y = 0;
    }
  }

  moveDown() {
    this.marker.y += CursorSize;
    if(this.marker.y > Height - CursorSize) {
      this.marker.y = Height - CursorSize;
    }
  }

  moveLeft() {
    this.marker.x -= CursorSize;
    if(this.marker.x < 0) {
      this.marker.x = 0;
    }
  }

  moveRight() {
    this.marker.x += CursorSize;
    if(this.marker.x > Width - CursorSize) {
      this.marker.x = Width - CursorSize;
    }
  }

}

export default MainView;
<commit_msg>fix bug<commit_after>import { WidthSpriteSheetHero, HeightSpriteSheetHero, Size, CursorSize, Width, Height, HudText, HudTextX, HudTextY } from '../Constants.js';
import { Tileset, Level1, Levels, HeroSprite } from '../ConstantsKey.js';
import Character from 'objects/Character';
import InformationString from 'objects/InformationString';

import MapManager from "objects/MapManager";
import Controls from "objects/Controls";

class MainView extends Phaser.State {

  constructor() {
    super();
  }

  init(indexLevel) {
    this.indexLevel = indexLevel || 1;
    this.hasLevel = Object.keys(Levels).length >= this.indexLevel;
    if(!this.game.controls) {
      let controls = new Controls();
      controls.PostMortemDefaultConfig();
      this.game.controls = controls;
    }
    //no more levels :|
  }

  create() {
    if(!this.hasLevel) {
      this.game.goToMenu();
    } else {

      this.game.physics.startSystem(Phaser.Physics.ARCADE);
      // Add the physics engine to all game objects
      this.game.world.enableBody = true;

      this.map = this.game.add.tilemap(Levels[`Level${this.indexLevel}`].key);
      this.map.addTilesetImage(Levels[`Level${this.indexLevel}`].key, Tileset.key);

      this.map.createLayer('thirdLayer');
      this.map.createLayer('secondLayer');
      this.map.createLayer('firstLayer');
      // This resizes the game world to match the layer dimensions
      this.collisionLayer = this.map.createLayer('colissionLayer');
      this.map.setCollisionByExclusion([], true, this.collisionLayer);

      this.collisionLayer.resizeWorld();

      this.hero = new Character(this.game, Levels[`Level${this.indexLevel}`].playerPosition.x , Levels[`Level${this.indexLevel}`].playerPosition.y, HeroSprite.key, 0);
      this.game.add.existing(this.hero);
      this.game.camera.follow(this.hero);

      this.marker = null;
      this.createTileSelector();
      this.game.input.addMoveCallback(this.updateMarker, this);

      this.mapManager = new MapManager(this.map, Levels[`Level${this.indexLevel}`].lastLayer);
      this.mapManager.setUpCollisionLayer(this.collisionLayer);

      this.text = new InformationString(this.game, Width/2, Levels[`Level${this.indexLevel}`].text );
      this.game.add.existing(this.text);
      this.text.blink();

      this.hud = this.game.add.text(400, 400, HudText, { font: "bold 22px Arial", fill: '#FFFFFF' });
      this.hud.x = this.game.camera.x + HudTextX;
      this.hud.y = this.game.camera.y + HudTextY;

      this.keyRemoveLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("undoLayer"));
      this.keyRemoveLayer.onDown.add(this.eraseBlockKeyboard, this);
      this.keyUndoLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("removeLayer"));
      this.keyUndoLayer.onDown.add(this.undoBlockKeyboard, this);

      this.keyUpLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("moveUpCursor"));
      this.keyUpLayer.onDown.add(this.moveUp, this);
      this.keyDownLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("moveDownCursor"));
      this.keyDownLayer.onDown.add(this.moveDown, this);
      this.keyLeftLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("moveLeftCursor"));
      this.keyLeftLayer.onDown.add(this.moveLeft, this);
      this.keyRightLayer = this.game.input.keyboard.addKey(this.game.controls.getKey("moveRightCursor"));
      this.keyRightLayer.onDown.add(this.moveRight, this);

      this.game.time.advancedTiming = true;
    }
  }

  update() {
    this.game.physics.arcade.collide(this.hero, this.collisionLayer, this.additionalCheck, this.hasPortal , this);
    if(this.hero.y > Height + this.hero.height) {
      this.game.reset();
    }

    this.updateGui();
  }

  updateGui() {
    this.hud.setText(HudText + this.mapManager.currentGems + " / " + this.mapManager.nbGems);
    this.hud.x = this.game.camera.x + HudTextX;
    this.hud.y = this.game.camera.y + HudTextY;

  }

  hasPortal(tile1, tile2) {
    if(tile2.properties && tile2.properties.portal == 1 && !this.mapManager.portalEnable()) {
      return false;
    }
    return true;
  }

  additionalCheck(tile1, tile2) {
    if(!tile2.properties) {
      return;
    }

    if(tile2.properties.layer_gem == 1) {
      if(tile2.properties.layer_destroy) {
        this.mapManager.removeLayer();
      } else if (tile2.properties.layer_rollback) {
        this.mapManager.undoLayer();
      }
      return;
    }

    if(tile2.properties.is_gem == 1) {
      this.map.removeTile(tile2.x, tile2.y, "colissionLayer").destroy();
      this.mapManager.killGem();
      return;
    }

    if(tile2.properties.portal == 1 && this.mapManager.portalEnable()) {
      //maybe make an animation
      this.game.nextLevel();
    }
  }

  preload() {
    this.game.load.spritesheet(HeroSprite.key, `res/${HeroSprite.path}`, WidthSpriteSheetHero, HeightSpriteSheetHero);
    this.game.load.image(Tileset.key, `res/${Tileset.path}`);
    if(this.hasLevel) {
      this.game.load.tilemap(Levels[`Level${this.indexLevel}`].key, `res/${Levels[`Level${this.indexLevel}`].path}` , null, Phaser.Tilemap.TILED_JSON);
    }
  }

  render() {
    //this.game.debug.text(this.game.time.fps, 2, 16, "#00ff00");
  }

  eraseBlockKeyboard() {
    this.mapManager.eraseBlock(this.marker.x / Size, this.marker.y / Size);
    this.hero.eraseBlocksAnimation(this.marker);
  }

  undoBlockKeyboard() {
    this.mapManager.undoBlock(this.marker.x / Size, this.marker.y / Size);
    this.hero.eraseBlocksAnimation(this.marker);
  }

  updateMarker() {
    this.marker.x = this.game.math.snapToFloor(this.game.input.activePointer.worldX, CursorSize, 0);
    this.marker.y = this.game.math.snapToFloor(this.game.input.activePointer.worldY, CursorSize, 0);

    if (this.game.input.mousePointer.isDown && this.marker.y > Size) {
      this.mapManager.eraseBlock(this.marker.x / Size, this.marker.y / Size);
      this.hero.eraseBlocksAnimation(this.marker);
    }
  }

  createTileSelector() {
    //Our painting marker
    this.marker = this.game.add.graphics();
    this.marker.lineStyle(2, 0xea4335, 1);
    this.marker.drawRect(0, 0, CursorSize, CursorSize);
    this.marker.x = 4 * CursorSize;
    this.marker.y = 4 * CursorSize;
  }

  moveUp() {
    this.marker.y -= CursorSize;
    if(this.marker.y < 0) {
      this.marker.y = 0;
    }
  }

  moveDown() {
    this.marker.y += CursorSize;
    if(this.marker.y > Height - CursorSize) {
      this.marker.y = Height - CursorSize;
    }
  }

  moveLeft() {
    this.marker.x -= CursorSize;
    if(this.marker.x < 0) {
      this.marker.x = 0;
    }
  }

  moveRight() {
    this.marker.x += CursorSize;
    if(this.marker.x > Width - CursorSize) {
      this.marker.x = Width - CursorSize;
    }
  }

}

export default MainView;
<|endoftext|>