<commit_before>const Reading = require('./../models/Reading');
const readCsv = require('./readCSV');
const Meter = require('./../models/Meter');
const moment = require('moment');
/**
 * Reads CSV file passed to input all the Metasys readings into database.
 * @param filePath the filePath to read
 */
async function readMetasysData(filePath, readingInterval, readingRepetition, cumulativeIndicator,conn) {
	//arrays to store readings and rows
	const readingArray = [];
	const rowArray = [];

	//getting filename
	const fileNameArray = filePath.split("/");
	const fileName = fileNameArray.pop();

	//list of readings
	const rows = await readCsv(filePath);

	//meterInformation
	const meter = await Meter.getByName(fileName.replace('.csv', ''));

	//Initialize timestamps and other variables
	let start_timestamp = moment(0);
	let end_timestamp = moment(0);
	let index = 0;
	let meterReading, meterReading1, meterReading2 = 0;

	for (const row of rows) {
		rowArray.push(row);
		// To read data where same reading is repeated. Like E-mon D-mon meters
		if (index != 0 && Math.abs((index - readingRepetition) % readingRepetition) == 0) {
			//set start_timestamp and end_timestamp
			start_timestamp = moment(rowArray[index][0], 'MM/DD/YY HH:mm');
			end_timestamp = moment(rowArray[index - readingRepetition][0], 'MM/DD/YY HH:mm');
			//meterReading for cumulative readings
			if (cumulativeIndicator == true) {
				//meterReading1
				meterReading1 = rowArray[index - readingRepetition][3];
				meterReading1 = meterReading1.replace(' kW', '');
				meterReading1 = Math.round(parseFloat(meterReading1));

				//meterReading2
				meterReading2 = rowArray[index][3];
				meterReading2 = meterReading2.replace(' kW', '');
				meterReading2 = Math.round(parseFloat(meterReading2));
				meterReading = meterReading1 - meterReading2;
			}
			//for data points
			else {
				//meterReading
				meterReading = rowArray[index - readingRepetition][3];
				meterReading = meterReading.replace(' kW', '');
				meterReading = Math.round(parseFloat(meterReading));
				console.log(meterReading);
			}
			//To handle cumulative readings that resets at midnight
			if(meterReading < 0){
				meterReading = meterReading1;
			}
			//push into reading Array
			const reading = new Reading(meter.id, meterReading, start_timestamp.toDate(), end_timestamp.toDate());
			readingArray.push(reading);
		}
		index = index + 1;
	}

	/*Deal with the last reading*/
	// Timestamp for last reading
	const lastRow = await rowArray.pop();
	end_timestamp = moment(lastRow[0], 'MM/DD/YY HH:mm');
	start_timestamp = moment(end_timestamp).subtract(readingInterval, 'minutes');
	//meterReadingForLastReading
	let meterReadingEnd = lastRow[3].replace(' kW', '');
	meterReadingEnd = Math.round(parseFloat(meterReadingEnd));
	//pushing last reading into array
	const reading = new Reading(meter.id,meterReadingEnd,start_timestamp.toDate(),end_timestamp.toDate());
	readingArray.push(reading);

	// //Insert into database
	try {
		console.log("About to insert");
		//inserting all the data from an array into database and catching error when it occurs.
		Reading.insertAll(readingArray,conn).then(() => console.log("Done"));
	} catch (err) {
		console.error(err);
	}
}
module.exports = readMetasysData;
<commit_msg>removed conn paramter  because it is not needed<commit_after>const Reading = require('./../models/Reading');
const readCsv = require('./readCSV');
const Meter = require('./../models/Meter');
const moment = require('moment');
/**
 * Reads CSV file passed to input all the Metasys readings into database.
 * @param filePath the filePath to read
 */
async function readMetasysData(filePath, readingInterval, readingRepetition, cumulativeIndicator) {
	//arrays to store readings and rows
	const readingArray = [];
	const rowArray = [];

	//getting filename
	const fileNameArray = filePath.split("/");
	const fileName = fileNameArray.pop();

	//list of readings
	const rows = await readCsv(filePath);

	//meterInformation
	const meter = await Meter.getByName(fileName.replace('.csv', ''));

	//Initialize timestamps and other variables
	let start_timestamp = moment(0);
	let end_timestamp = moment(0);
	let index = 0;
	let meterReading, meterReading1, meterReading2 = 0;

	for (const row of rows) {
		rowArray.push(row);
		// To read data where same reading is repeated. Like E-mon D-mon meters
		if (index != 0 && Math.abs((index - readingRepetition) % readingRepetition) == 0) {
			//set start_timestamp and end_timestamp
			start_timestamp = moment(rowArray[index][0], 'MM/DD/YY HH:mm');
			end_timestamp = moment(rowArray[index - readingRepetition][0], 'MM/DD/YY HH:mm');
			//meterReading for cumulative readings
			if (cumulativeIndicator == true) {
				//meterReading1
				meterReading1 = rowArray[index - readingRepetition][3];
				meterReading1 = meterReading1.replace(' kW', '');
				meterReading1 = Math.round(parseFloat(meterReading1));

				//meterReading2
				meterReading2 = rowArray[index][3];
				meterReading2 = meterReading2.replace(' kW', '');
				meterReading2 = Math.round(parseFloat(meterReading2));
				meterReading = meterReading1 - meterReading2;
			}
			//for data points
			else {
				//meterReading
				meterReading = rowArray[index - readingRepetition][3];
				meterReading = meterReading.replace(' kW', '');
				meterReading = Math.round(parseFloat(meterReading));
				console.log(meterReading);
			}
			//To handle cumulative readings that resets at midnight
			if(meterReading < 0){
				meterReading = meterReading1;
			}
			//push into reading Array
			const reading = new Reading(meter.id, meterReading, start_timestamp.toDate(), end_timestamp.toDate());
			readingArray.push(reading);
		}
		index = index + 1;
	}

	/*Deal with the last reading*/
	// Timestamp for last reading
	const lastRow = await rowArray.pop();
	end_timestamp = moment(lastRow[0], 'MM/DD/YY HH:mm');
	start_timestamp = moment(end_timestamp).subtract(readingInterval, 'minutes');
	//meterReadingForLastReading
	let meterReadingEnd = lastRow[3].replace(' kW', '');
	meterReadingEnd = Math.round(parseFloat(meterReadingEnd));
	//pushing last reading into array
	const reading = new Reading(meter.id,meterReadingEnd,start_timestamp.toDate(),end_timestamp.toDate());
	readingArray.push(reading);

	// //Insert into database
	try {
		console.log("About to insert");
		//inserting all the data from an array into database and catching error when it occurs.
		Reading.insertAll(readingArray).then(() => console.log("Done"));
	} catch (err) {
		console.error(err);
	}
}
module.exports = readMetasysData;
<|endoftext|>


<commit_before>'use strict';

module.exports = new Promise(function(resolve) {
  window.addEventListener('load', function() {
    var otScript = document.createElement('script');
    otScript.setAttribute('src', '//static.opentok.com/v2/js/opentok.min.js');
    otScript.setAttribute('async', '');
    document.head.appendChild(otScript);

    otScript.addEventListener('load', function() {
      var opentok = window.OT;
      delete window.OT;
      delete window.OTHelpers;
      //delete window.OTPlugin;

      resolve(opentok);
    })
  });
});
<commit_msg>Add missing semicolon<commit_after>'use strict';

module.exports = new Promise(function(resolve) {
  window.addEventListener('load', function() {
    var otScript = document.createElement('script');
    otScript.setAttribute('src', '//static.opentok.com/v2/js/opentok.min.js');
    otScript.setAttribute('async', '');
    document.head.appendChild(otScript);

    otScript.addEventListener('load', function() {
      var opentok = window.OT;
      delete window.OT;
      delete window.OTHelpers;
      //delete window.OTPlugin;

      resolve(opentok);
    });
  });
});
<|endoftext|>


<commit_before>angular.module('mol.controllers').controller('molDatasetsMapCtrl',
    ['$scope', 'leafletData', 'leafletBoundsHelpers', '$timeout', '$window', '$http', '$filter', 'molApi', '$q', '$state', 'leafletMapEvents',
    function($scope, leafletData, leafletBoundsHelpers, $timeout, $window, $http, $filter, molApi, $q, $state, leafletMapEvents) {

  $scope.$watch('model.choices', function() {
    $scope.map.legend = { position: 'bottomleft', labels: [], colors: [] };
    $scope.map.layers.overlays = {};
    $timeout($scope.datasetsQuery);
  }, true);

  $scope.map = {
    center: { lat: 0, lng: 0, zoom: 3 },
    extent: leafletBoundsHelpers.createBoundsFromArray([[90, 180], [-90, -180]]),
    controls: { fullscreen: { position: 'topright' }},
    events: { map: { enable: ['click'], logic: 'emit' } },
    defaults: { minZoom: 2 },
    bounds: {},
    legend: {},
    layers: {
      baselayers: {
        xyz: {
          name: 'OpenStreetMap (XYZ)',
          url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
          type: 'xyz'
        }
      }
    },
  };

  $scope.canceller = $q.defer();

  /*
  $scope.$on('leafletDirectiveMap.moveend', function(event) {
    leafletData.getMap().then(function(map) {
      var bbox = map.getBounds();
      molApi({
        service: 'inventory/bbox',
        processing: true,
        params: { coords: [bbox._northEast.lng, bbox._northEast.lat, bbox._southWest.lng, bbox._southWest.lat].join(',') }
      }).then(function(response) {
        $scope.model.filterByIds = response.data.dataset_id;
      });
    });
  });
  */

  $scope.datasetsQuery = function() {
    var payload = {};
    Object.keys($scope.model.choices).forEach(function (facet) {
      var choices = $scope.model.choices[facet];
      payload[facet] = Object.keys(choices).filter(function(choice) {
        return choices[choice]
      }).join(',').toLowerCase() || '';
    });

    if ($state.params.dataset) {
      payload = { dataset_id: $state.params.dataset };
    }

    $scope.canceller.resolve();
    $scope.canceller = $q.defer();
    molApi({
      service: 'inventory/maps',
      params : payload,
      canceller: $scope.canceller,
      processing: true
    }).then(function(response) {
      $scope.map.bounds = leafletBoundsHelpers.createBoundsFromArray([
        response.data.extent.coordinates[0][2].reverse(),
        response.data.extent.coordinates[0][0].reverse()
      ]);
      $scope.map.layers.overlays = {
        xyz: {
          name: 'Datasets',
          visible: true,
          url: response.data.tile_url,
          type: 'xyz',
          doRefresh: true
        }
      };
      $scope.map.legend = $scope.buildLegend(response.data.legend);
    });
  };

  $scope.buildLegend = function(legendData) {
    var legend = { position: 'bottomleft', labels: [], colors: [] };
    var used = {};
    legendData.colors.reduce(function(prev, curr, i) {
      var item = {
        low: i ? legendData.bins[i-1] + 1 : 1,
        high: i > legendData.bins.length - 1 ? 'and over' : legendData.bins[i],
        color: curr
      };
      if (item.low > item.high) { item.low = item.high; }
      if (!used[item.high]) {
        used[item.high] = true;
        prev.push(item);
      }
      return prev;
    }, []).forEach(function(item) {
      if (item.low == item.high) {
        legend.labels.push('' + item.low);
      } else {
        var h = item.high;
        legend.labels.push('' + item.low + (isNaN(h) ? ' ' + h : ' - ' + h));
      }
      legend.colors.push(item.color);
    });
    if ($state.params.dataset) {
      legend.labels = legend.labels.slice(0, 1);
      legend.colors = legend.colors.slice(0, 1);
    }
    return legend;
  };

}]);
<commit_msg>Change zoom on map loads #32<commit_after>angular.module('mol.controllers').controller('molDatasetsMapCtrl',
    ['$scope', 'leafletData', 'leafletBoundsHelpers', '$timeout', '$window', '$http', '$filter', 'molApi', '$q', '$state', 'leafletMapEvents',
    function($scope, leafletData, leafletBoundsHelpers, $timeout, $window, $http, $filter, molApi, $q, $state, leafletMapEvents) {

  $scope.$watch('model.choices', function() {
    $scope.map.legend = { position: 'bottomleft', labels: [], colors: [] };
    $scope.map.layers.overlays = {};
    $timeout($scope.datasetsQuery);
  }, true);

  $scope.map = {
    center: { lat: 0, lng: 0, zoom: 3 },
    extent: leafletBoundsHelpers.createBoundsFromArray([[90, 180], [-90, -180]]),
    controls: { fullscreen: { position: 'topright' }},
    events: { map: { enable: ['click'], logic: 'emit' } },
    defaults: { minZoom: 2 },
    bounds: {},
    legend: {},
    layers: {
      baselayers: {
        xyz: {
          name: 'OpenStreetMap (XYZ)',
          url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
          type: 'xyz'
        }
      }
    },
  };

  $scope.canceller = $q.defer();

  $scope.datasetsQuery = function() {
    var payload = {};
    Object.keys($scope.model.choices).forEach(function (facet) {
      var choices = $scope.model.choices[facet];
      payload[facet] = Object.keys(choices).filter(function(choice) {
        return choices[choice]
      }).join(',').toLowerCase() || '';
    });

    if ($state.params.dataset) {
      payload = { dataset_id: $state.params.dataset };
    }

    $scope.canceller.resolve();
    $scope.canceller = $q.defer();
    molApi({
      service: 'inventory/maps',
      params : payload,
      canceller: $scope.canceller,
      processing: true
    }).then(function(response) {
      $scope.map.bounds = leafletBoundsHelpers.createBoundsFromArray([
        response.data.extent.coordinates[0][2].reverse(),
        response.data.extent.coordinates[0][0].reverse()
      ]);
      var padding = 5;
      $scope.map.bounds.northEast.lat += padding;
      $scope.map.bounds.northEast.lng += padding;
      $scope.map.bounds.southWest.lat -= padding;
      $scope.map.bounds.southWest.lng -= padding;
      $scope.map.layers.overlays = {
        xyz: {
          name: 'Datasets',
          visible: true,
          url: response.data.tile_url,
          type: 'xyz',
          doRefresh: true
        }
      };
      $scope.map.legend = $scope.buildLegend(response.data.legend);
    });
  };

  $scope.buildLegend = function(legendData) {
    var legend = { position: 'bottomleft', labels: [], colors: [] };
    var used = {};
    legendData.colors.reduce(function(prev, curr, i) {
      var item = {
        low: i ? legendData.bins[i-1] + 1 : 1,
        high: i > legendData.bins.length - 1 ? 'and over' : legendData.bins[i],
        color: curr
      };
      if (item.low > item.high) { item.low = item.high; }
      if (!used[item.high]) {
        used[item.high] = true;
        prev.push(item);
      }
      return prev;
    }, []).forEach(function(item) {
      if (item.low == item.high) {
        legend.labels.push('' + item.low);
      } else {
        var h = item.high;
        legend.labels.push('' + item.low + (isNaN(h) ? ' ' + h : ' - ' + h));
      }
      legend.colors.push(item.color);
    });
    if ($state.params.dataset) {
      legend.labels = legend.labels.slice(0, 1);
      legend.colors = legend.colors.slice(0, 1);
    }
    return legend;
  };

}]);
<|endoftext|>


<commit_before>// Depends on ECMAScript 5 or appropriate polyfill for:
// Array.prototype.map, JSON.stringify

(function() {
  var MAX_LINES = 1000;
  var CONSOLE_CSS = "#SHIMCONSOLE { visibility: hidden; position: fixed; z-index: 9999; left: 0; right: 0; bottom: 0; height: 200px; border-top: solid 1px #808080; overflow: auto; word-wrap: break-word; padding: 5px; background-color: #eeeeee; color: #000000; font-family: monospace; font-size: 10pt; font-weight: normal; font-style: normal; }"
      + "#SHIMCONSOLE .SHIMCONSOLE_GROUP { margin-left: 20px; }"
      + "#SHIMCONSOLE .SHIMCONSOLE_ERROR { color: #ff0000; }"
      + "#SHIMCONSOLE .SHIMCONSOLE_WARN { color: #ff8000; }"
      + "#SHIMCONTROLS { visibility: hidden; position: fixed; z-index: 9999; left: 0; right: 0; bottom: 0px; height: 30px; }"
      + "#SHIMCONTROLS button { cursor: pointer; }";
  var FORMAT_REGEXP = /([^%]|%([\-+0]*)(\d+)?(\.\d+)?([%sdilfox]))/g;
  var OPEN_TEXT = "Open console";
  var CLOSE_TEXT = "Close console";

  function Console() {

    // Add stylesheet
    (function() {
      var style = document.createElement('style');
      (document.getElementsByTagName('HEAD')[0] || document.documentElement)
          .appendChild(style);
      if('styleSheet' in style) {
        style.styleSheet.cssText = CONSOLE_CSS;
      } else {
        style.appendChild(document.createTextNode(CONSOLE_CSS));
      }
    }());

    var controls;
    var toggle;
    var display;
    var counts = {};
    var times = {};
    var groups = [];

    var _this = this;

    controls = document.createElement('div');
    controls.id = 'SHIMCONTROLS';
    (document.body || document.documentElement).appendChild(controls);
    toggle = document.createElement('button');
    toggle.appendChild(document.createTextNode(OPEN_TEXT));
    toggle.onclick = function() {
      _this.toggle();
    };
    controls.appendChild(toggle);

    display = document.createElement('div');
    display.id = 'SHIMCONSOLE';
    (document.body || document.documentElement).appendChild(display);

    function format(o) {
      var span = document.createElement('span'), text, color, classOf;
      switch(typeof o) {
        case 'undefined':
          text = String(o);
          color = 'gray';
          break;
        case 'boolean':
          text = String(o);
          color = 'green';
          break;
        case 'number':
          text = String(o);
          color = 'blue';
          break;
        case 'string':
          text = o;
          break;
        default: // object and null
          if(!o) {
            text = String(o);
            color = 'gray';
          } else {
            classOf = Object.prototype.toString.call(o);
            if(classOf === '[object Array]' || classOf === '[object Object]') {
              try {
                text = JSON.stringify(o);
              } catch(e) {
                // Cyclic, use fallback
                text = classOf;
              }
            } else {
              text = String(o);
            }
          }
      }

      span.appendChild(document.createTextNode(text));
      if(color) {
        span.style.color = color;
      }
      return span;
    }

    function show(args, type, prefix) {
      if(!args.length) {
        return;
      }
      var line = document.createElement('div');
      line.className = 'SHIMCONSOLE_' + type;

      line.style.whiteSpace = 'pre';

      if(prefix) {
        line.appendChild(document.createTextNode(prefix));
      }

      function trunc(n) {
        return n < 0 ? Math.ceil(n) : Math.floor(n);
      }
      function repl(str, unit, flags, width, precision, specifier) {
        if(unit.charAt(0) != '%' || !args.length) {
          return unit;
        } else if(specifier === '%') {
          return '%';
        }
        var arg = args.shift();
        switch(specifier) {
          case 's':
            return String(arg);
          case 'd':
          case 'i':
          case 'l':
            return String(trunc(Number(arg)));
          case 'f':
            return String(Number(arg));
          default:
          case 'o':
            try {
              return JSON.stringify(arg);
            } catch(e) {
              return String(arg);
            }
        }
        return void 0;
      }

      if(typeof args[0] === 'string') {
        line.appendChild(document.createTextNode(args.shift().replace(
            FORMAT_REGEXP, repl)));
        line.appendChild(document.createTextNode(' '));
      }

      // pretty-print remaining arguments
      while(args.length) {
        line.appendChild(format(args.shift()));
        line.appendChild(document.createTextNode(' '));
      }
      var parent = groups.length ? groups[groups.length - 1] : display;
      parent.appendChild(line);

      while(display.children.length > MAX_LINES) {
        display.removeChild(display.firstChild);
      }
      display.scrollTop = display.scrollHeight;
      controls.style.visibility = 'visible';
    }

    function toArray(a) {
      var result = [], i;
      for(i = 0; i < a.length; i += 1) {
        result[i] = a[i];
      }
      return result;
    }

    this.open = function() {
      display.style.visibility = 'visible';
      controls.style.bottom = '211px';
      toggle.firstChild.remove();
      toggle.appendChild(document.createTextNode(CLOSE_TEXT));
    };

    this.close = function() {
      display.style.visibility = 'hidden';
      controls.style.bottom = '0';
      toggle.firstChild.remove();
      toggle.appendChild(document.createTextNode(OPEN_TEXT));
    };

    this.toggle = function() {
      if(display.style.visibility === 'visible') {
        this.close();
      } else {
        this.open();
      }
    }

    this.log = function log(messageObject) {
      show(toArray(arguments), 'LOG');
    };
    this.debug = function debug(messageObject) {
      show(toArray(arguments), 'DEBUG');
    };
    this.info = function info(messageObject) {
      show(toArray(arguments), 'INFO');
    };
    this.warn = function warn(messageObject) {
      show(toArray(arguments), 'WARN', 'Warning: ');
    };
    this.error = function error(messageObject) {
      show(toArray(arguments), 'ERROR', 'Error: ');
    };

    this.assert = function assert(a, messageObject) {
      if(!a) {
        var args = toArray(arguments);
        args.shift();
        show(args, 'ERROR', 'Assertion failed: ');
      }
    };

    this.count = function count(name) {
      name = (name || '');
      if(!(('$' + name) in counts)) {
        counts['$' + name] = 0;
      }
      counts['$' + name] += 1;
      show([name + ": " + counts['$' + name]], 'INFO');
    };

    this.time = function time(name) {
      name = (name || '');
      times['$' + name] = Number(new Date);
    };
    this.timeEnd = function timeEnd(name) {
      name = (name || '');
      if(('$' + name) in times) {
        show([name + ": " + (Number(new Date) - times['$' + name]) + "ms"],
            'INFO');
        delete times['$' + name];
      }
    };

    this.group = function group(name) {
      name = (name || '');
      show(['>' + name], 'INFO');
      var div = document.createElement('div');
      div.className = 'SHIMCONSOLE_GROUP';
      var parent = groups.length ? groups[groups.length - 1] : display;
      parent.appendChild(div);
      groups.push(div);
    };
    this.groupEnd = function groupEnd() {
      groups.pop();
    };

    this.dir = function dir(name) {
      show([name], 'INFO');
    };
    this.dirxml = this.dir;

    this.trace = function trace() {
      try {
        this.wont.work = 0;
      } catch(e) {
        if(e.stack) {
          show([e.stack.replace(/^[^\n]*\n/, 'Stack trace:\n')], 'INFO');
        }
      }
    };

    this.clear = function clear() {
      while(display.children.length) {
        display.removeChild(display.firstChild);
      }
    };
  }

  window.console = window.console || new Console();
}());
<commit_msg>Older IE versions don't have JS remove() method, using innerHTML now.<commit_after>// Depends on ECMAScript 5 or appropriate polyfill for:
// Array.prototype.map, JSON.stringify

(function() {
  var MAX_LINES = 1000;
  var CONSOLE_CSS = "#SHIMCONSOLE { visibility: hidden; position: fixed; z-index: 9999; left: 0; right: 0; bottom: 0; height: 200px; border-top: solid 1px #808080; overflow: auto; word-wrap: break-word; padding: 5px; background-color: #eeeeee; color: #000000; font-family: monospace; font-size: 10pt; font-weight: normal; font-style: normal; }"
      + "#SHIMCONSOLE .SHIMCONSOLE_GROUP { margin-left: 20px; }"
      + "#SHIMCONSOLE .SHIMCONSOLE_ERROR { color: #ff0000; }"
      + "#SHIMCONSOLE .SHIMCONSOLE_WARN { color: #ff8000; }"
      + "#SHIMCONTROLS { visibility: hidden; position: fixed; z-index: 9999; left: 0; right: 0; bottom: 0px; height: 30px; }"
      + "#SHIMCONTROLS button { cursor: pointer; }";
  var FORMAT_REGEXP = /([^%]|%([\-+0]*)(\d+)?(\.\d+)?([%sdilfox]))/g;
  var OPEN_TEXT = "Open console";
  var CLOSE_TEXT = "Close console";

  function Console() {

    // Add stylesheet
    (function() {
      var style = document.createElement('style');
      (document.getElementsByTagName('HEAD')[0] || document.documentElement)
          .appendChild(style);
      if('styleSheet' in style) {
        style.styleSheet.cssText = CONSOLE_CSS;
      } else {
        style.appendChild(document.createTextNode(CONSOLE_CSS));
      }
    }());

    var controls;
    var toggle;
    var display;
    var counts = {};
    var times = {};
    var groups = [];

    var _this = this;

    controls = document.createElement('div');
    controls.id = 'SHIMCONTROLS';
    (document.body || document.documentElement).appendChild(controls);
    toggle = document.createElement('button');
    toggle.appendChild(document.createTextNode(OPEN_TEXT));
    toggle.onclick = function() {
      _this.toggle();
    };
    controls.appendChild(toggle);

    display = document.createElement('div');
    display.id = 'SHIMCONSOLE';
    (document.body || document.documentElement).appendChild(display);

    function format(o) {
      var span = document.createElement('span'), text, color, classOf;
      switch(typeof o) {
        case 'undefined':
          text = String(o);
          color = 'gray';
          break;
        case 'boolean':
          text = String(o);
          color = 'green';
          break;
        case 'number':
          text = String(o);
          color = 'blue';
          break;
        case 'string':
          text = o;
          break;
        default: // object and null
          if(!o) {
            text = String(o);
            color = 'gray';
          } else {
            classOf = Object.prototype.toString.call(o);
            if(classOf === '[object Array]' || classOf === '[object Object]') {
              try {
                text = JSON.stringify(o);
              } catch(e) {
                // Cyclic, use fallback
                text = classOf;
              }
            } else {
              text = String(o);
            }
          }
      }

      span.appendChild(document.createTextNode(text));
      if(color) {
        span.style.color = color;
      }
      return span;
    }

    function show(args, type, prefix) {
      if(!args.length) {
        return;
      }
      var line = document.createElement('div');
      line.className = 'SHIMCONSOLE_' + type;

      line.style.whiteSpace = 'pre';

      if(prefix) {
        line.appendChild(document.createTextNode(prefix));
      }

      function trunc(n) {
        return n < 0 ? Math.ceil(n) : Math.floor(n);
      }
      function repl(str, unit, flags, width, precision, specifier) {
        if(unit.charAt(0) != '%' || !args.length) {
          return unit;
        } else if(specifier === '%') {
          return '%';
        }
        var arg = args.shift();
        switch(specifier) {
          case 's':
            return String(arg);
          case 'd':
          case 'i':
          case 'l':
            return String(trunc(Number(arg)));
          case 'f':
            return String(Number(arg));
          default:
          case 'o':
            try {
              return JSON.stringify(arg);
            } catch(e) {
              return String(arg);
            }
        }
        return void 0;
      }

      if(typeof args[0] === 'string') {
        line.appendChild(document.createTextNode(args.shift().replace(
            FORMAT_REGEXP, repl)));
        line.appendChild(document.createTextNode(' '));
      }

      // pretty-print remaining arguments
      while(args.length) {
        line.appendChild(format(args.shift()));
        line.appendChild(document.createTextNode(' '));
      }
      var parent = groups.length ? groups[groups.length - 1] : display;
      parent.appendChild(line);

      while(display.children.length > MAX_LINES) {
        display.removeChild(display.firstChild);
      }
      display.scrollTop = display.scrollHeight;
      controls.style.visibility = 'visible';
    }

    function toArray(a) {
      var result = [], i;
      for(i = 0; i < a.length; i += 1) {
        result[i] = a[i];
      }
      return result;
    }

    this.open = function() {
      display.style.visibility = 'visible';
      controls.style.bottom = '211px';
      toggle.firstChild.innerHTML = CLOSE_TEXT;
    };

    this.close = function() {
      display.style.visibility = 'hidden';
      controls.style.bottom = '0';
      toggle.firstChild.innerHTML = OPEN_TEXT;
    };

    this.toggle = function() {
      if(display.style.visibility === 'visible') {
        this.close();
      } else {
        this.open();
      }
    }

    this.log = function log(messageObject) {
      show(toArray(arguments), 'LOG');
    };
    this.debug = function debug(messageObject) {
      show(toArray(arguments), 'DEBUG');
    };
    this.info = function info(messageObject) {
      show(toArray(arguments), 'INFO');
    };
    this.warn = function warn(messageObject) {
      show(toArray(arguments), 'WARN', 'Warning: ');
    };
    this.error = function error(messageObject) {
      show(toArray(arguments), 'ERROR', 'Error: ');
    };

    this.assert = function assert(a, messageObject) {
      if(!a) {
        var args = toArray(arguments);
        args.shift();
        show(args, 'ERROR', 'Assertion failed: ');
      }
    };

    this.count = function count(name) {
      name = (name || '');
      if(!(('$' + name) in counts)) {
        counts['$' + name] = 0;
      }
      counts['$' + name] += 1;
      show([name + ": " + counts['$' + name]], 'INFO');
    };

    this.time = function time(name) {
      name = (name || '');
      times['$' + name] = Number(new Date);
    };
    this.timeEnd = function timeEnd(name) {
      name = (name || '');
      if(('$' + name) in times) {
        show([name + ": " + (Number(new Date) - times['$' + name]) + "ms"],
            'INFO');
        delete times['$' + name];
      }
    };

    this.group = function group(name) {
      name = (name || '');
      show(['>' + name], 'INFO');
      var div = document.createElement('div');
      div.className = 'SHIMCONSOLE_GROUP';
      var parent = groups.length ? groups[groups.length - 1] : display;
      parent.appendChild(div);
      groups.push(div);
    };
    this.groupEnd = function groupEnd() {
      groups.pop();
    };

    this.dir = function dir(name) {
      show([name], 'INFO');
    };
    this.dirxml = this.dir;

    this.trace = function trace() {
      try {
        this.wont.work = 0;
      } catch(e) {
        if(e.stack) {
          show([e.stack.replace(/^[^\n]*\n/, 'Stack trace:\n')], 'INFO');
        }
      }
    };

    this.clear = function clear() {
      while(display.children.length) {
        display.removeChild(display.firstChild);
      }
    };
  }

  window.console = window.console || new Console();
}());
<|endoftext|>


<commit_before>!function (nbrut, window, $, undefined) {
    var templating = function () {
        var templates = {},
            stringKeys = {},
            regexKeys = [],
            active = [],
			activity = {
				history: []
			},
			defaultTemplate = 'home',
            defaults = {
                container: '#content',
                mustache: false,
                initialized: false,
                initialize: $.noop,
                prepare: function(next){
					next();
				},
                afterActivate: $.noop,
                selfCleanup: true
            },
            titleSettings = {
                tag: $('title'),
                format: '{0} - ' + nbrut.site.title,
                default: {
                    text: nbrut.site.title,
                    literal: true
                }
            },
            loading = '',
            plugins = [];

        function register(settings) {
            var template = {};

            $.extend(template, defaults, settings);

            if(template.key in templates){
                throw new Error('template key not unique.');
            }
            read(template);

            templates[template.key] = template;

			setup(template);
        }

		function setup(template){
            $.each(template.aliases || [], function(){
                var alias = this;

				setupAlias(template, alias);
				bindTrigger(template, alias);
            });
		}

		function setupAlias(template, alias){
			alias.route = fixRouteObject(alias.route);

			if(!alias.route.regex){
				stringKeys[alias.route.get()] = template.key;
			}else{
				regexKeys.push({
					key: template.key,
					alias: alias,
					regex: alias.route.regex
				});
			}
		}

		function bindTrigger(template, alias){
			if(typeof alias.trigger === 'string'){
				trigger = $(alias.trigger);
				trigger.on('click', function(e){
					if (e.which === 1){ // left-click
						activate(template.key);
						return false;
					}
				});
			}
		}

		function back(){
			var h = activity.history,
				to = h[h.length-1];

			if(!to){
				activate(defaultTemplate);
			}else{
				activate(to.key, to.settings);
			}
		}

		function bindBack(template){
			if(typeof template.back === 'string'){
				var backTrigger = $(template.back);
				backTrigger.on('click', back);
			}
		}

        function configure(settings) {
            if(!(settings.key in templates)){
                throw new Error('template not registered.');
            }
            var configured = {},
                template = templates[settings.key];

            $.extend(configured, template, settings);
            templates[settings.key] = configured;
        }

        function read(template) {
            var s = $(template.source);
            if (s.length !== 1){
                throw new Error('template source not unique.');
            }
            var css = s.data('class'),
				html = s.remove().html();

            template.dom = {
                html: html,
                css: css
            };

            if (template.mustache){
				var m = {
					regex: /<!--[ ]*({{[^}]+}})[ ]*-->/g,
					replace: '$1'
				};
				var sanitized = html.replace(m.regex, m.replace);
                template.dom.view = Mustache.compile(sanitized);
            }
        }

        function fixRouteObject(source){
            if(typeof source === 'string'){
                return {
                    get: function(){
                        return source;
                    },
                    map: function(){
                        return null;
                    }
                };
            }
            return source;
        }

        function getHash(){
            return activity.history.length + (activity.current === undefined ? 0 : 1);
        }

        function equalSettings(x){
            var c = activity.current.settings,
                sameKey = c.key === x.key; // same route alias
            if(!sameKey){
                return false;
            }
            if(c.data === null && x.data === null){ // both null
                return true;
            }
            if(c.data === null || x.data === null){ // one null
                return false;
            }
            return equalRouteData(c.data, x.data);
        }

        function equalRouteData(c, x){
            for(var key in c){
                if(c[key] !== x[key]){
                    return false;
                }
            }
            return true;
        }

        function activate(key, settings, soft) { // soft: don't push history state.
            var template = templates[key];
            if (template === undefined) {
                template = templates['404']; // fall back to 404.
            }

            if (settings === undefined){
                settings = {};
            }

            var container = $(template.container);
            settings.flash = container.data('flash');
            container.removeAttr('data-flash');

            if(template.container in active) {
                if(active[template.container] === template) { // already active template
                    if (activity.current !== undefined){ // template engine initialized
                        if(equalSettings(settings)){ // compare template settings
                            if(!template.selfCleanup){
                                return;
                            }
                            if (soft !== 'replace'){
                                soft = true; // don't push history state.
                            }
                        }
                    }
                }
                deactivateContainer(template); // clean-up.
            }

            if(!template.initialized){
                template.initialized = true;
                template.initialize();
            }

            settings.identifier = getHash();

			function render(viewModel, err){
                if(settings.identifier !== getHash()){ // prevent mis-rendering when the user navigated away.
                    return;
                }
                if(err === true){
                    activate();
                    return;
                }
				activateTemplate(template, settings, viewModel || {}, soft); // set-up.
			}

			template.prepare(render, settings.data || {}, settings.identifier);
        }

        function deactivateContainer(template) {
            if(template.container in active){
                raise('deactivate', template);
                $(template.container).removeClass().off().html(loading);
                active.splice(active.indexOf(template.container), 1);
            }
        }

        function activateTemplate(template, settings, viewModel, soft){
            var c = $(template.container);
            if (c.length !== 1){
                throw new Error('template container not unique.');
            }

            active[template.container] = template;

            if (template.container === defaults.container){
                var alias = getTemplateAlias(template, settings), title, url;
                if (alias !== undefined){
                    title = setTitle(alias.title, viewModel, settings.data);
                    url = alias.route.get(settings.data);
                }else{
                    title = setTitle(template.title, viewModel, settings.data);
                    url = document.location.pathname;
                }

                if(soft === 'replace'){
                    history.replaceState({
                        key: template.key,
                        settings: settings
                    }, title, url);
                }
                else if(soft !== true){
                    history.pushState({
                        key: template.key,
                        settings: settings
                    }, title, url);
                }

				if (activity.current !== undefined){
					activity.history.push(activity.current);
				}
				activity.current = {
					key: template.key,
					settings: settings
				};
            }

            viewModel.flash = settings.flash  || {};
            var view = partial(template.key, viewModel);
            view.fill(c, settings.data || {}, settings.identifier);
        }

        function partial(key, viewModel, data){
            var template = templates[key];
            if (template === undefined){
                template = templates['404']; // fall back to 404.
            }

            var html;

            if(template.mustache){
                html = template.dom.view(viewModel);
            } else {
                html = template.dom.html;
            }

            function fill(container, data, identifier){
                container.addClass(template.dom.css).html(html);
                fixLocalRoutes(container);
                bindBack(template);
                template.afterActivate(viewModel, data || {}, identifier);
            }

            function move(fn){
                return function(container,data){ /* NOTE: the data-class will be lost, same for event bindings. */
                    var temp = $('<div/>');
                    fill(temp, data);
                    var elements = temp.children();
                    elements[fn](container);
                    return elements;
                };
            }

            return {
                html: html,
                css: template.dom.css,
                fill: fill,
                appendTo: move('appendTo'),
                insertAfter: move('insertAfter')
            };
        }

        function getTemplateAlias(template, settings){
            var key,
                alias;

            if(settings !== undefined){
                key = settings.key;
            }

            $.each(template.aliases || [], function(){
                if(this.key === key){
                    alias = this;
                    return false;
                }
            });

            return alias;
        }

        function setTitle(opts, viewModel, data){
            if (opts === undefined){
                opts = titleSettings.default;
            }else if(typeof opts === 'string'){
                opts = { text: opts };
            }else if($.isFunction(opts)){
                opts = { dynamic: opts };
            }

            var text = opts.text || opts.dynamic(viewModel, data),
                title = opts.literal === true ? text : titleSettings.format.format(text);

            titleSettings.tag.text(title);
            viewModel.title = text;
            return title;
        }

        function getRoute(url){
            if(url === undefined){
                return {};
            }

            var result = {
                key: stringKeys[url]
            };

            if(result.key !== undefined){
                return result;
            }

            $.each(regexKeys, function() {
                var self = this,
                    captures = url.match(self.regex);
                if (captures !== null){
                    result = {
                        key: self.key,
                        settings: {
                            key: self.alias.key,
                            data: self.alias.route.map(captures)
                        }
                    };
                    return false;
                }
            });
            return result;
        }

        function fixLocalRoutes(container){
            container.find('a').each(function(){
               var self = $(this),
                   url = self.attr('href'),
                   route = getRoute(url);

                if(route.key !== undefined){
                    self.on('click', function(e){
                        if (e.which === 1){ // left-click
                            activate(route.key, route.settings);
                            return false;
                        }
                    });
                }
            });
        }

        function activateRoute(route){
            activate(route.key, route.settings, 'replace');
        }

		function popState(e){
            var initial = e.originalEvent === undefined || e.originalEvent.state === null;
			if(!initial){
                activateRoute({
                    key: e.originalEvent.state.key,
				    settings: e.originalEvent.state.settings
                });
			}
		}

        function init(){
            loading = $(defaults.container).html();

            $(window).on('popstate', popState);

            $(function(){
                var route = getRoute(document.location.pathname);
                activateRoute(route);
            });
        }

        function raise(eventName){
            var args = $.makeArray(arguments).splice(1);
            $.each(plugins[eventName] || [],function(){
                this.apply(null, args);
            });
        }

        function hook(eventName, plugin){
            if (plugins[eventName] === undefined){
                plugins[eventName] = [];
            }
            plugins[eventName].push(plugin);
        }

        return {
            defaults: defaults,
            init: init,
            register: register,
            configure: configure,
            activate: activate,
            deactivate: deactivateContainer,
            partial: partial,
            hook: hook,
            get active() { return getHash() - 1; } /* offset by one because 0 means nothing is active yet */
        };
    }();

    nbrut.tt = templating;
}(nbrut, window, jQuery);<commit_msg>fixed flash temporality<commit_after>!function (nbrut, window, $, undefined) {
    var templating = function () {
        var templates = {},
            stringKeys = {},
            regexKeys = [],
            active = [],
			activity = {
				history: []
			},
			defaultTemplate = 'home',
            defaults = {
                container: '#content',
                mustache: false,
                initialized: false,
                initialize: $.noop,
                prepare: function(next){
					next();
				},
                afterActivate: $.noop,
                selfCleanup: true
            },
            titleSettings = {
                tag: $('title'),
                format: '{0} - ' + nbrut.site.title,
                default: {
                    text: nbrut.site.title,
                    literal: true
                }
            },
            loading = '',
            plugins = [];

        function register(settings) {
            var template = {};

            $.extend(template, defaults, settings);

            if(template.key in templates){
                throw new Error('template key not unique.');
            }
            read(template);

            templates[template.key] = template;

			setup(template);
        }

		function setup(template){
            $.each(template.aliases || [], function(){
                var alias = this;

				setupAlias(template, alias);
				bindTrigger(template, alias);
            });
		}

		function setupAlias(template, alias){
			alias.route = fixRouteObject(alias.route);

			if(!alias.route.regex){
				stringKeys[alias.route.get()] = template.key;
			}else{
				regexKeys.push({
					key: template.key,
					alias: alias,
					regex: alias.route.regex
				});
			}
		}

		function bindTrigger(template, alias){
			if(typeof alias.trigger === 'string'){
				trigger = $(alias.trigger);
				trigger.on('click', function(e){
					if (e.which === 1){ // left-click
						activate(template.key);
						return false;
					}
				});
			}
		}

		function back(){
			var h = activity.history,
				to = h[h.length-1];

			if(!to){
				activate(defaultTemplate);
			}else{
				activate(to.key, to.settings);
			}
		}

		function bindBack(template){
			if(typeof template.back === 'string'){
				var backTrigger = $(template.back);
				backTrigger.on('click', back);
			}
		}

        function configure(settings) {
            if(!(settings.key in templates)){
                throw new Error('template not registered.');
            }
            var configured = {},
                template = templates[settings.key];

            $.extend(configured, template, settings);
            templates[settings.key] = configured;
        }

        function read(template) {
            var s = $(template.source);
            if (s.length !== 1){
                throw new Error('template source not unique.');
            }
            var css = s.data('class'),
				html = s.remove().html();

            template.dom = {
                html: html,
                css: css
            };

            if (template.mustache){
				var m = {
					regex: /<!--[ ]*({{[^}]+}})[ ]*-->/g,
					replace: '$1'
				};
				var sanitized = html.replace(m.regex, m.replace);
                template.dom.view = Mustache.compile(sanitized);
            }
        }

        function fixRouteObject(source){
            if(typeof source === 'string'){
                return {
                    get: function(){
                        return source;
                    },
                    map: function(){
                        return null;
                    }
                };
            }
            return source;
        }

        function getHash(){
            return activity.history.length + (activity.current === undefined ? 0 : 1);
        }

        function equalSettings(x){
            var c = activity.current.settings,
                sameKey = c.key === x.key; // same route alias
            if(!sameKey){
                return false;
            }
            if(c.data === null && x.data === null){ // both null
                return true;
            }
            if(c.data === null || x.data === null){ // one null
                return false;
            }
            return equalRouteData(c.data, x.data);
        }

        function equalRouteData(c, x){
            for(var key in c){
                if(c[key] !== x[key]){
                    return false;
                }
            }
            return true;
        }

        function activate(key, settings, soft) { // soft: don't push history state.
            var template = templates[key];
            if (template === undefined) {
                template = templates['404']; // fall back to 404.
            }

            if (settings === undefined){
                settings = {};
            }

            var container = $(template.container);
            settings.flash = container.data('flash');
            container.removeAttr('data-flash').removeData('flash');

            if(template.container in active) {
                if(active[template.container] === template) { // already active template
                    if (activity.current !== undefined){ // template engine initialized
                        if(equalSettings(settings)){ // compare template settings
                            if(!template.selfCleanup){
                                return;
                            }
                            if (soft !== 'replace'){
                                soft = true; // don't push history state.
                            }
                        }
                    }
                }
                deactivateContainer(template); // clean-up.
            }

            if(!template.initialized){
                template.initialized = true;
                template.initialize();
            }

            settings.identifier = getHash();

			function render(viewModel, err){
                if(settings.identifier !== getHash()){ // prevent mis-rendering when the user navigated away.
                    return;
                }
                if(err === true){
                    activate();
                    return;
                }
				activateTemplate(template, settings, viewModel || {}, soft); // set-up.
			}

			template.prepare(render, settings.data || {}, settings.identifier);
        }

        function deactivateContainer(template) {
            if(template.container in active){
                raise('deactivate', template);
                $(template.container).removeClass().off().html(loading);
                active.splice(active.indexOf(template.container), 1);
            }
        }

        function activateTemplate(template, settings, viewModel, soft){
            var c = $(template.container);
            if (c.length !== 1){
                throw new Error('template container not unique.');
            }

            active[template.container] = template;

            if (template.container === defaults.container){
                var alias = getTemplateAlias(template, settings), title, url;
                if (alias !== undefined){
                    title = setTitle(alias.title, viewModel, settings.data);
                    url = alias.route.get(settings.data);
                }else{
                    title = setTitle(template.title, viewModel, settings.data);
                    url = document.location.pathname;
                }

                if(soft === 'replace'){
                    history.replaceState({
                        key: template.key,
                        settings: settings
                    }, title, url);
                }
                else if(soft !== true){
                    history.pushState({
                        key: template.key,
                        settings: settings
                    }, title, url);
                }

				if (activity.current !== undefined){
					activity.history.push(activity.current);
				}
				activity.current = {
					key: template.key,
					settings: settings
				};
            }

            viewModel.flash = settings.flash  || {};
            var view = partial(template.key, viewModel);
            view.fill(c, settings.data || {}, settings.identifier);
        }

        function partial(key, viewModel, data){
            var template = templates[key];
            if (template === undefined){
                template = templates['404']; // fall back to 404.
            }

            var html;

            if(template.mustache){
                html = template.dom.view(viewModel);
            } else {
                html = template.dom.html;
            }

            function fill(container, data, identifier){
                container.addClass(template.dom.css).html(html);
                fixLocalRoutes(container);
                bindBack(template);
                template.afterActivate(viewModel, data || {}, identifier);
            }

            function move(fn){
                return function(container,data){ /* NOTE: the data-class will be lost, same for event bindings. */
                    var temp = $('<div/>');
                    fill(temp, data);
                    var elements = temp.children();
                    elements[fn](container);
                    return elements;
                };
            }

            return {
                html: html,
                css: template.dom.css,
                fill: fill,
                appendTo: move('appendTo'),
                insertAfter: move('insertAfter')
            };
        }

        function getTemplateAlias(template, settings){
            var key,
                alias;

            if(settings !== undefined){
                key = settings.key;
            }

            $.each(template.aliases || [], function(){
                if(this.key === key){
                    alias = this;
                    return false;
                }
            });

            return alias;
        }

        function setTitle(opts, viewModel, data){
            if (opts === undefined){
                opts = titleSettings.default;
            }else if(typeof opts === 'string'){
                opts = { text: opts };
            }else if($.isFunction(opts)){
                opts = { dynamic: opts };
            }

            var text = opts.text || opts.dynamic(viewModel, data),
                title = opts.literal === true ? text : titleSettings.format.format(text);

            titleSettings.tag.text(title);
            viewModel.title = text;
            return title;
        }

        function getRoute(url){
            if(url === undefined){
                return {};
            }

            var result = {
                key: stringKeys[url]
            };

            if(result.key !== undefined){
                return result;
            }

            $.each(regexKeys, function() {
                var self = this,
                    captures = url.match(self.regex);
                if (captures !== null){
                    result = {
                        key: self.key,
                        settings: {
                            key: self.alias.key,
                            data: self.alias.route.map(captures)
                        }
                    };
                    return false;
                }
            });
            return result;
        }

        function fixLocalRoutes(container){
            container.find('a').each(function(){
               var self = $(this),
                   url = self.attr('href'),
                   route = getRoute(url);

                if(route.key !== undefined){
                    self.on('click', function(e){
                        if (e.which === 1){ // left-click
                            activate(route.key, route.settings);
                            return false;
                        }
                    });
                }
            });
        }

        function activateRoute(route){
            activate(route.key, route.settings, 'replace');
        }

		function popState(e){
            var initial = e.originalEvent === undefined || e.originalEvent.state === null;
			if(!initial){
                activateRoute({
                    key: e.originalEvent.state.key,
				    settings: e.originalEvent.state.settings
                });
			}
		}

        function init(){
            loading = $(defaults.container).html();

            $(window).on('popstate', popState);

            $(function(){
                var route = getRoute(document.location.pathname);
                activateRoute(route);
            });
        }

        function raise(eventName){
            var args = $.makeArray(arguments).splice(1);
            $.each(plugins[eventName] || [],function(){
                this.apply(null, args);
            });
        }

        function hook(eventName, plugin){
            if (plugins[eventName] === undefined){
                plugins[eventName] = [];
            }
            plugins[eventName].push(plugin);
        }

        return {
            defaults: defaults,
            init: init,
            register: register,
            configure: configure,
            activate: activate,
            deactivate: deactivateContainer,
            partial: partial,
            hook: hook,
            get active() { return getHash() - 1; } /* offset by one because 0 means nothing is active yet */
        };
    }();

    nbrut.tt = templating;
}(nbrut, window, jQuery);<|endoftext|>


<commit_before>/**
 * Provides generic Board module for writing board games
 *
 * @module Board
 */

var module = module || {};

module.Board = (function() {
    'use strict';

    // private variables for BitBoard class
    var width;
    var height;
    var bitboard;

    var numPlayers;
    var players;

    /**
     * constructor function
     *
     */
    function BitBoard (np, w, h) {
        width      = w;
        height     = h;
        bitboard   = new Uint8Array(new ArrayBuffer(width * height / 8));

        numPlayers = np;
        players    = [];
    }

    // class methods for BitBoard class
    /**
     *
     *
     *
     */
    // BitBoard.prototype.setPosition = function () {};
    // BitBoard.prototype.getPosition = function () {};
    // BitBoard.prototype.getBoard    = function () {};

    // return a module!
    return {
    };
})();
<commit_msg>created primary implementation for Board.js<commit_after>/**
 * Provides generic Board module for writing board games.
 * An example of an 8x8 Board is depicted as follows:
 *
 *             01234567  (X)
 *            0........
 *            1........
 *            2........
 *            3........
 *            4........
 *            5........
 *            6........
 *            7........
 *
 *           (Y)
 *
 * @module Board
 */

var module = module || {};

module.Board = (function() {
    'use strict';

    // private variables for BitBoard class
    var width;
    var height;
    var bitboard;

    var numPlayers;
    var players;

    /**
     * Represents a BitBoard: https://chessprogramming.wikispaces.com/Bitboards
     *
     * @constructor
     * @param {number} np - number of players for this bitboard
     * @param {number} w - width of this bitboard
     * @param {number} h - height this bitboard
     */
    function BitBoard (np, w, h) {
        width      = w;
        height     = h;
        bitboard   = new Uint8Array(new ArrayBuffer(width * height / 8));

        numPlayers = np;
        players    = [];
    }

    /** @function setPosition
     *
     * @param {number} player - the player for which the postion to be set
     * @param {number} x - the x coordinate of the postion
     * @param {number} y - the y coordinate of the postion
     */
    BitBoard.prototype.setPosition = function (player, x, y) {
        bitboard[y]      = 128 >>> x;
        players [player] = y*height + x;
    };

    /** @function setPosition
     *
     * @param {number} player - the player for which the postion to be retrieved
     * @returns {Object} - the x and y coordinate in Object literal format
     */
    BitBoard.prototype.getPosition = function (player) {
        var pos = players[player];

        return {
            x: pos % 8,
            y: pos / 8
        };
    };

    // BitBoard.prototype.getBoard    = function () {};

    // return a module/namespace!
    return {
        BitBoard: BitBoard
        // init: ;
    };
})();
<|endoftext|>


<commit_before>// Board
var Board={
    // init func
    createNew: function(g,w,h,pw,terrain,res,building){
        var board={};

        // Class members
        board.game=g;
        board.width=w;
        board.height=h;
        board.map=g.add.group();

        // returns the tile sprite at [i]
        board.at=function(i){return Board.at(board,i);};
        // returns the adjacent index at clock direction [cd] of tile [i]
        board.adjacent=function(i,cd,warning){return Board.adjacent(board,i,cd,warning);};
        // returns all adjacent indice within [N] steps of tile [i]
        board.allAdjacent=function(i,N){return Board.allAdjacent(board,i,N);};
        // returns the (x,y) of i
        board.xyOf=function(i){return Board.xyOf(board,i);};
        // returns the step distance between i and j
        board.distanceOf=function(i,j){return Board.distanceOf(board,i,j);};

        // init
        var N=w*h;
        var ph=pw*(1.732/2.0);
        for(var i=0;i<N;i++){
            var ix=i%w;
            var iy=Math.floor(i/w);
            var x=pw*0.75*ix;
            var y=ph*iy;
            if(ix%2===1){
                y+=ph*0.5;
            }
            // create the tile group
            var oneTile=g.add.group(board.map);
            oneTile.x=x;
            oneTile.y=y;

            // create map table
            var terrainTable=['undefined', 'coast', 'desert', 'grass', 'mountain', 'water'];
            var resTable=['undefined', 'forest', 'oil'];
            var buildingTable=['undefined', 'apartments', 'factory', 'hospital', 'palace', 'shanties'];

            // create terrain, res and building
            var terrainIndex=parseInt(terrain[i],10);
            oneTile.create(0,0,terrainTable[terrainIndex]);

            var resIndex=parseInt(res[i],10);
            if(resIndex>=1){
                oneTile.create(0,0,resTable[resIndex]);
            }

            var buildingIndex=parseInt(building[i],10);
            if(buildingIndex>=1){
                oneTile.create(0,0,buildingTable[buildingIndex]);
            }
        }
        return board;
    },

    // returns the tile sprite at [i]
    at: function(b,i){
        return b.map.children[i];
    },
    // returns the adjacent index at clock direction [cd] of tile [i]
    adjacent: function(b,i,cd,warning){
        var w=b.width, h=b.height;
        var x=i%w;
        //              0   1   2   3   4   5   6   7   8   9   10  11
        var adj_even=[-w, -w+1,-w+1,0, +1,  +1, +w,-1,  -1, 0,  -w-1,-w-1];
        var adj_odd= [-w, +1,   +1, 0, +w+1,+w+1,+w,+w-1,+w-1,0,-1,     -1];
        // see if it is the leftmost/rightmost
        if(x===0){
            adj_even[7]=0, adj_even[8]=0, adj_even[10]=0, adj_even[11]=0;
        }else if(x===w-1){
            adj_even[1]=0, adj_even[2]=0, adj_even[4]=0, adj_even[5]=0;
        }
        var newIndex=(x%2===0?i+adj_even[cd]:i+adj_odd[cd])
        if(newIndex<0 || newIndex>=w*h){
            if(warning) console.warn('[Board] Tile '+i+' does not have an adjacent at '+cd);
            return null;
        }else if(newIndex===i){
            if(warning) console.error('[Board] The clock direction should not be '+cd);
            return null;
        }else{
            return newIndex;
        }
    },
    // returns all adjacent indice within [N] steps of tile [i]
    allAdjacent: function(b,i,N){
        var result=[i];
        var p0=0, p1=1;
        for(var j=0;j<N;j++){
            p1=result.length;
            for(var p=p0;p<p1;p++){
                var index=result[p];
                for(var cd=0;cd<12;cd+=2){
                    var adj=b.adjacent(index,cd);
                    if(adj) result.push(adj);
                }
            }
        }
        result.shift();
        return result;
    },
    // returns the (x,y) of i
    xyOf: function(b,i){
        var w=b.width;
        return {x:i%w, y:Math.floor(i/w)};
    },
    // returns the step distance between i and j
    distanceOf: function(b,i,j){
        var p0=b.xyOf(i), p1=b.xyOf(j);
        if(p0.x===p1.x){
            return Math.abs(p0.y-p1.y);
        }else if(p0.y===p1.y){
            return Math.abs(p0.x-p1.x);
        }else{
            var dx=Math.abs(p0.x-p1.x);
            var dy=Math.abs(p0.y-p1.y);
            if(p0.x%2===1){
                if(p0.y<p1.y){
                    return dx+dy-Math.ceil(dx/2);
                }else{
                    return dx+dy-Math.floor(dx/2);
                }
            }else{
                if(p0.y>p1.y){
                    return dx+dy-Math.ceil(dx/2);
                }else{
                    return dx+dy-Math.floor(dx/2);
                }
            }
        }
    },
};
<commit_msg>This is a test commit to the turnSystem branch<commit_after>// Board
var Board={
    // init func
    createNew: function(g,w,h,pw,terrain,res,building){
        var board={};

        // Class members
        board.game=g;
        board.width=w;
        board.height=h;
        board.map=g.add.group();

        // Class Functions
        // returns the tile sprite at [i]
        board.at=function(i){return Board.at(board,i);};
        // returns the adjacent index at clock direction [cd] of tile [i]
        board.adjacent=function(i,cd,warning){return Board.adjacent(board,i,cd,warning);};
        // returns all adjacent indice within [N] steps of tile [i]
        board.allAdjacent=function(i,N){return Board.allAdjacent(board,i,N);};
        // returns the (x,y) of i
        board.xyOf=function(i){return Board.xyOf(board,i);};
        // returns the step distance between i and j
        board.distanceOf=function(i,j){return Board.distanceOf(board,i,j);};

        // init
        var N=w*h;
        var ph=pw*(1.732/2.0);
        for(var i=0;i<N;i++){
            var ix=i%w;
            var iy=Math.floor(i/w);
            var x=pw*0.75*ix;
            var y=ph*iy;
            if(ix%2===1){
                y+=ph*0.5;
            }
            // create the tile group
            var oneTile=g.add.group(board.map);
            oneTile.x=x;
            oneTile.y=y;

            // create map table
            var terrainTable=['undefined', 'coast', 'desert', 'grass', 'mountain', 'water'];
            var resTable=['undefined', 'forest', 'oil'];
            var buildingTable=['undefined', 'apartments', 'factory', 'hospital', 'palace', 'shanties'];

            // create terrain, res and building
            var terrainIndex=parseInt(terrain[i],10);
            oneTile.create(0,0,terrainTable[terrainIndex]);

            var resIndex=parseInt(res[i],10);
            if(resIndex>=1){
                oneTile.create(0,0,resTable[resIndex]);
            }

            var buildingIndex=parseInt(building[i],10);
            if(buildingIndex>=1){
                oneTile.create(0,0,buildingTable[buildingIndex]);
            }
        }
        return board;
    },

    // returns the tile sprite at [i]
    at: function(b,i){
        return b.map.children[i];
    },
    // returns the adjacent index at clock direction [cd] of tile [i]
    adjacent: function(b,i,cd,warning){
        var w=b.width, h=b.height;
        var x=i%w;
        //              0   1   2   3   4   5   6   7   8   9   10  11
        var adj_even=[-w, -w+1,-w+1,0, +1,  +1, +w,-1,  -1, 0,  -w-1,-w-1];
        var adj_odd= [-w, +1,   +1, 0, +w+1,+w+1,+w,+w-1,+w-1,0,-1,     -1];
        // see if it is the leftmost/rightmost
        if(x===0){
            adj_even[7]=0, adj_even[8]=0, adj_even[10]=0, adj_even[11]=0;
        }else if(x===w-1){
            adj_even[1]=0, adj_even[2]=0, adj_even[4]=0, adj_even[5]=0;
        }
        var newIndex=(x%2===0?i+adj_even[cd]:i+adj_odd[cd])
        if(newIndex<0 || newIndex>=w*h){
            if(warning) console.warn('[Board] Tile '+i+' does not have an adjacent at '+cd);
            return null;
        }else if(newIndex===i){
            if(warning) console.error('[Board] The clock direction should not be '+cd);
            return null;
        }else{
            return newIndex;
        }
    },
    // returns all adjacent indice within [N] steps of tile [i]
    allAdjacent: function(b,i,N){
        var result=[i];
        var p0=0, p1=1;
        for(var j=0;j<N;j++){
            p1=result.length;
            for(var p=p0;p<p1;p++){
                var index=result[p];
                for(var cd=0;cd<12;cd+=2){
                    var adj=b.adjacent(index,cd);
                    if(adj) result.push(adj);
                }
            }
        }
        result.shift();
        return result;
    },
    // returns the (x,y) of i
    xyOf: function(b,i){
        var w=b.width;
        return {x:i%w, y:Math.floor(i/w)};
    },
    // returns the step distance between i and j
    distanceOf: function(b,i,j){
        var p0=b.xyOf(i), p1=b.xyOf(j);
        if(p0.x===p1.x){
            return Math.abs(p0.y-p1.y);
        }else if(p0.y===p1.y){
            return Math.abs(p0.x-p1.x);
        }else{
            var dx=Math.abs(p0.x-p1.x);
            var dy=Math.abs(p0.y-p1.y);
            if(p0.x%2===1){
                if(p0.y<p1.y){
                    return dx+dy-Math.ceil(dx/2);
                }else{
                    return dx+dy-Math.floor(dx/2);
                }
            }else{
                if(p0.y>p1.y){
                    return dx+dy-Math.ceil(dx/2);
                }else{
                    return dx+dy-Math.floor(dx/2);
                }
            }
        }
    },
};
<|endoftext|>


<commit_before>/**
 * Rollup configuration for packaging the plugin in a module that is consumable
 * as the `src` of a `script` tag or via AMD or similar client-side loading.
 *
 * This module DOES include its dependencies.
 */
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import json from 'rollup-plugin-json';
import string from 'rollup-plugin-string';
import resolve from 'rollup-plugin-node-resolve';

export default {
  moduleName: 'videojsShare',
  entry: 'src/plugin.js',
  dest: 'dist/videojs-share.js',
  format: 'umd',
  external: ['video.js'],
  globals: {
    'video.js': 'videojs'
  },
  legacy: true,
  plugins: [
    resolve({
      browser: true,
      main: true,
      jsnext: true
    }),
    string({
      include: 'src/icons/*.svg'
    }),
    json(),
    commonjs({
      sourceMap: false
    }),
    babel({
      babelrc: false,
      exclude: 'node_modules/**',
      presets: [
        ['es2015', {
          loose: true,
          modules: false
        }]
      ],
      plugins: [
        'external-helpers',
        'transform-object-assign'
      ]
    })
  ]
};
<commit_msg>fix: move commonjs upper<commit_after>/**
 * Rollup configuration for packaging the plugin in a module that is consumable
 * as the `src` of a `script` tag or via AMD or similar client-side loading.
 *
 * This module DOES include its dependencies.
 */
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import json from 'rollup-plugin-json';
import string from 'rollup-plugin-string';
import resolve from 'rollup-plugin-node-resolve';

export default {
  moduleName: 'videojsShare',
  entry: 'src/plugin.js',
  dest: 'dist/videojs-share.js',
  format: 'umd',
  external: ['video.js'],
  globals: {
    'video.js': 'videojs'
  },
  legacy: true,
  plugins: [
    commonjs({
      sourceMap: false
    }),
    resolve({
      browser: true,
      main: true,
      jsnext: true
    }),
    string({
      include: 'src/icons/*.svg'
    }),
    json(),
    babel({
      babelrc: false,
      exclude: 'node_modules/**',
      presets: [
        ['es2015', {
          loose: true,
          modules: false
        }]
      ],
      plugins: [
        'external-helpers',
        'transform-object-assign'
      ]
    })
  ]
};
<|endoftext|>


<commit_before>var body = document.body;
var html = document.documentElement;
var body = html.getElementsByTagName("body")[0];
var table = body.getElementsByTagName("table")[0];
var size = 20; // Size of cell

// Credit to http://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
var width = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth);
width -= 10; // Make the table a little smaller so there's a valid border.
height -= 10;
width = Math.floor(width/size);
height = Math.floor(height/size);
console.log("Width: "+width, " Height: "+height);
table.setAttribute("height", height*size + "px");
table.setAttribute("width", width*size + "px");
for (var i=0; i<height; i+=1) {
	var row = document.createElement("tr");
	for (var j=0; j<width; j+=1) {
	  var cell = document.createElement("td");
	  var btn = document.createElement("button");
	  cell.setAttribute("class", "emptycell");
	  cell.setAttribute("name", i+"_"+j);
	  btn.setAttribute("onclick", "placeFood("+i+","+j+")");
	  row.appendChild(cell);
	}
	table.appendChild(row);
}

function updateBoard(snake) {
  console.log(snake);
	for (var row in table.rows) {
	  for (var cell in row.cells) {
	    var isSnakeCell = false;
	    for (var s in snake) {
  	    if (cell.name == s[0]+"_"+s[1]) {
    	    isSnakeCell = true;
    	    break;
    	  }
	    }
	    console.log(cell);
	    if (isSnakeCell) {
        cell.setAttribute("class", "snakecell");
	    } else {
  	    cell.setAttribute("class", "emptycell");
  	  }
	  }
	}
}<commit_msg>Debugging again<commit_after>var body = document.body;
var html = document.documentElement;
var body = html.getElementsByTagName("body")[0];
var table = body.getElementsByTagName("table")[0];
var size = 20; // Size of cell

// Credit to http://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
var width = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth);
width -= 10; // Make the table a little smaller so there's a valid border.
height -= 10;
width = Math.floor(width/size);
height = Math.floor(height/size);
console.log("Width: "+width, " Height: "+height);
table.setAttribute("height", height*size + "px");
table.setAttribute("width", width*size + "px");
for (var i=0; i<height; i+=1) {
	var row = document.createElement("tr");
	for (var j=0; j<width; j+=1) {
	  var cell = document.createElement("td");
	  var btn = document.createElement("button");
	  cell.setAttribute("class", "emptycell");
	  cell.setAttribute("name", i+"_"+j);
	  btn.setAttribute("onclick", "placeFood("+i+","+j+")");
	  row.appendChild(cell);
	}
	table.appendChild(row);
}

function updateBoard(snake) {
  console.log(snake);
	for (var row in table.rows) {
  	console.log(row);
	  for (var cell in row.cells) {
  	  console.log(cell);
	    var isSnakeCell = false;
	    for (var s in snake) {
  	    if (cell.name == s[0]+"_"+s[1]) {
    	    isSnakeCell = true;
    	    break;
    	  }
	    }
	    console.log(cell);
	    if (isSnakeCell) {
        cell.setAttribute("class", "snakecell");
	    } else {
  	    cell.setAttribute("class", "emptycell");
  	  }
	  }
	}
}<|endoftext|>


<commit_before>const inquirer = require('inquirer')
const CanvasApi = require('kth-canvas-api')
process.env['NODE_ENV'] = 'production'
const csvFile = require('../csvFile')
require('colors')
async function createFile () {
  const {api} = await inquirer.prompt(
    {
      message: 'Vilken miljö?',
      name: 'api',
      choices: [
        {name: 'test', value: {apiUrl: 'https://kth.test.instructure.com/api/v1'}},
        {name: 'prod', value: {apiUrl: 'https://kth.instructure.com/api/v1'}},
        {name: 'beta', value: {apiUrl: 'https://kth.beta.instructure.com/api/v1'}}
      ],
      type: 'list'
    })
  const {apiUrl} = api

  const {apiKey} = await inquirer.prompt({
    message: 'Klistra in api nyckel till Canvas här',
    name: 'apiKey',
    type: 'string'
  })

  const canvasApi = new CanvasApi(apiUrl, apiKey)
  canvasApi.logger = {info () {
    for (let arg of arguments) {
      console.log(arg.yellow)
    }
  }}
  try {
    const sectionFileName = 'csv/unenrollObserversSections.csv'
    const coursesFileName = 'csv/unenrollObserversCourses.csv'

    await csvFile.writeLine(['section_id', 'user_id', 'role', 'status'], sectionFileName)
    await csvFile.writeLine(['course_id', 'user_id', 'role', 'status'], coursesFileName)

    const courses = await canvasApi.get(`/accounts/1/courses?per_page=100`)

    const allEnrollments = []
    for (let course of courses) {
      try {
        const enrollments = await canvasApi.get(`/courses/${course.id}/enrollments?role[]=Applied%20pending%20registration%20(Observer)&per_page=100`)
        allEnrollments.push(...enrollments)
        for (let enrollment of enrollments) {
          // console.log('Unenroll the user with the old role (21)')
          await canvasApi.requestUrl(`/courses/${enrollment.course_id}/enrollments/${enrollment.id}`, 'DELETE')
        }
      } catch (e) {
        console.log('an error occured, continue', e)
      }
    }
    console.log('Done.'.green)
    console.log(JSON.stringify(allEnrollments, null, 4))
  } catch (err) {
    console.error(err)
  }
}
createFile()
<commit_msg>moved unenroll script over to lms-courses instead<commit_after><|endoftext|>


<commit_before>var CSSTransitionEditor = function(previousValue) {
    var self = this;
    self._map = {};

    if (previousValue) {
        var parts = previousValue.split(",");
        for (var part in parts) {
            var stripped = part.replace(/^\s+|\s+$/g, '');
            var fields = stripped.split(/\s+/);
            if (fields.length != 2)
                continue;
            self._map[fields[0]] = fields[1];
        }
    }

    self.set = function(field, value) {
        self._map[field] = value;
    }
    self.unset = function(field) {
        delete self._map[field];
    }
    self.serialize = function() {
        result = [];
        for (var field in self._map)
            result.push(field + " " + self._map[field]);
        return result.join(", ");
    }
};

(function() {

var app = angular.module('whiteframe', []);

var zHeights = [
    { boxShadow: null },
    { boxShadow: '0px 2px 5px 0', boxShadowOpacity: 0.26 },
    { boxShadow: '0px 8px 17px', boxShadowOpacity: 0.2 },
    { boxShadow: '0px 17px 50px', boxShadowOpacity: 0.19 },
    { boxShadow: '0px 16px 28px 0', boxShadowOpacity: 0.22 },
    { boxShadow: '0px 27px 24px 0', boxShadowOpacity: 0.2 },
];

var growCSSTransition = function(element, toWidth, toHeight, toLeft, toTop) {
    var editor = new CSSTransitionEditor(element.style.transition);
    editor.set('width', '0.3s');
    editor.set('height', '0.3s');
    editor.set('left', '0.3s');
    editor.set('top', '0.3s');
    var transition = editor.serialize();
    element.style['-os-transition'] = transition;
    element.style['-moz-transition'] = transition;
    element.style['-webkit-transition'] = transition;
    element.style.transition = transition;
    element.style.width = '' + toWidth + 'px';
    element.style.height = '' + toHeight + 'px';
    element.style.left = '' + toLeft + 'px';
    element.style.top = '' + toTop + 'px';
};

app.directive('whiteframeOver', ['$compile', '$q', '$parse',
    function ($compile, $q, $parse) {
        'use strict';

        return {
            restrict: 'A',
            scope: {
                depthText: "@whiteframeZheight",
                paddingText: "@whiteframePadding",
                heightMultiplierText: "@whiteframeHeightMultiplier",
            },
            link: function (scope, element, attrs, ngModelCtrl) {
                scope.isOpen = false;
                scope.open = function() {
                    scope.isOpen = true;
                };
                scope.$parent.openWhiteframe = scope.open;
                scope.close = function() {
                    scope.isOpen = false;
                };
                scope.$parent.closeWhiteframe = scope.close;
                scope.depth = parseInt(scope.depthText);
                scope.padding = parseInt(scope.paddingText);
                scope.heightMultiplier = parseInt(scope.heightMultiplierText);
                $(element).children().hide();
                var closedRoot = $(element).children()[0];
                var openedRoot = $(element).children()[1];
                $(closedRoot).show();
                scope.$watch('isOpen', function(value, prev) {
                    if (value === prev)
                        return;
                    if (value === true) {
                        var offset = $(closedRoot).offset();
                        var width = $(closedRoot).width();
                        var height = $(closedRoot).height();
                        var zHeight = zHeights[scope.depth];
                        $(openedRoot).show().offset(offset).width(width).height(height);
                        openedRoot.style.boxShadow = zHeight.boxShadow + ' rgba(0,0,0,0)';
                        openedRoot.style['box-shadow-opacity'] = 0;
                        $(openedRoot).animate({
                            'box-shadow-opacity': zHeight.boxShadowOpacity}, {
                            duration: 200,
                            step: function( now, fx ) {
                                openedRoot.style.boxShadow = zHeight.boxShadow + ' rgba(0,0,0,' + now + ')';
                            },
                            complete: function() {
                                growCSSTransition(openedRoot,
                                    width + 2*scope.padding,
                                    scope.heightMultiplier * height,
                                    -scope.padding,
                                    -(scope.heightMultiplier * height + 1) / 2);
                            },
                        });
                    } else {
                        var offset = $(closedRoot).offset();
                        var width = $(closedRoot).width();
                        var height = $(closedRoot).height();
                        $(openedRoot).fadeOut(200, function(){
                            $(openedRoot).show().offset(offset).width(width).height(height).hide();
                        });
                    }
                });
            }
        }
    }
]);

app.directive('whiteframeMenu', ['$compile', '$q', '$parse',
    function ($compile, $q, $parse) {
        'use strict';

        return {
            restrict: 'E',
            replace: true,
            scope: {
                zheight: "@whiteframeZheight",
                heightMultiplier: "@whiteframeHeightMultiplier",
                options: "=whiteframeMenuOptions",
                selected: "=whiteframeMenuSelected",
            },
            template:
                '
' +
                '
' +
                '
' +
                '        ' +
                '
' +
                '
' +
                '                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"><path d="M5 8l4 4 4-4z"/></svg>' +
                '
'+
                '
'+
                '
' +
                '
' +
                '        Click me!' +
                '
' +
                '

',
            controller: function($scope, $element) {
                if (!$scope.zheight)
                    $scope.zheight = 1;
                if (!$scope.heightMultiplier)
                    $scope.heightMultiplier = 5;
                $scope.showingLabel = "";
                if ($scope.selected)
                    $scope.showingLabel = $scope.selected.label;
            },
        };
    }
]);

})();
<commit_msg>Simpler fade in animation code<commit_after>var CSSTransitionEditor = function(previousValue) {
    var self = this;
    self._map = {};

    if (previousValue) {
        var parts = previousValue.split(",");
        for (var part in parts) {
            var stripped = part.replace(/^\s+|\s+$/g, '');
            var fields = stripped.split(/\s+/);
            if (fields.length != 2)
                continue;
            self._map[fields[0]] = fields[1];
        }
    }

    self.set = function(field, value) {
        self._map[field] = value;
    }
    self.unset = function(field) {
        delete self._map[field];
    }
    self.serialize = function() {
        result = [];
        for (var field in self._map)
            result.push(field + " " + self._map[field]);
        return result.join(", ");
    }
};

(function() {

var app = angular.module('whiteframe', []);

var zHeights = [
    { boxShadow: null },
    { boxShadow: '0px 2px 5px 0', boxShadowOpacity: 0.26 },
    { boxShadow: '0px 8px 17px', boxShadowOpacity: 0.2 },
    { boxShadow: '0px 17px 50px', boxShadowOpacity: 0.19 },
    { boxShadow: '0px 16px 28px 0', boxShadowOpacity: 0.22 },
    { boxShadow: '0px 27px 24px 0', boxShadowOpacity: 0.2 },
];

var growCSSTransition = function(element, toWidth, toHeight, toLeft, toTop) {
    var editor = new CSSTransitionEditor(element.style.transition);
    editor.set('width', '0.3s');
    editor.set('height', '0.3s');
    editor.set('left', '0.3s');
    editor.set('top', '0.3s');
    var transition = editor.serialize();
    element.style['-os-transition'] = transition;
    element.style['-moz-transition'] = transition;
    element.style['-webkit-transition'] = transition;
    element.style.transition = transition;
    element.style.width = '' + toWidth + 'px';
    element.style.height = '' + toHeight + 'px';
    element.style.left = '' + toLeft + 'px';
    element.style.top = '' + toTop + 'px';
};

app.directive('whiteframeOver', ['$compile', '$q', '$parse',
    function ($compile, $q, $parse) {
        'use strict';

        return {
            restrict: 'A',
            scope: {
                depthText: "@whiteframeZheight",
                paddingText: "@whiteframePadding",
                heightMultiplierText: "@whiteframeHeightMultiplier",
            },
            link: function (scope, element, attrs, ngModelCtrl) {
                scope.isOpen = false;
                scope.open = function() {
                    scope.isOpen = true;
                };
                scope.$parent.openWhiteframe = scope.open;
                scope.close = function() {
                    scope.isOpen = false;
                };
                scope.$parent.closeWhiteframe = scope.close;
                scope.depth = parseInt(scope.depthText);
                scope.padding = parseInt(scope.paddingText);
                scope.heightMultiplier = parseInt(scope.heightMultiplierText);
                $(element).children().hide();
                var closedRoot = $(element).children()[0];
                var openedRoot = $(element).children()[1];
                $(closedRoot).show();
                scope.$watch('isOpen', function(value, prev) {
                    if (value === prev)
                        return;
                    if (value === true) {
                        var offset = $(closedRoot).offset();
                        var width = $(closedRoot).width();
                        var height = $(closedRoot).height();
                        var zHeight = zHeights[scope.depth];
                        $(openedRoot).show().offset(offset).width(width).height(height);
                        openedRoot.style.boxShadow = zHeight.boxShadow + ' rgba(0,0,0,' + zHeight.boxShadowOpacity + ')';
                        $(openedRoot).hide().fadeIn(200, function() {
                            growCSSTransition(openedRoot,
                                width + 2*scope.padding,
                                scope.heightMultiplier * height,
                                -scope.padding,
                                -(scope.heightMultiplier * height + 1) / 2);
                        });
                    } else {
                        var offset = $(closedRoot).offset();
                        var width = $(closedRoot).width();
                        var height = $(closedRoot).height();
                        $(openedRoot).fadeOut(200, function(){
                            $(openedRoot).show().offset(offset).width(width).height(height).hide();
                        });
                    }
                });
            }
        }
    }
]);

app.directive('whiteframeMenu', ['$compile', '$q', '$parse',
    function ($compile, $q, $parse) {
        'use strict';

        return {
            restrict: 'E',
            replace: true,
            scope: {
                zheight: "@whiteframeZheight",
                heightMultiplier: "@whiteframeHeightMultiplier",
                options: "=whiteframeMenuOptions",
                selected: "=whiteframeMenuSelected",
            },
            template:
                '
' +
                '
' +
                '
' +
                '        ' +
                '
' +
                '
' +
                '                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"><path d="M5 8l4 4 4-4z"/></svg>' +
                '
'+
                '
'+
                '
' +
                '
' +
                '        Click me!' +
                '
' +
                '

',
            controller: function($scope, $element) {
                if (!$scope.zheight)
                    $scope.zheight = 1;
                if (!$scope.heightMultiplier)
                    $scope.heightMultiplier = 5;
                $scope.showingLabel = "";
                if ($scope.selected)
                    $scope.showingLabel = $scope.selected.label;
            },
        };
    }
]);

})();
<|endoftext|>