<commit_before>dojo.provide("dijit._editor.selection");

// FIXME:
//		all of these methods branch internally for IE. This is probably
//		sub-optimal in terms of runtime performance. We should investigate the
//		size difference for differentiating at definition time.

dojo.mixin(dijit._editor.selection, {
	getType: function(){
		// summary: Get the selection type (like document.select.type in IE).
		if(dojo.doc["selection"]){ //IE
			return dojo.doc.selection.type.toLowerCase();
		}else{
			var stype = "text";

			// Check if the actual selection is a CONTROL (IMG, TABLE, HR, etc...).
			var oSel;
			try{
				oSel = dojo.global.getSelection();
			}catch(e){ /*squelch*/ }

			if(oSel && oSel.rangeCount==1){
				var oRange = oSel.getRangeAt(0);
				if(	(oRange.startContainer == oRange.endContainer) &&
					((oRange.endOffset - oRange.startOffset) == 1) &&
					(oRange.startContainer.nodeType != 3 /* text node*/)
				){
					stype = "control";
				}
			}
			return stype;
		}
	},

	getSelectedText: function(){
		// summary:
		//		Return the text (no html tags) included in the current selection or null if no text is selected
		if(dojo.doc["selection"]){ //IE
			if(dijit._editor.selection.getType() == 'control'){
				return null;
			}
			return dojo.doc.selection.createRange().text;
		}else{
			var selection = dojo.global.getSelection();
			if(selection){
				return selection.toString();
			}
		}
	},

	getSelectedHtml: function(){
		// summary:
		//		Return the html of the current selection or null if unavailable
		if(dojo.doc["selection"]){ //IE
			if(dijit._editor.selection.getType() == 'control'){
				return null;
			}
			return dojo.doc.selection.createRange().htmlText;
		}else{
			var selection = dojo.global.getSelection();
			if(selection && selection.rangeCount){
				var frag = selection.getRangeAt(0).cloneContents();
				var div = document.createElement("div");
				div.appendChild(frag);
				return div.innerHTML;
			}
			return null;
		}
	},

	getSelectedElement: function(){
		// summary:
		//		Retrieves the selected element (if any), just in the case that
		//		a single element (object like and image or a table) is
		//		selected.
		if(this.getType() == "control"){
			if(dojo.doc["selection"]){ //IE
				var range = dojo.doc.selection.createRange();
				if(range && range.item){
					return dojo.doc.selection.createRange().item(0);
				}
			}else{
				var selection = dojo.global.getSelection();
				return selection.anchorNode.childNodes[ selection.anchorOffset ];
			}
		}
	},

	getParentElement: function(){
		// summary:
		//		Get the parent element of the current selection
		if(this.getType() == "control"){
			var p = this.getSelectedElement();
			if(p){ return p.parentNode; }
		}else{
			if(dojo.doc["selection"]){ //IE
				return dojo.doc.selection.createRange().parentElement();
			}else{
				var selection = dojo.global.getSelection();
				if(selection){
					var node = selection.anchorNode;

					while(node && (node.nodeType != 1)){ // not an element
						node = node.parentNode;
					}

					return node;
				}
			}
		}
	},

	hasAncestorElement: function(/*String*/tagName /* ... */){
		// summary:
		// 		Check whether current selection has a  parent element which is
		// 		of type tagName (or one of the other specified tagName)
		return (this.getAncestorElement.apply(this, arguments) != null);
	},

	getAncestorElement: function(/*String*/tagName /* ... */){
		// summary:
		//		Return the parent element of the current selection which is of
		//		type tagName (or one of the other specified tagName)

		var node = this.getSelectedElement() || this.getParentElement();
		return this.getParentOfType(node, arguments);
	},

	isTag: function(/*DomNode*/node, /*Array*/tags){
		if(node && node.tagName){
			var _nlc = node.tagName.toLowerCase();
			for(var i=0; i<tags.length; i++){
				var _tlc = String(tags[i]).toLowerCase();
				if(_nlc == _tlc){
					return _tlc;
				}
			}
		}
		return "";
	},

	getParentOfType: function(/*DomNode*/node, /*Array*/tags){
		while(node){
			if(this.isTag(node, tags).length){
				return node;
			}
			node = node.parentNode;
		}
		return null;
	},

	remove: function(){
		// summary: delete current selection
		var _s = dojo.doc.selection;
		if(_s){ //IE
			if(_s.type.toLowerCase() != "none"){
				_s.clear();
			}
			return _s;
		}else{
			_s = dojo.global.getSelection();
			_s.deleteFromDocument();
			return _s;
		}
	},

	selectElementChildren: function(/*DomNode*/element,/*Boolean?*/nochangefocus){
		// summary:
		//		clear previous selection and select the content of the node
		//		(excluding the node itself)
		var _window = dojo.global;
		var _document = dojo.doc;
		element = dojo.byId(element);
		if(_document.selection && dojo.body().createTextRange){ // IE
			var range = element.ownerDocument.body.createTextRange();
			range.moveToElementText(element);
			if(!nochangefocus){
				range.select();
			}
		}else if(_window["getSelection"]){
			var selection = _window.getSelection();
			if(selection["setBaseAndExtent"]){ // Safari
				selection.setBaseAndExtent(element, 0, element, element.innerText.length - 1);
			}else if(selection["selectAllChildren"]){ // Mozilla
				selection.selectAllChildren(element);
			}
		}
	},

	selectElement: function(/*DomNode*/element,/*Boolean?*/nochangefocus){
		// summary:
		//		clear previous selection and select element (including all its children)
		var _document = dojo.doc;
		element = dojo.byId(element);
		if(_document.selection && dojo.body().createTextRange){ // IE
			try{
				var range = dojo.body().createControlRange();
				range.addElement(element);
				if(!nochangefocus){
					range.select();
				}
			}catch(e){
				this.selectElementChildren(element,nochangefocus);
			}
		}else if(dojo.global["getSelection"]){
			var selection = dojo.global.getSelection();
			// FIXME: does this work on Safari?
			if(selection["removeAllRanges"]){ // Mozilla
				var range = _document.createRange() ;
				range.selectNode(element) ;
				selection.removeAllRanges() ;
				selection.addRange(range) ;
			}
		}
	}
});
<commit_msg>add comment about IE error if widget is hidden.  Refs #5439 !strict<commit_after>dojo.provide("dijit._editor.selection");

// FIXME:
//		all of these methods branch internally for IE. This is probably
//		sub-optimal in terms of runtime performance. We should investigate the
//		size difference for differentiating at definition time.

dojo.mixin(dijit._editor.selection, {
	getType: function(){
		// summary: Get the selection type (like document.select.type in IE).
		if(dojo.doc.selection){ //IE
			return dojo.doc.selection.type.toLowerCase();
		}else{
			var stype = "text";

			// Check if the actual selection is a CONTROL (IMG, TABLE, HR, etc...).
			var oSel;
			try{
				oSel = dojo.global.getSelection();
			}catch(e){ /*squelch*/ }

			if(oSel && oSel.rangeCount==1){
				var oRange = oSel.getRangeAt(0);
				if(	(oRange.startContainer == oRange.endContainer) &&
					((oRange.endOffset - oRange.startOffset) == 1) &&
					(oRange.startContainer.nodeType != 3 /* text node*/)
				){
					stype = "control";
				}
			}
			return stype;
		}
	},

	getSelectedText: function(){
		// summary:
		//		Return the text (no html tags) included in the current selection or null if no text is selected
		if(dojo.doc.selection){ //IE
			if(dijit._editor.selection.getType() == 'control'){
				return null;
			}
			return dojo.doc.selection.createRange().text;
		}else{
			var selection = dojo.global.getSelection();
			if(selection){
				return selection.toString();
			}
		}
	},

	getSelectedHtml: function(){
		// summary:
		//		Return the html of the current selection or null if unavailable
		if(dojo.doc.selection){ //IE
			if(dijit._editor.selection.getType() == 'control'){
				return null;
			}
			return dojo.doc.selection.createRange().htmlText;
		}else{
			var selection = dojo.global.getSelection();
			if(selection && selection.rangeCount){
				var frag = selection.getRangeAt(0).cloneContents();
				var div = document.createElement("div");
				div.appendChild(frag);
				return div.innerHTML;
			}
			return null;
		}
	},

	getSelectedElement: function(){
		// summary:
		//		Retrieves the selected element (if any), just in the case that
		//		a single element (object like and image or a table) is
		//		selected.
		if(this.getType() == "control"){
			if(dojo.doc.selection){ //IE
				var range = dojo.doc.selection.createRange();
				if(range && range.item){
					return dojo.doc.selection.createRange().item(0);
				}
			}else{
				var selection = dojo.global.getSelection();
				return selection.anchorNode.childNodes[ selection.anchorOffset ];
			}
		}
	},

	getParentElement: function(){
		// summary:
		//		Get the parent element of the current selection
		if(this.getType() == "control"){
			var p = this.getSelectedElement();
			if(p){ return p.parentNode; }
		}else{
			if(dojo.doc.selection){ //IE
				return dojo.doc.selection.createRange().parentElement();
			}else{
				var selection = dojo.global.getSelection();
				if(selection){
					var node = selection.anchorNode;

					while(node && (node.nodeType != 1)){ // not an element
						node = node.parentNode;
					}

					return node;
				}
			}
		}
	},

	hasAncestorElement: function(/*String*/tagName /* ... */){
		// summary:
		// 		Check whether current selection has a  parent element which is
		// 		of type tagName (or one of the other specified tagName)
		return this.getAncestorElement.apply(this, arguments) != null;
	},

	getAncestorElement: function(/*String*/tagName /* ... */){
		// summary:
		//		Return the parent element of the current selection which is of
		//		type tagName (or one of the other specified tagName)

		var node = this.getSelectedElement() || this.getParentElement();
		return this.getParentOfType(node, arguments);
	},

	isTag: function(/*DomNode*/node, /*Array*/tags){
		if(node && node.tagName){
			var _nlc = node.tagName.toLowerCase();
			for(var i=0; i<tags.length; i++){
				var _tlc = String(tags[i]).toLowerCase();
				if(_nlc == _tlc){
					return _tlc;
				}
			}
		}
		return "";
	},

	getParentOfType: function(/*DomNode*/node, /*Array*/tags){
		while(node){
			if(this.isTag(node, tags).length){
				return node;
			}
			node = node.parentNode;
		}
		return null;
	},

	remove: function(){
		// summary: delete current selection
		var _s = dojo.doc.selection;
		if(_s){ //IE
			if(_s.type.toLowerCase() != "none"){
				_s.clear();
			}
			return _s;
		}else{
			_s = dojo.global.getSelection();
			_s.deleteFromDocument();
			return _s;
		}
	},

	selectElementChildren: function(/*DomNode*/element,/*Boolean?*/nochangefocus){
		// summary:
		//		clear previous selection and select the content of the node
		//		(excluding the node itself)
		var _window = dojo.global;
		var _document = dojo.doc;
		element = dojo.byId(element);
		if(_document.selection && dojo.body().createTextRange){ // IE
			var range = element.ownerDocument.body.createTextRange();
			range.moveToElementText(element);
			if(!nochangefocus){
				range.select(); // IE throws an exception here if the widget is hidden.  See #5439
			}
		}else if(_window.getSelection){
			var selection = _window.getSelection();
			if(selection.setBaseAndExtent){ // Safari
				selection.setBaseAndExtent(element, 0, element, element.innerText.length - 1);
			}else if(selection.selectAllChildren){ // Mozilla
				selection.selectAllChildren(element);
			}
		}
	},

	selectElement: function(/*DomNode*/element,/*Boolean?*/nochangefocus){
		// summary:
		//		clear previous selection and select element (including all its children)
		var range, _document = dojo.doc;
		element = dojo.byId(element);
		if(_document.selection && dojo.body().createTextRange){ // IE
			try{
				range = dojo.body().createControlRange();
				range.addElement(element);
				if(!nochangefocus){
					range.select();
				}
			}catch(e){
				this.selectElementChildren(element,nochangefocus);
			}
		}else if(dojo.global.getSelection){
			var selection = dojo.global.getSelection();
			// FIXME: does this work on Safari?
			if(selection.removeAllRanges){ // Mozilla
				range = _document.createRange();
				range.selectNode(element);
				selection.removeAllRanges();
				selection.addRange(range);
			}
		}
	}
});
<|endoftext|>


<commit_before>var State = require('ampersand-state');
var View = require('ampersand-view');

var Numbers = require('./numbers.js');

//------------------------------------------------------------------------------

function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

//------------------------------------------------------------------------------

var colors = [
  "#ED2079",
  "#ED3E36",
  "#F76321",
  "#FFB73B",
  "#F5EC2B",
  "#8DC53A",
  "#37B347",
  "#00ABEE",
  "#283891",
  "#92278B"
];
var minWidth = 768;
var minRadius = 0.5;

var radius;
var gridSpacing = 25;
var padding;
var alreadyWarned = false;

var widthColsToRadius = function(width, cols) {
  // width: 2 * (gridSpacing + radius) + (cols - 1) * (2 * radius + gridSpacing)
	// w = 2 * (g + r) + (c - 1) * (2 * r + g)
  // w = c * g + 2 * c * r + g
  // (w - (c * g) - g) / (2 * c) = r
  return (width - (cols * gridSpacing) - gridSpacing) / (2 * cols);
}

var radiusDensityToWidth = function(radius, cols) {
  return cols * gridSpacing + 2 * cols * radius + gridSpacing;
}

var widthRadiusToCols = function(width, radius) {
  // w = c *(g + 2 * r) + g
  // (w - g) / (g + 2 * r) = c
  return (width - gridSpacing) / (gridSpacing + 2 * radius);
}

var render = function(cols, displayMode, subject) {
  var svg = d3.select("svg");
  var limit = subject.length;
  var width = svg.attr("width");
  var heigth;
  var strokeWidth;
  var circlesData = [];
  var linesData = [];
  var thisDigit;
  var digitSW, digitW, digitNW, digitN;
  var iSW, iW, iNW, iN;
  var nextDigit = 3;
  var thisX, nextX, thisY, nextY;
  var thisColor;
  var firstCol, lastCol, firstRow, lastRow;
  var datum;
  var i, xIndex;
  var xCoord = function(i) {
    return padding + (i % cols) * (gridSpacing + 2 * radius);
  }
  var yCoord = function(i) {
    return padding + Math.floor(i / cols) * (gridSpacing + 2 * radius);
  }
  var markEqualNeigbour = function(i) {
    if (typeof circlesData[i] !== 'undefined') {
      circlesData[i].hasEqualNeighbour = true;
    }
  };

  radius = widthColsToRadius(width, cols);
  strokeWidth = radius / 2.5;
  padding = radius + gridSpacing;

  height = (2 * padding) + (limit / cols) * (2 * radius) + ((limit / cols) - 1) * gridSpacing;
  svg.attr("height", height);

  for (i = 0; i < limit; i++) {
    thisDigit = nextDigit;
    nextDigit = parseInt(subject.charAt(i + 1), 10);
    thisColor = colors[thisDigit];
    thisX = xCoord(i);
    thisY = yCoord(i);
    nextX = xCoord(i + 1);
    nextY = yCoord(i + 1);
    xIndex = i % cols;
    firstCol = xIndex === 0;
    lastCol = xIndex === cols - 1;
    firstRow = i <= cols;
    lastRow = i >= (limit - cols - 1);

    datum = {
      outerColor: thisColor,
      innerColor: colors[nextDigit],
      x: thisX,
      y: thisY,
      r: radius,
      hasEqualNeighbour: false
    };

    if (displayMode > 0) {
      if (!firstCol && !lastRow) {
        iSW = i + cols - 1;
        digitSW = parseInt(subject.charAt(iSW), 10);

        if (thisDigit === digitSW) {
          markEqualNeigbour(iSW);
          datum.hasEqualNeighbour = true;
          swX = xCoord(iSW);
          swY = yCoord(iSW);

          linesData.push({
            x1: thisX, x2: swX,
            y1: thisY, y2: swY,
            color: thisColor,
            "stroke-width": datum.r
          })
        }
      }

      if (!firstRow) { // second row and onwards
        iN = i - cols;
        digitN = parseInt(subject.charAt(iN), 10);
        nX = xCoord(iN);
        nY = yCoord(iN);

        if (thisDigit === digitN) {
          markEqualNeigbour(iN);
          datum.hasEqualNeighbour = true;

          linesData.push({
            x1: thisX, x2: nX,
            y1: thisY, y2: nY,
            color: thisColor,
            "stroke-width": datum.r
          })
        }

        if (!firstCol) {
          iW = i - 1;
          iNW = i - cols - 1;
          digitW = parseInt(subject.charAt(iW), 10);
          digitNW = parseInt(subject.charAt(iNW), 10);

          if (thisDigit === digitW) {
            markEqualNeigbour(iW);
            datum.hasEqualNeighbour = true;
            wX = xCoord(iW);
            wY = yCoord(iW);

            linesData.push({
              x1: thisX, x2: wX,
              y1: thisY, y2: wY,
              color: thisColor,
              "stroke-width": datum.r
            })
          }

          if (thisDigit === digitNW) {
            markEqualNeigbour(iNW);
            datum.hasEqualNeighbour = true;

            nwX = xCoord(iNW);
            nwY = yCoord(iNW);

            linesData.push({
              x1: thisX, x2: nwX,
              y1: thisY, y2: nwY,
              color: thisColor,
              "stroke-width": datum.r
            })
          }
        }
      }

      if (!lastCol) {
        // Special case because we can't "mark" neighbours ahead of them being
        // inserted into circlesData, which is the case of digitSW === thisDigit

        digitNE = parseInt(subject.charAt(i - cols + 1), 10);

        if (thisDigit === digitNE) {
          if (typeof circlesData[i - cols + 1] !== 'undefined') {
            circlesData[i - cols + 1].hasEqualNeighbour = true;
          }
          datum.hasEqualNeighbour = true;
        }
      }
    }

    circlesData.push(datum)
  }

  // Remove neighbourless circles in third display mode
  if (displayMode === 2) {
    for (i = circlesData.length - 1; i >= 0; i -= 1) {
      if (!circlesData[i].hasEqualNeighbour) {
        circlesData.splice(i, 1);
      }
    }
  }

  // CIRCLES

  var circlesGroup = svg.select('g.circles');
  var circlesSelection = circlesGroup.selectAll('g').data(circlesData);
  var clipStrokeCircle = svg.select('#cstroke circle');
  clipStrokeCircle.attr({ r: radius });

  var groupAttr = {
    transform: function(d) {
      return 'translate(' + d.x + ',' + d.y + ')';
    }
  }

  var colorValve = function(open, colorCode) {
    if (displayMode === 2) {
      if (open) {
        return colorCode;
      } else {
        return '#000';
      }
    } else {
      return colorCode;
    }
  };

  var circleAttr = {
    r: function(d) { return d.r },
    "stroke-width": function(d) { return d.r / 1.4 },
    "stroke": function(d) {
      return d.outerColor;
      //return colorValve(d.hasEqualNeighbour, d.outerColor);
    },
    "clip-path": "url(#cstroke)",
    "fill": function(d) {
      return d.innerColor;
      //return colorValve(d.hasEqualNeighbour, d.innerColor);
    }

  }

  // Enter
  var groups = circlesSelection.enter().append('g');
  var circle = groups.append('circle');

  // Enter + Update
  circlesSelection.attr(groupAttr).select('circle').attr(circleAttr);

  circlesSelection.exit().remove();

  // LINES

  var linesGroup = svg.select('g.displayMode');
  var linesSelection = linesGroup.selectAll('line').data(linesData);

  var linesAttr = {
    x1: function(d) { return d.x1; },
    y1: function(d) { return d.y1; },
    x2: function(d) { return d.x2; },
    y2: function(d) { return d.y2; },
    "stroke-width": function(d) { return d["stroke-width"]; },
    "stroke": function(d) { return d.color; }
  };

  // Enter
  linesSelection.enter().append('line');

  // Enter + Update
  linesSelection.attr(linesAttr);

  linesSelection.exit().remove();
};

//------------------------------------------------------------------------------

var StageView = View.extend({
  template: '<svg id="stage"></svg>',

  autoRender: true,

  bindings: {
    "model.width": {
      type: "attribute",
      name: "width"
    }
  },

  events: {
    'click': function() {
      this.model.cycleDisplayMode();
    }
  },

  render: function() {
    if (!this.rendered) {
      View.prototype.render.apply(this, arguments);

      var svg = d3.select(this.el);

      svg.append('defs').append('clipPath').attr({id: 'cstroke'}).
        append('circle');
      svg.append('g').classed('displayMode', true);
      svg.append('g').classed('circles', true);
    }
  }
});

//------------------------------------------------------------------------------

ready(function() {
  var _densitySlider = d3.select("#density-slider");
  var _colsSlider = d3.select("#columns-slider");
  var minDensity = 1, maxDensity = 29, densityValue = 20;
  var minCols = 1, maxCols = 29, colsValue = 20;
  var numbers = new Numbers();

  var _phi = d3.select("#phi-link");
  var _pi = d3.select("#pi-link");
  var _e = d3.select("#e-link");

  var svg = d3.select("svg");

  //----------------------------------------------------------------------------

  var StageState = State.extend({
    props: {
      width: ['number', true, 768],
      displayMode: ['number', true, 0],
      subjectValue: ['string', true, numbers.subjectValue()]
    },

    cycleDisplayMode: function() {
      this.displayMode = (this.displayMode + 1) % 3;
    }
  });

  var stageState = new StageState();

  var stageView = new StageView({
    model: stageState,
    el: svg[0][0]
  });

  stageState.on('change', function() {
    stageView.render();
  })

  //----------------------------------------------------------------------------

  _phi.on("click", function() {
    d3.event.preventDefault();

    _phi.classed("active", true);
    _pi.classed("active", false);
    _e.classed("active", false);

    numbers.setSubject(Numbers.PHI, function() {
      stageState.subjectValue = numbers.subjectValue();

      render(densityValue, stageState.displayMode, stageState.subjectValue);
    });
  });

  _pi.on("click", function() {
    d3.event.preventDefault();

    _phi.classed("active", false);
    _pi.classed("active", true);
    _e.classed("active", false);

    numbers.setSubject(Numbers.PI, function() {
      stageState.subjectValue = numbers.subjectValue();

      render(densityValue, stageState.displayMode, stageState.subjectValue);
    });
  });

  _e.on("click", function() {
    d3.event.preventDefault();

    _phi.classed("active", false);
    _pi.classed("active", false);
    _e.classed("active", true);

    numbers.setSubject(Numbers.E, function() {
      stageState.subjectValue = numbers.subjectValue();

      render(densityValue, stageState.displayMode, stageState.subjectValue);
    });
  });

  var updateDensitySlider = function(min, max, value) {
    _densitySlider.attr({ min: min, max: max, value: value });
    _densitySlider[0][0].value = value;
  }

  var updateColsSlider = function(min, max, value) {
    _colsSlider.attr({ min: min, max: max, value: value });
    _colsSlider[0][0].value = value;
  }

  var densityValueChanged =  function() {
    densityValue = +this.value;

    render(densityValue, stageState.displayMode, stageState.subjectValue);

    minCols = Math.max(Math.floor(widthRadiusToCols(minWidth, radius)), 1);
    maxCols = Math.floor(widthRadiusToCols(window.innerWidth, radius));
    updateColsSlider(minCols, maxCols, densityValue);
  };

  var columnsValueChanged = function() {
    densityValue = +this.value;

    var w = radiusDensityToWidth(radius,  densityValue);

    stageState.width = w;

    render(densityValue, stageState.displayMode, stageState.subjectValue);

    maxDensity = widthRadiusToCols(w, minRadius);
    updateDensitySlider(minDensity, maxDensity, densityValue);
  };

  //----------------------------------------------------------------------------

  // *sets radius
  render(densityValue, stageState.displayMode, stageState.subjectValue);

  maxCols = Math.floor(widthRadiusToCols(window.innerWidth, radius));
  minCols = densityValue;

  maxDensity = widthRadiusToCols(minWidth, minRadius);

  updateDensitySlider(minDensity, maxDensity, densityValue);
  updateColsSlider(minCols, maxCols, minCols);

  _densitySlider.on("change", densityValueChanged);
  _densitySlider.on("input", densityValueChanged);

  _colsSlider.on("change", columnsValueChanged);
  _colsSlider.on("input", columnsValueChanged);

  //----------------------------------------------------------------------------

  stageState.on("change:displayMode", function() {
    render(densityValue, stageState.displayMode, stageState.subjectValue);
  });

  var digits = d3.selectAll('#digits-radio input');
  var onDigitsChange = function() {
    var value = +this.value;

    numbers.setDigits(+this.value, function() {
      render(densityValue, stageState.displayMode, stageState.subjectValue);
    });
  };

  digits.on('click', function() {
    var value = +this.value;
    var warning = 'Displaying 100k digits or more, can be very resource ' +
      'intensive, even on a powerfull computer. Are you sure you would like ' +
      'to proceed?';

    if (value > 4 && !alreadyWarned) {
      if (confirm(warning)) {
        alreadyWarned = true;
      } else {
        d3.event.preventDefault();
        return false;
      }
    }
  });

  digits.on('change', onDigitsChange);
});
<commit_msg>Moves densityValue onto stage state<commit_after>var State = require('ampersand-state');
var View = require('ampersand-view');

var Numbers = require('./numbers.js');

//------------------------------------------------------------------------------

function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

//------------------------------------------------------------------------------

var colors = [
  "#ED2079",
  "#ED3E36",
  "#F76321",
  "#FFB73B",
  "#F5EC2B",
  "#8DC53A",
  "#37B347",
  "#00ABEE",
  "#283891",
  "#92278B"
];
var minWidth = 768;
var minRadius = 0.5;

var radius;
var gridSpacing = 25;
var padding;
var alreadyWarned = false;

var widthColsToRadius = function(width, cols) {
  // width: 2 * (gridSpacing + radius) + (cols - 1) * (2 * radius + gridSpacing)
	// w = 2 * (g + r) + (c - 1) * (2 * r + g)
  // w = c * g + 2 * c * r + g
  // (w - (c * g) - g) / (2 * c) = r
  return (width - (cols * gridSpacing) - gridSpacing) / (2 * cols);
}

var radiusDensityToWidth = function(radius, cols) {
  return cols * gridSpacing + 2 * cols * radius + gridSpacing;
}

var widthRadiusToCols = function(width, radius) {
  // w = c *(g + 2 * r) + g
  // (w - g) / (g + 2 * r) = c
  return (width - gridSpacing) / (gridSpacing + 2 * radius);
}

var render = function(cols, displayMode, subject) {
  var svg = d3.select("svg");
  var limit = subject.length;
  var width = svg.attr("width");
  var heigth;
  var strokeWidth;
  var circlesData = [];
  var linesData = [];
  var thisDigit;
  var digitSW, digitW, digitNW, digitN;
  var iSW, iW, iNW, iN;
  var nextDigit = 3;
  var thisX, nextX, thisY, nextY;
  var thisColor;
  var firstCol, lastCol, firstRow, lastRow;
  var datum;
  var i, xIndex;
  var xCoord = function(i) {
    return padding + (i % cols) * (gridSpacing + 2 * radius);
  }
  var yCoord = function(i) {
    return padding + Math.floor(i / cols) * (gridSpacing + 2 * radius);
  }
  var markEqualNeigbour = function(i) {
    if (typeof circlesData[i] !== 'undefined') {
      circlesData[i].hasEqualNeighbour = true;
    }
  };

  radius = widthColsToRadius(width, cols);
  strokeWidth = radius / 2.5;
  padding = radius + gridSpacing;

  height = (2 * padding) + (limit / cols) * (2 * radius) + ((limit / cols) - 1) * gridSpacing;
  svg.attr("height", height);

  for (i = 0; i < limit; i++) {
    thisDigit = nextDigit;
    nextDigit = parseInt(subject.charAt(i + 1), 10);
    thisColor = colors[thisDigit];
    thisX = xCoord(i);
    thisY = yCoord(i);
    nextX = xCoord(i + 1);
    nextY = yCoord(i + 1);
    xIndex = i % cols;
    firstCol = xIndex === 0;
    lastCol = xIndex === cols - 1;
    firstRow = i <= cols;
    lastRow = i >= (limit - cols - 1);

    datum = {
      outerColor: thisColor,
      innerColor: colors[nextDigit],
      x: thisX,
      y: thisY,
      r: radius,
      hasEqualNeighbour: false
    };

    if (displayMode > 0) {
      if (!firstCol && !lastRow) {
        iSW = i + cols - 1;
        digitSW = parseInt(subject.charAt(iSW), 10);

        if (thisDigit === digitSW) {
          markEqualNeigbour(iSW);
          datum.hasEqualNeighbour = true;
          swX = xCoord(iSW);
          swY = yCoord(iSW);

          linesData.push({
            x1: thisX, x2: swX,
            y1: thisY, y2: swY,
            color: thisColor,
            "stroke-width": datum.r
          })
        }
      }

      if (!firstRow) { // second row and onwards
        iN = i - cols;
        digitN = parseInt(subject.charAt(iN), 10);
        nX = xCoord(iN);
        nY = yCoord(iN);

        if (thisDigit === digitN) {
          markEqualNeigbour(iN);
          datum.hasEqualNeighbour = true;

          linesData.push({
            x1: thisX, x2: nX,
            y1: thisY, y2: nY,
            color: thisColor,
            "stroke-width": datum.r
          })
        }

        if (!firstCol) {
          iW = i - 1;
          iNW = i - cols - 1;
          digitW = parseInt(subject.charAt(iW), 10);
          digitNW = parseInt(subject.charAt(iNW), 10);

          if (thisDigit === digitW) {
            markEqualNeigbour(iW);
            datum.hasEqualNeighbour = true;
            wX = xCoord(iW);
            wY = yCoord(iW);

            linesData.push({
              x1: thisX, x2: wX,
              y1: thisY, y2: wY,
              color: thisColor,
              "stroke-width": datum.r
            })
          }

          if (thisDigit === digitNW) {
            markEqualNeigbour(iNW);
            datum.hasEqualNeighbour = true;

            nwX = xCoord(iNW);
            nwY = yCoord(iNW);

            linesData.push({
              x1: thisX, x2: nwX,
              y1: thisY, y2: nwY,
              color: thisColor,
              "stroke-width": datum.r
            })
          }
        }
      }

      if (!lastCol) {
        // Special case because we can't "mark" neighbours ahead of them being
        // inserted into circlesData, which is the case of digitSW === thisDigit

        digitNE = parseInt(subject.charAt(i - cols + 1), 10);

        if (thisDigit === digitNE) {
          if (typeof circlesData[i - cols + 1] !== 'undefined') {
            circlesData[i - cols + 1].hasEqualNeighbour = true;
          }
          datum.hasEqualNeighbour = true;
        }
      }
    }

    circlesData.push(datum)
  }

  // Remove neighbourless circles in third display mode
  if (displayMode === 2) {
    for (i = circlesData.length - 1; i >= 0; i -= 1) {
      if (!circlesData[i].hasEqualNeighbour) {
        circlesData.splice(i, 1);
      }
    }
  }

  // CIRCLES

  var circlesGroup = svg.select('g.circles');
  var circlesSelection = circlesGroup.selectAll('g').data(circlesData);
  var clipStrokeCircle = svg.select('#cstroke circle');
  clipStrokeCircle.attr({ r: radius });

  var groupAttr = {
    transform: function(d) {
      return 'translate(' + d.x + ',' + d.y + ')';
    }
  }

  var colorValve = function(open, colorCode) {
    if (displayMode === 2) {
      if (open) {
        return colorCode;
      } else {
        return '#000';
      }
    } else {
      return colorCode;
    }
  };

  var circleAttr = {
    r: function(d) { return d.r },
    "stroke-width": function(d) { return d.r / 1.4 },
    "stroke": function(d) {
      return d.outerColor;
      //return colorValve(d.hasEqualNeighbour, d.outerColor);
    },
    "clip-path": "url(#cstroke)",
    "fill": function(d) {
      return d.innerColor;
      //return colorValve(d.hasEqualNeighbour, d.innerColor);
    }

  }

  // Enter
  var groups = circlesSelection.enter().append('g');
  var circle = groups.append('circle');

  // Enter + Update
  circlesSelection.attr(groupAttr).select('circle').attr(circleAttr);

  circlesSelection.exit().remove();

  // LINES

  var linesGroup = svg.select('g.displayMode');
  var linesSelection = linesGroup.selectAll('line').data(linesData);

  var linesAttr = {
    x1: function(d) { return d.x1; },
    y1: function(d) { return d.y1; },
    x2: function(d) { return d.x2; },
    y2: function(d) { return d.y2; },
    "stroke-width": function(d) { return d["stroke-width"]; },
    "stroke": function(d) { return d.color; }
  };

  // Enter
  linesSelection.enter().append('line');

  // Enter + Update
  linesSelection.attr(linesAttr);

  linesSelection.exit().remove();
};

//------------------------------------------------------------------------------

var StageView = View.extend({
  template: '<svg id="stage"></svg>',

  autoRender: true,

  bindings: {
    "model.width": {
      type: "attribute",
      name: "width"
    }
  },

  events: {
    'click': function() {
      this.model.cycleDisplayMode();
    }
  },

  render: function() {
    if (!this.rendered) {
      View.prototype.render.apply(this, arguments);

      var svg = d3.select(this.el);

      svg.append('defs').append('clipPath').attr({id: 'cstroke'}).
        append('circle');
      svg.append('g').classed('displayMode', true);
      svg.append('g').classed('circles', true);
    }
  }
});

//------------------------------------------------------------------------------

ready(function() {
  var _densitySlider = d3.select("#density-slider");
  var _colsSlider = d3.select("#columns-slider");
  var minDensity = 1, maxDensity = 29;
  var minCols = 1, maxCols = 29, colsValue = 20;
  var numbers = new Numbers();

  var _phi = d3.select("#phi-link");
  var _pi = d3.select("#pi-link");
  var _e = d3.select("#e-link");

  var svg = d3.select("svg");

  //----------------------------------------------------------------------------

  var StageState = State.extend({
    props: {
      width: ['number', true, 768],
      displayMode: ['number', true, 0],
      subjectValue: ['string', true, numbers.subjectValue()],
      densityValue: ['number', true, 20]
    },

    cycleDisplayMode: function() {
      this.displayMode = (this.displayMode + 1) % 3;
    }
  });

  var stageState = new StageState();

  var stageView = new StageView({
    model: stageState,
    el: svg[0][0]
  });

  stageState.on('change', function() {
    stageView.render();
    render(stageState.densityValue, stageState.displayMode, stageState.subjectValue);
  })

  //----------------------------------------------------------------------------

  _phi.on("click", function() {
    d3.event.preventDefault();

    _phi.classed("active", true);
    _pi.classed("active", false);
    _e.classed("active", false);

    numbers.setSubject(Numbers.PHI, function() {
      stageState.subjectValue = numbers.subjectValue();
    });
  });

  _pi.on("click", function() {
    d3.event.preventDefault();

    _phi.classed("active", false);
    _pi.classed("active", true);
    _e.classed("active", false);

    numbers.setSubject(Numbers.PI, function() {
      stageState.subjectValue = numbers.subjectValue();
    });
  });

  _e.on("click", function() {
    d3.event.preventDefault();

    _phi.classed("active", false);
    _pi.classed("active", false);
    _e.classed("active", true);

    numbers.setSubject(Numbers.E, function() {
      stageState.subjectValue = numbers.subjectValue();
    });
  });

  var updateDensitySlider = function(min, max, value) {
    _densitySlider.attr({ min: min, max: max, value: value });
    _densitySlider[0][0].value = value;
  }

  var updateColsSlider = function(min, max, value) {
    _colsSlider.attr({ min: min, max: max, value: value });
    _colsSlider[0][0].value = value;
  }

  var densityValueChanged =  function() {
    stageState.densityValue = +this.value;

    minCols = Math.max(Math.floor(widthRadiusToCols(minWidth, radius)), 1);
    maxCols = Math.floor(widthRadiusToCols(window.innerWidth, radius));
    updateColsSlider(minCols, maxCols, stageState.densityValue);
  };

  var columnsValueChanged = function() {
    var v = +this.value;

    stageState.set({
      densityValue: v,
      width: radiusDensityToWidth(radius,  v)
    });

    maxDensity = widthRadiusToCols(stageState.width, minRadius);
    updateDensitySlider(minDensity, maxDensity, v);
  };

  //----------------------------------------------------------------------------

  // *sets radius
  render(stageState.densityValue, stageState.displayMode, stageState.subjectValue);

  maxCols = Math.floor(widthRadiusToCols(window.innerWidth, radius));
  minCols = stageState.densityValue;

  maxDensity = widthRadiusToCols(minWidth, minRadius);

  updateDensitySlider(minDensity, maxDensity, stageState.densityValue);
  updateColsSlider(minCols, maxCols, minCols);

  _densitySlider.on("change", densityValueChanged);
  _densitySlider.on("input", densityValueChanged);

  _colsSlider.on("change", columnsValueChanged);
  _colsSlider.on("input", columnsValueChanged);

  //----------------------------------------------------------------------------

  var digits = d3.selectAll('#digits-radio input');
  var onDigitsChange = function() {
    var value = +this.value;

    numbers.setDigits(+this.value, function() {
      render(stageState.densityValue, stageState.displayMode, stageState.subjectValue);
    });
  };

  digits.on('click', function() {
    var value = +this.value;
    var warning = 'Displaying 100k digits or more, can be very resource ' +
      'intensive, even on a powerfull computer. Are you sure you would like ' +
      'to proceed?';

    if (value > 4 && !alreadyWarned) {
      if (confirm(warning)) {
        alreadyWarned = true;
      } else {
        d3.event.preventDefault();
        return false;
      }
    }
  });

  digits.on('change', onDigitsChange);
});
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2018  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.6.0');
		this.setClientTag('node:18-10-10');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2018  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.6.0');
		this.setClientTag('node:18-10-11');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>/**
 * Copyright reelyActive 2016
 * We believe in an open Internet of Things
 */

var event = require('./event');
var time = require('./time');
var tiraid = require('./tiraid');

var DEFAULT_KEEP_ALIVE_MILLISECONDS = 5000;
var DEFAULT_DISAPPEARANCE_MILLISECONDS = 15000;

/**
 * EventQueue Class
 * Simple queue that converts tiraids to timely events.
 * @param {Object} options The options as a JSON object.
 * @constructor
 */
function EventQueue(options) {
  options = options || {};
  var self = this;

  self.keepAliveMilliseconds = options.keepAliveMilliseconds ||
                               DEFAULT_KEEP_ALIVE_MILLISECONDS;
  self.disappearanceMilliseconds = options.disappearanceMilliseconds ||
                                   DEFAULT_DISAPPEARANCE_MILLISECONDS;

  self.devices = {};

  function cleanup() {
    handleDisappearances(self);
  }
  setInterval(cleanup, self.disappearanceMilliseconds);
}

/**
 * Insert a tiraid into the queue, prompting an event in the callback if due.
 * @param {Object} givenTiraid The given tiraid.
 * @param {callback} callback Function to call on completion.
 */
EventQueue.prototype.insert = function(givenTiraid, callback) {
  var self = this;

  var givenEvent = tiraid.toFlattened(givenTiraid);

  // New device: insert and callback event
  if(!self.devices.hasOwnProperty(givenEvent.deviceId)) {
    givenEvent.event = event.APPEARANCE;
    self.devices[givenEvent.deviceId] = {
      nextKeepAliveTime: time.toFuture(givenEvent.time,
                                       self.keepAliveMilliseconds),
      event: givenEvent
    };
    return callback(givenEvent);
  }

  // Existing device: merge
  else {
    var device = self.devices[givenEvent.deviceId];
    givenEvent.event = event.KEEPALIVE;
    var mergedEvent = givenEvent; // TODO: merge associationIds
    device.event = mergedEvent;

    // Keep-alive threshold exceeded: callback event
    if(time.isEarlier(device.nextKeepAliveTime, mergedEvent.time)) {
      device.nextKeepAliveTime = time.toFuture(givenEvent.time,
                                               self.keepAliveMilliseconds);
      return callback(mergedEvent);
    }
    else {
      return callback(null);
    }
  }
};

/**
 * Handle disappearances by removing them from the queue to free memory.
 * @param {EventQueue} instance The EventQueue instance.
 */
function handleDisappearances(instance) {
  var cutoffTime = time.getFuture(-instance.disappearanceMilliseconds);

  for(device in instance.devices) {
    if(time.isEarlier(instance.devices[device].nextKeepAliveTime,
                      cutoffTime)) {
      delete instance.devices[device];
    }
  }
}

module.exports = EventQueue;
<commit_msg>Added merge of deviceAssociationIds<commit_after>/**
 * Copyright reelyActive 2016
 * We believe in an open Internet of Things
 */

var event = require('./event');
var time = require('./time');
var tiraid = require('./tiraid');

var DEFAULT_KEEP_ALIVE_MILLISECONDS = 5000;
var DEFAULT_DISAPPEARANCE_MILLISECONDS = 15000;

/**
 * EventQueue Class
 * Simple queue that converts tiraids to timely events.
 * @param {Object} options The options as a JSON object.
 * @constructor
 */
function EventQueue(options) {
  options = options || {};
  var self = this;

  self.keepAliveMilliseconds = options.keepAliveMilliseconds ||
                               DEFAULT_KEEP_ALIVE_MILLISECONDS;
  self.disappearanceMilliseconds = options.disappearanceMilliseconds ||
                                   DEFAULT_DISAPPEARANCE_MILLISECONDS;

  self.devices = {};

  function cleanup() {
    handleDisappearances(self);
  }
  setInterval(cleanup, self.disappearanceMilliseconds);
}

/**
 * Insert a tiraid into the queue, prompting an event in the callback if due.
 * @param {Object} givenTiraid The given tiraid.
 * @param {callback} callback Function to call on completion.
 */
EventQueue.prototype.insert = function(givenTiraid, callback) {
  var self = this;

  var givenEvent = tiraid.toFlattened(givenTiraid);

  // New device: insert and callback event
  if(!self.devices.hasOwnProperty(givenEvent.deviceId)) {
    givenEvent.event = event.APPEARANCE;
    self.devices[givenEvent.deviceId] = {
      nextKeepAliveTime: time.toFuture(givenEvent.time,
                                       self.keepAliveMilliseconds),
      event: givenEvent
    };
    return callback(givenEvent);
  }

  // Existing device: merge
  else {
    var device = self.devices[givenEvent.deviceId];
    givenEvent.event = event.KEEPALIVE;
    device.event = mergeEvents(givenEvent, device.event);

    // Keep-alive threshold exceeded: callback event
    if(time.isEarlier(device.nextKeepAliveTime, device.event.time)) {
      device.nextKeepAliveTime = time.toFuture(device.event.time,
                                               self.keepAliveMilliseconds);
      return callback(device.event);
    }
    else {
      return callback(null);
    }
  }
};

/**
 * Handle disappearances by removing them from the queue to free memory.
 * @param {EventQueue} instance The EventQueue instance.
 */
function handleDisappearances(instance) {
  var cutoffTime = time.getFuture(-instance.disappearanceMilliseconds);

  for(device in instance.devices) {
    if(time.isEarlier(instance.devices[device].nextKeepAliveTime,
                      cutoffTime)) {
      delete instance.devices[device];
    }
  }
}

/**
 * Merge two events, specifically the deviceAssociationIds.
 * @param {Object} currentEvent The current event to merge into.
 * @param {Object} previousEvent The previous event to merge from.
 */
function mergeEvents(currentEvent, previousEvent) {
  if(previousEvent.hasOwnProperty('deviceAssociationIds') &&
     previousEvent.deviceAssociationIds.length) {
    for(var cId = 0; cId < previousEvent.deviceAssociationIds.length; cId++) {
      var id = previousEvent.deviceAssociationIds[cId];
      if(currentEvent.deviceAssociationIds.indexOf(id) < 0) {
        if((id.length === 32) || (id.length === 40)) {   // 128-bit UUID and
          currentEvent.deviceAssociationIds.unshift(id); //   iBeacon have
        }                                                //   higher priority
        else {                                           // Other ids have
          currentEvent.deviceAssociationIds.push(id);    //   lower priority
        }
      }
    }
  }
  return currentEvent;
}

module.exports = EventQueue;
<|endoftext|>


<commit_before>if (typeof exports !== 'undefined') {
	exports = rewrite;
}

var fs = require('fs');
var MP4Box = require('../../dist/mp4box.all.js').MP4Box;

function rewrite(infile, outfile) {
	var outfile = fs.createWriteStream(outfile);

	var mp4box = new MP4Box();

	mp4box.onReady = function (info) {
	}

	var filePos = 0;
	var filereader = fs.createReadStream(infile);
	filereader.on('readable', function () {
		//console.log("Readable event");
		var chunk = filereader.read();
		//console.log("Read chunk", chunk);
		if (chunk) {
			var arrayBuffer = toArrayBuffer(chunk);
			//console.log("ArrayBuffer", arrayBuffer);
			arrayBuffer.fileStart = filePos;
			filePos += arrayBuffer.byteLength;
			mp4box.appendBuffer(arrayBuffer);
		} else {
			mp4box.flush();
			outfile.write(toBuffer(mp4box.writeFile()));
		}
	});
}

function toArrayBuffer(buffer) {
    var ab = new ArrayBuffer(buffer.length);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; ++i) {
        view[i] = buffer[i];
    }
    return ab;
}

function toBuffer(ab) {
    var buffer = new Buffer(ab.byteLength);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; ++i) {
        buffer[i] = view[i];
    }
    return buffer;
}

if (process.argv.length < 3) {
	console.log("usage: node rewrite.js <inputfilename> <outputfilename>");
	return;
} else {
	rewrite(process.argv[2], process.argv[3]);
}

<commit_msg>fix lint problem<commit_after>if (typeof exports !== 'undefined') {
	exports = rewrite;
}

var fs = require('fs');
var MP4Box = require('../../dist/mp4box.all.js').MP4Box;

function rewrite(infile, outfilename) {
	var outfile = fs.createWriteStream(outfilename);

	var mp4box = new MP4Box();

	mp4box.onReady = function (info) {
	}

	var filePos = 0;
	var filereader = fs.createReadStream(infile);
	filereader.on('readable', function () {
		//console.log("Readable event");
		var chunk = filereader.read();
		//console.log("Read chunk", chunk);
		if (chunk) {
			var arrayBuffer = toArrayBuffer(chunk);
			//console.log("ArrayBuffer", arrayBuffer);
			arrayBuffer.fileStart = filePos;
			filePos += arrayBuffer.byteLength;
			mp4box.appendBuffer(arrayBuffer);
		} else {
			mp4box.flush();
			outfile.write(toBuffer(mp4box.writeFile()));
		}
	});
}

function toArrayBuffer(buffer) {
    var ab = new ArrayBuffer(buffer.length);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; ++i) {
        view[i] = buffer[i];
    }
    return ab;
}

function toBuffer(ab) {
    var buffer = new Buffer(ab.byteLength);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; ++i) {
        buffer[i] = view[i];
    }
    return buffer;
}

if (process.argv.length < 3) {
	console.log("usage: node rewrite.js <inputfilename> <outputfilename>");
	return;
} else {
	rewrite(process.argv[2], process.argv[3]);
}

<|endoftext|>


<commit_before>var io, load, execon, join;

(function(global) {
    'use strict';

    if (typeof module !== 'undefined' && module.exports)
        module.exports  = new SperoProto();
    else
        global.spero    = new SperoProto();

    function SperoProto() {
        var Progress;

        function Spero(element, prefix, callback) {
            var el,
                type        = typeof element,
                isString    = type === 'string';

            if (!callback) {
                callback    = prefix;
                prefix      = '/spero';
            }

            if (isString)
                el  = document.querySelector(element);
            else
                el  = element;

            loadAll(prefix, function() {
                Progress = new ProgressProto(prefix);

                if (typeof callback === 'function')
                    callback();
            });
        }

        function loadAll(prefix, callback) {
            var scripts = [];

            if (!execon)
                scripts.push('/modules/execon/lib/execon.js');

            if (!scripts.length)
                loadFiles(prefix, callback);
            else
                loadScript(scripts.map(function(name) {
                    return prefix + name;
                }), function() {
                    loadFiles(prefix, callback);
                });
        }

        function loadFiles(prefix, callback) {
            var exec = execon;

            exec.series([
                function(callback) {
                    var scripts = [
                        'js/loadremote.js'
                    ];

                    if (!load)
                        scripts.push('modules/load/load.js');

                    if (!join)
                        scripts.push('join/join.js');

                    scripts = scripts.map(function(name) {
                        return prefix + name;
                    });

                    exec.if(!scripts.length, callback, function() {
                        loadScript(scripts, callback);
                    });
                },

                function() {
                    var load    = window.load,
                        css     = prefix + '/css/style.css';

                    load.json(prefix + '/modules.json', function(error, remote) {
                        if (error)
                            console.error(error);
                        else
                            load.series(remote.concat(css), callback);
                    });
                },

                function() {
                    callback();
                }
            ]);
        }

        function loadScript(srcs, callback) {
            var i       = srcs.length,
                func    = function() {
                    --i;

                    if (!i)
                        callback();
                };

            srcs.forEach(function(src) {
                var element = document.createElement('script');

                element.src = src;
                element.addEventListener('load', function load() {
                    func();
                    element.removeEventListener('load', load);
                });

                document.body.appendChild(element);
            });
        }

        function ProgressProto(room) {
            var socket;

            init(room);

            function init(room) {
                var href            = getHost(),
                    FIVE_SECONDS    = 5000;

                socket = io.connect(href + room, {
                    'max reconnection attempts' : Math.pow(2, 32),
                    'reconnection limit'        : FIVE_SECONDS
                });

                socket.on('err', function(data) {
                    var msg = data + '\n Continue?',
                        is = confirm(msg);

                    if (is)
                        socket.emit('continue');
                    else
                        socket.emit('abort');
                });

                socket.on('file', function(name) {
                    console.log(name);
                });

                socket.on('progress', function(percent) {
                    console.log(percent);
                });

                socket.on('end', function() {
                    console.log('copy ended up');
                });

                socket.on('connect', function() {
                    console.log('spero: connected\n');
                });

                socket.on('disconnect', function() {
                    console.error('spero: disconnected\n');
                });
            }

            this.pause       = function() {
                socket.emit('pause');
            };

            this.abort       = function() {
                socket.emit('abort');
            };

            function getHost() {
                var l       = location,
                    href    = l.origin || l.protocol + '//' + l.host;

                return href;
            }
        }

        return Spero;
    }

})(this);
<commit_msg>fix(spero) execon -> exec<commit_after>var io, load, exec, join;

(function(global) {
    'use strict';

    if (typeof module !== 'undefined' && module.exports)
        module.exports  = new SperoProto();
    else
        global.spero    = new SperoProto();

    function SperoProto() {
        var Progress;

        function Spero(element, prefix, callback) {
            var el,
                type        = typeof element,
                isString    = type === 'string';

            if (!callback) {
                callback    = prefix;
                prefix      = '/spero';
            }

            if (isString)
                el  = document.querySelector(element);
            else
                el  = element;

            loadAll(prefix, function() {
                Progress = new ProgressProto(prefix);

                if (typeof callback === 'function')
                    callback();
            });
        }

        function loadAll(prefix, callback) {
            var scripts = [];

            if (!exec)
                scripts.push('/modules/execon/lib/exec.js');

            if (!scripts.length)
                loadFiles(prefix, callback);
            else
                loadScript(scripts.map(function(name) {
                    return prefix + name;
                }), function() {
                    loadFiles(prefix, callback);
                });
        }

        function loadFiles(prefix, callback) {
            exec.series([
                function(callback) {
                    var scripts = [
                        '/js/loadremote.js'
                    ];

                    if (!load)
                        scripts.push('/modules/load/load.js');

                    if (!join)
                        scripts.push('/join/join.js');

                    scripts = scripts.map(function(name) {
                        return prefix + name;
                    });

                    exec.if(!scripts.length, callback, function() {
                        loadScript(scripts, callback);
                    });
                },

                function() {
                    var load    = window.load,
                        css     = prefix + '/css/style.css';

                    load.json(prefix + '/modules.json', function(error, remote) {
                        if (error)
                            console.error(error);
                        else
                            load.series(remote.concat(css), callback);
                    });
                },

                function() {
                    callback();
                }
            ]);
        }

        function loadScript(srcs, callback) {
            var i       = srcs.length,
                func    = function() {
                    --i;

                    if (!i)
                        callback();
                };

            srcs.forEach(function(src) {
                var element = document.createElement('script');

                element.src = src;
                element.addEventListener('load', function load() {
                    func();
                    element.removeEventListener('load', load);
                });

                document.body.appendChild(element);
            });
        }

        function ProgressProto(room) {
            var socket;

            init(room);

            function init(room) {
                var href            = getHost(),
                    FIVE_SECONDS    = 5000;

                socket = io.connect(href + room, {
                    'max reconnection attempts' : Math.pow(2, 32),
                    'reconnection limit'        : FIVE_SECONDS
                });

                socket.on('err', function(data) {
                    var msg = data + '\n Continue?',
                        is = confirm(msg);

                    if (is)
                        socket.emit('continue');
                    else
                        socket.emit('abort');
                });

                socket.on('file', function(name) {
                    console.log(name);
                });

                socket.on('progress', function(percent) {
                    console.log(percent);
                });

                socket.on('end', function() {
                    console.log('copy ended up');
                });

                socket.on('connect', function() {
                    console.log('spero: connected\n');
                });

                socket.on('disconnect', function() {
                    console.error('spero: disconnected\n');
                });
            }

            this.pause       = function() {
                socket.emit('pause');
            };

            this.abort       = function() {
                socket.emit('abort');
            };

            function getHost() {
                var l       = location,
                    href    = l.origin || l.protocol + '//' + l.host;

                return href;
            }
        }

        return Spero;
    }

})(this);
<|endoftext|>


<commit_before>// This code uses ES2015 syntax that requires at least Node.js v4.
// For Node.js ES2015 support details, reference http://node.green/

"use strict";
var request = require('request-promise');
var OpenT2T = require('opent2t').OpenT2T;

/**
* This translator class implements the "Hub" interface.
*/
class Translator {
    constructor(accessTokenInfo) {
        this._accessToken = accessTokenInfo;
        this._baseUrl = '';
        this._devicesPath = '/devices';
        this._updatePath = '/update';
        this._name = "SmartThings Hub"; // TODO: Can be pulled from OpenT2T global constants.
    }

    /**
     * Get the hub definition and devices
     */
    get(expand, payload) {
         return this.getPlatforms(expand, payload);
    }

    /**
     * Get the list of devices discovered through the hub.
     */
    getPlatforms(expand, payload) {
        if (payload != undefined) {
            return this._providerSchemaToPlatformSchema(payload, expand);
        }
        else {
            return this._hasValidEndpoint().then((isValid) => {
                if (isValid == false) return undefined;

                return this._makeRequest(this._devicesPath, 'GET')
                    .then((devices) => {
                        return this._providerSchemaToPlatformSchema(devices, expand);
                    });
            });
        }
    }

    /**
     * Get the name of the hub.  Ties to the n property from oic.core
     */
    getN() {
        return this._name;
    }

    /**
     * Gets device details (all fields)
     */
    getDeviceDetailsAsync(deviceId) {
        return this._hasValidEndpoint().then((isValid) => {
            if (isValid == false) return undefined;

            return this._makeRequest(this._devicesPath + '/' + deviceId, 'GET')
                .then((device) => {
                    return device;
                });
        });
    }

    /**
     * Puts device details (all fields) payload
     */
    putDeviceDetailsAsync(deviceId, putPayload) {
        return this._hasValidEndpoint().then((isValid) => {
            if (isValid == false) return undefined;

            var putPayloadString = JSON.stringify(putPayload);
            return this._makeRequest(this._updatePath + '/' + deviceId, 'PUT', putPayloadString)
                .then((result) => {
                    if (result === "succeed") {
                        return this.getDeviceDetailsAsync(deviceId);
                    }
                    return undefined;
                });
        });
    }

    /**
     * Subscribe to notifications for a platform.
     * This function is intended to be called by the platform translator for initial subscription,
     * and on the hub translator (this) for verification.
     */
    postSubscribe(subscriptionInfo) {
        return {
            expiration: -1, // Subscription has no expiration
            response: ""
        };
    }

    /**
     * Unsubscribe from a platform subscription.
     * This function is intended to be called by a platform translator
     */
    _unsubscribe(subscriptionInfo) {
        return {
            expiration: -1, // Subscription has no expiration
        };
    }

    /**
     * Translates an array of provider schemas into an opent2t/OCF representations
     */
    _providerSchemaToPlatformSchema(providerSchemas, expand) {
        var platformPromises = [];

        // Ensure that we have an array of provider schemas, even if a single object was given.
        var devices = [].concat(providerSchemas);

        devices.forEach((smartThingsDevice) => {
            // get the opent2t schema and translator for the SmartThings device
            var opent2tInfo = this._getOpent2tInfo(smartThingsDevice.deviceType);

            if (typeof opent2tInfo !== 'undefined') // we support the device
            {
                /// set the opent2t info for the SmartThings device
                var deviceInfo = {};
                deviceInfo.opent2t = {};
                deviceInfo.opent2t.controlId = smartThingsDevice.id;

                // Create a translator for this device and get the platform information, possibly expanded
                platformPromises.push(OpenT2T.createTranslatorAsync(opent2tInfo.translator, { 'deviceInfo': deviceInfo, 'hub': this })
                    .then((translator) => {
                        // Use get to translate the SmartThings formatted device that we already got in the previous request.
                        // We already have this data, so no need to make an unnecesary request over the wire.
                        return OpenT2T.invokeMethodAsync(translator, opent2tInfo.schema, 'get', [expand, smartThingsDevice])
                            .then((platformResponse) => {
                                return platformResponse;
                            });
                    }));
            }
        });

        return Promise.all(platformPromises)
                .then((platforms) => {
                    var toReturn = {};
                    toReturn.schema = "opent2t.p.hub";
                    toReturn.platforms = platforms;
                    return toReturn;
                });
    }

    /**
     * Given the hub specific device, returns the opent2t schema and translator
     */
    _getOpent2tInfo(deviceType) {
        switch (deviceType) {
            case "light":
                return {
                    "schema": 'org.opent2t.sample.lamp.superpopular',
                    "translator": 'opent2t-translator-com-smartthings-lightbulb'
                };
            case "switch":
                return {
                    "schema": 'org.opent2t.sample.binaryswitch.superpopular',
                    "translator": 'opent2t-translator-com-smartthings-binaryswitch'
                };
            case "thermostat":
                return {
                    "schema": 'org.opent2t.sample.thermostat.superpopular',
                    "translator": 'opent2t-translator-com-smartthings-thermostat'
                };
            default:
                return undefined;
        }
    }

    /**
     * Get the endpoint URI associated to the account
     */
    _getEndpoint() {
        var endpointUrl = 'https://graph.api.smartthings.com/api/smartapps/endpoints/' + this._accessToken.clientId + '?access_token=' + this._accessToken.accessToken;

        return this._makeRequest(endpointUrl, 'GET').then((responses) => {
            if (responses.length !== 0 && responses[0].uri !== undefined) {
                return Promise.resolve(responses[0].uri);
            }
            return Promise.resolve(undefined);
        });
    }

    _subscribe(deviceId) {
        return this._hasValidEndpoint().then((isValid) => {
            if (isValid == false) return undefined;

            var requestPath = '/subscription/' + deviceId;
            return this._makeRequest(requestPath, 'POST', '');
        });
    }

    _unsubscribe(deviceId) {
        return this._hasValidEndpoint().then((isValid) => {
            if (isValid == false) return undefined;

            var requestPath = '/subscription/' + deviceId;
            return this._makeRequest(requestPath, 'DELETE');
        });
    }

    /**
     * Get all OpenT2T-supported devices from the based (endpoint) URI
     */
    _hasValidEndpoint() {
        if (this._baseUrl === '') {
            return this._getEndpoint().then((endpointURI) => {
                if (endpointURI === undefined) return Promise.resolve(false);
                this._baseUrl = endpointURI;
                return Promise.resolve(true)
            });
        } else {
            return Promise.resolve(true);
        }
    }

    /**
     * Internal helper method which makes the actual request to the hue service
     */
    _makeRequest(path, method, content) {

        // build request URI
        var requestUri = this._baseUrl + path;

        // Set the headers
        var headers = {
            'Authorization': 'Bearer ' + this._accessToken.accessToken,
            'Accept': 'application/json'
        }

        if (content) {
            headers['Content-Type'] = 'application/json';
            headers['Content-length'] = content.length;
        }

        var options = {
            url: requestUri,
            method: method,
            headers: headers,
            followAllRedirects: true
        };

        if (content) {
            options.body = content;
        }

        // Start the async request
        return request(options)
            .then(function (body) {
                if (method === 'PUT' || method === 'DELETE') {
                    if (body.length === 0) return "succeed";
                    return "Unkown error";
                } else {
                    return JSON.parse(body);
                }
            })
            .catch(function (err) {
                console.log("Request failed to: " + options.method + " - " + options.url);
                console.log("Error            : " + err);
                throw err;
            });
    }
}

module.exports = Translator;<commit_msg>es-lint fix, unused vars in smartthings hub<commit_after>// This code uses ES2015 syntax that requires at least Node.js v4.
// For Node.js ES2015 support details, reference http://node.green/

"use strict";
var request = require('request-promise');
var OpenT2T = require('opent2t').OpenT2T;

/**
* This translator class implements the "Hub" interface.
*/
class Translator {
    constructor(accessTokenInfo) {
        this._accessToken = accessTokenInfo;
        this._baseUrl = '';
        this._devicesPath = '/devices';
        this._updatePath = '/update';
        this._name = "SmartThings Hub"; // TODO: Can be pulled from OpenT2T global constants.
    }

    /**
     * Get the hub definition and devices
     */
    get(expand, payload) {
         return this.getPlatforms(expand, payload);
    }

    /**
     * Get the list of devices discovered through the hub.
     */
    getPlatforms(expand, payload) {
        if (payload != undefined) {
            return this._providerSchemaToPlatformSchema(payload, expand);
        }
        else {
            return this._hasValidEndpoint().then((isValid) => {
                if (isValid == false) return undefined;

                return this._makeRequest(this._devicesPath, 'GET')
                    .then((devices) => {
                        return this._providerSchemaToPlatformSchema(devices, expand);
                    });
            });
        }
    }

    /**
     * Get the name of the hub.  Ties to the n property from oic.core
     */
    getN() {
        return this._name;
    }

    /**
     * Gets device details (all fields)
     */
    getDeviceDetailsAsync(deviceId) {
        return this._hasValidEndpoint().then((isValid) => {
            if (isValid == false) return undefined;

            return this._makeRequest(this._devicesPath + '/' + deviceId, 'GET')
                .then((device) => {
                    return device;
                });
        });
    }

    /**
     * Puts device details (all fields) payload
     */
    putDeviceDetailsAsync(deviceId, putPayload) {
        return this._hasValidEndpoint().then((isValid) => {
            if (isValid == false) return undefined;

            var putPayloadString = JSON.stringify(putPayload);
            return this._makeRequest(this._updatePath + '/' + deviceId, 'PUT', putPayloadString)
                .then((result) => {
                    if (result === "succeed") {
                        return this.getDeviceDetailsAsync(deviceId);
                    }
                    return undefined;
                });
        });
    }

    /* eslint no-unused-vars: "off" */

    /**
     * Subscribe to notifications for a platform.
     * This function is intended to be called by the platform translator for initial subscription,
     * and on the hub translator (this) for verification.
     */
    postSubscribe(subscriptionInfo) {
        return {
            expiration: -1, // Subscription has no expiration
            response: ""
        };
    }

    /**
     * Unsubscribe from a platform subscription.
     * This function is intended to be called by a platform translator
     */
    _unsubscribe(subscriptionInfo) {
        return {
            expiration: -1, // Subscription has no expiration
        };
    }

    /* eslint no-unused-vars: "warn" */

    /**
     * Translates an array of provider schemas into an opent2t/OCF representations
     */
    _providerSchemaToPlatformSchema(providerSchemas, expand) {
        var platformPromises = [];

        // Ensure that we have an array of provider schemas, even if a single object was given.
        var devices = [].concat(providerSchemas);

        devices.forEach((smartThingsDevice) => {
            // get the opent2t schema and translator for the SmartThings device
            var opent2tInfo = this._getOpent2tInfo(smartThingsDevice.deviceType);

            if (typeof opent2tInfo !== 'undefined') // we support the device
            {
                /// set the opent2t info for the SmartThings device
                var deviceInfo = {};
                deviceInfo.opent2t = {};
                deviceInfo.opent2t.controlId = smartThingsDevice.id;

                // Create a translator for this device and get the platform information, possibly expanded
                platformPromises.push(OpenT2T.createTranslatorAsync(opent2tInfo.translator, { 'deviceInfo': deviceInfo, 'hub': this })
                    .then((translator) => {
                        // Use get to translate the SmartThings formatted device that we already got in the previous request.
                        // We already have this data, so no need to make an unnecesary request over the wire.
                        return OpenT2T.invokeMethodAsync(translator, opent2tInfo.schema, 'get', [expand, smartThingsDevice])
                            .then((platformResponse) => {
                                return platformResponse;
                            });
                    }));
            }
        });

        return Promise.all(platformPromises)
                .then((platforms) => {
                    var toReturn = {};
                    toReturn.schema = "opent2t.p.hub";
                    toReturn.platforms = platforms;
                    return toReturn;
                });
    }

    /**
     * Given the hub specific device, returns the opent2t schema and translator
     */
    _getOpent2tInfo(deviceType) {
        switch (deviceType) {
            case "light":
                return {
                    "schema": 'org.opent2t.sample.lamp.superpopular',
                    "translator": 'opent2t-translator-com-smartthings-lightbulb'
                };
            case "switch":
                return {
                    "schema": 'org.opent2t.sample.binaryswitch.superpopular',
                    "translator": 'opent2t-translator-com-smartthings-binaryswitch'
                };
            case "thermostat":
                return {
                    "schema": 'org.opent2t.sample.thermostat.superpopular',
                    "translator": 'opent2t-translator-com-smartthings-thermostat'
                };
            default:
                return undefined;
        }
    }

    /**
     * Get the endpoint URI associated to the account
     */
    _getEndpoint() {
        var endpointUrl = 'https://graph.api.smartthings.com/api/smartapps/endpoints/' + this._accessToken.clientId + '?access_token=' + this._accessToken.accessToken;

        return this._makeRequest(endpointUrl, 'GET').then((responses) => {
            if (responses.length !== 0 && responses[0].uri !== undefined) {
                return Promise.resolve(responses[0].uri);
            }
            return Promise.resolve(undefined);
        });
    }

    _subscribe(deviceId) {
        return this._hasValidEndpoint().then((isValid) => {
            if (isValid == false) return undefined;

            var requestPath = '/subscription/' + deviceId;
            return this._makeRequest(requestPath, 'POST', '');
        });
    }

    _unsubscribe(deviceId) {
        return this._hasValidEndpoint().then((isValid) => {
            if (isValid == false) return undefined;

            var requestPath = '/subscription/' + deviceId;
            return this._makeRequest(requestPath, 'DELETE');
        });
    }

    /**
     * Get all OpenT2T-supported devices from the based (endpoint) URI
     */
    _hasValidEndpoint() {
        if (this._baseUrl === '') {
            return this._getEndpoint().then((endpointURI) => {
                if (endpointURI === undefined) return Promise.resolve(false);
                this._baseUrl = endpointURI;
                return Promise.resolve(true)
            });
        } else {
            return Promise.resolve(true);
        }
    }

    /**
     * Internal helper method which makes the actual request to the hue service
     */
    _makeRequest(path, method, content) {

        // build request URI
        var requestUri = this._baseUrl + path;

        // Set the headers
        var headers = {
            'Authorization': 'Bearer ' + this._accessToken.accessToken,
            'Accept': 'application/json'
        }

        if (content) {
            headers['Content-Type'] = 'application/json';
            headers['Content-length'] = content.length;
        }

        var options = {
            url: requestUri,
            method: method,
            headers: headers,
            followAllRedirects: true
        };

        if (content) {
            options.body = content;
        }

        // Start the async request
        return request(options)
            .then(function (body) {
                if (method === 'PUT' || method === 'DELETE') {
                    if (body.length === 0) return "succeed";
                    return "Unkown error";
                } else {
                    return JSON.parse(body);
                }
            })
            .catch(function (err) {
                console.log("Request failed to: " + options.method + " - " + options.url);
                console.log("Error            : " + err);
                throw err;
            });
    }
}

module.exports = Translator;<|endoftext|>


<commit_before>'use babel';

/** @jsx etch.dom */
/* @flow*/
import etch from 'etch';
import { Emitter, CompositeDisposable, Disposable } from 'atom';
import { normalizeString } from '../helpers';
import type { Message } from '../types';

export default class ResultView {
  properties: {
    messages: Array<Message>;
  }
  refs: any;
  element: any;
  panel: any;
  emitter: Emitter;
  disposables: CompositeDisposable;

  constructor(properties:Object) {
    this.properties = properties;
    this.emitter = new Emitter();
    this.disposables = new CompositeDisposable();
    etch.initialize(this);

    this.panel = atom.workspace.addBottomPanel({
      item: this.element,
      visible: true,
      priority: 500,
    });

    const clearHandler = async () => {
      await this.update({ messages: [] });
    };
    this.refs.clearButton.addEventListener('click', clearHandler);
    this.disposables.add(new Disposable(() => { this.refs.clearButton.removeEventListener('click', clearHandler); }));

    const closeHandler = () => {
      this.close();
    };
    this.refs.closeButton.addEventListener('click', closeHandler);
    this.disposables.add(new Disposable(() => { this.refs.closeButton.removeEventListener('click', closeHandler); }));
  }

  render() {
    return (

Tester Results

State

Duration

Title

Error

Location

          {/* {this.properties.messages.length === 0 &&

No tester messages

          } */}
          {this.properties.messages.map((message) => {
            console.log('message', message);
            return

                      {message.state || 'unknown'}

{message.duration || 0}ms

{message.title || ''}

                    <div class='tester-message-cell tester-message-error inline-block'
                      dangerouslySetInnerHTML={{ __html: `<em>foo</em>${normalizeString(message)}` }}/>

                      {message.filePath || ''}:{message.lineNumber.toString() || ''}

;
          })}

    );
  }

  update(newProperties:Object) {
    if (this.properties.messages !== newProperties.messages) {
      console.log('MESSAGES', newProperties.messages);
      this.properties.messages = newProperties.messages;
      return etch.update(this);
    }
    return Promise.resolve();
  }

  async destroy() {
    await etch.destroy(this);
  }

  close() {
    if (this.panel != null) {
      this.panel.destroy();
      this.panel = null;
    }
  }
}
<commit_msg>fix html<commit_after>'use babel';

/** @jsx etch.dom */
/* @flow*/
import etch from 'etch';
import { Emitter, CompositeDisposable, Disposable } from 'atom';
import { normalizeString } from '../helpers';
import type { Message } from '../types';

export default class ResultView {
  properties: {
    messages: Array<Message>;
  }
  refs: any;
  element: any;
  panel: any;
  emitter: Emitter;
  disposables: CompositeDisposable;

  constructor(properties:Object) {
    this.properties = properties;
    this.emitter = new Emitter();
    this.disposables = new CompositeDisposable();
    etch.initialize(this);

    this.panel = atom.workspace.addBottomPanel({
      item: this.element,
      visible: true,
      priority: 500,
    });

    const clearHandler = async () => {
      await this.update({ messages: [] });
    };
    this.refs.clearButton.addEventListener('click', clearHandler);
    this.disposables.add(new Disposable(() => { this.refs.clearButton.removeEventListener('click', clearHandler); }));

    const closeHandler = () => {
      this.close();
    };
    this.refs.closeButton.addEventListener('click', closeHandler);
    this.disposables.add(new Disposable(() => { this.refs.closeButton.removeEventListener('click', closeHandler); }));
  }

  render() {
    return (

Tester Results

State

Duration

Title

Error

Location

          {/* {this.properties.messages.length === 0 &&

No tester messages

          } */}
          {this.properties.messages.map((message) => {
            console.log('message', message);
            return

                      {message.state || 'unknown'}

{message.duration || 0}ms

{message.title || ''}

                      {message.filePath || ''}:{message.lineNumber.toString() || ''}

;
          })}

    );
  }

  update(newProperties:Object) {
    if (this.properties.messages !== newProperties.messages) {
      console.log('MESSAGES', newProperties.messages);
      this.properties.messages = newProperties.messages;
      return etch.update(this);
    }
    return Promise.resolve();
  }

  async destroy() {
    await etch.destroy(this);
  }

  close() {
    if (this.panel != null) {
      this.panel.destroy();
      this.panel = null;
    }
  }
}
<|endoftext|>


<commit_before>   var lang = {
    en: {
        EngButton: "English",
        FrButton: "Français",
        Title: "Interactive Forest Atlas of Cameroon",
        SubTitle: "A practical tool for understanding and working within Cameroon's forest sector",
        MapModule: "Explore the Map",
        DownloadModule: "Download the Data",
        AnalyzeModule: "Analyze the Data",
        TutorialModule: "View the Tutorials",
        AboutTitle: "About the Atlas",
        AboutText: "
The Interactive forest atlas of Cameroon is a living, dynamic forest monitoring system that provides unbiased and up-to-date information on the Cameroonian forest sector. Built on a geographic information system (GIS) platform, the Atlas aims to strengthen forest management and land use planning by bringing information on all major land use categories onto the same standardized platform.

The underlying forest atlas database is supported and kept up-to-date by the Ministry of Forestry and Wildlife (MINFOF) and the World Resources Institute (WRI), releasing new information as it becomes available via this mapping application. Other publications are released periodically and can be found in the download section.

The Interactive forest atlas of Cameroon overcomes a key data challenge by integrating forest management classes with forest cover extent and change data from Global Forest Watch’s near-real-time monitoring system. With a simple click, users can run complex analyses and explore the most up-to-date land cover changes within a variety of land allocations. To learn about the wide range of functionalities, visit the online tutorial.

Unless otherwise noted, Atlas data are licensed under a Creative Commons Attribution 4.0 International License. You are free to copy and redistribute the material in any medium or format, and to transform and build upon the material for any purpose, even commercially. You must give appropriate credit, provide a link to the license, and indicate if changes were made. When displaying and citing the data, use the appropriate credit as listed for the corresponding dataset in the download section.
",
        PartnerTitle: "A partnership between",
        SupporterTitle: "Supported by",
        Share: "Share the Atlas",
        TermsConditions: "Terms of Service",
        ContactUs: "Contact us"
    },

    fr: {
        EngButton: "English",
        FrButton: "Français",
        Title: "Atlas Forestier Interactif du Cameroun",
        SubTitle: "Un outil pratique pour comprendre et travailler dans le secteur forestier du Cameroun",
        MapModule: "Explorer le Plan",
        DownloadModule: "Télécharger les Données",
        AnalyzeModule: "Analyzer les Données",
        TutorialModule: "Regarder les Didacticiels",
        AboutTitle: "A Propos l'Atlas",
        AboutText: "
L’Atlas forestier interactif du Cameroun est un système de suivi forestier dynamique qui fournit des informations crédibles et actualisées sur le secteur forestier au Cameroun. Construit sur une plateforme SIG (Système d’Information Géographique), l’Atlas a pour but de renforcer la gestion des forêts et la planification de l’utilisation des terres en réunissant sur une même plateforme standardisée les informations sur toutes les principales catégories d’utilisation des terres.

La base de données sous-jacente de l’Atlas forestier est géré et mis à jour par le Ministère des Forêts et de la Faune (MINFOF) et le World Resources Institute (WRI), apportant de nouvelles informations à travers une application cartographique lorsque celles sont disponibles. D’autres publications sont produites périodiquement et peuvent être trouvés dans la section téléchargement.

L’Atlas Forestier Interactif répond à un défi en données clés en combinant les classes de gestion des forêts avec les données sur l’étendu et les changements de la couverture forestière provenant du système de suivi en temps quasi-réel Global Forest Watch. Par un simple clic, les utilisateurs peuvent effectuer des analyses complexes et explorer les changements de la couverture terrestre les plus récentes au sein d’une variété d’affectation des terres. Pour apprendre la large gamme de fonctionnalités, visiter le cours en ligne.

A moins que cela soit indiqué autrement, les données de l’Atlas forestier interactif sont sous licence Creative Commons Attribution 4.0 International License. Vous êtes libres de copier et redistribuer le matériel sous tous les formats, et de transformer et de mettre à profit le matériel à d’autres fins, y compris commerciales. Vous donnez donner du crédit, fournir le lien vers la licence et indiquer si des modifications ont été effectuées. Lorsque vous affichez ou citez les données, utiliser le crédit approprié tel que listé pour la série de données correspondante dans la section de téléchargement.
",
        PartnerTitle: "Un partenariat entre",
        SupporterTitle: "Supporté par",
        Share: "Partager l'Atlas",
        TermsConditions: "Conditions d’Utilisation",
        ContactUs: "Contactez nous"
    }
}

var flag = {
    href: "http://www.minfof.cm/",
    src: "img/flag/flag-cameroon.png",
}

var bcgImage = {
    src: "url(img/title-bg-1.jpg) no-repeat center center scroll"
}

var link = {
    en: {
        mapLink: "http://cmr.forest-atlas.org/map",
        downloadLink: "http://cmr-data.forest-atlas.org"
    },
    fr: {
        mapLink: "http://cmr.atlas-forestier.org/map/#v=atlas&l=fr&init=y",
        downloadLink: "http://cmr-data.atlas-forestier.org"
    }
}

var partners = {
    cmrMin: {
        href: "http://www.minfof.cm/",
        src: "img/logo/mifw-logo.png",
        alt: "MIFW Logo"
    },
    wri: {
        href: "http://www.wri.org/",
        src: "img/logo/wri-logo.png",
        alt: "WRI Logo"
    }
}

var sponsors = {
    gfw: {
        href: "http://globalforestwatch.org/",
        src: "img/logo/gfw-logo-bw.png",
        srcActive: "img/logo/gfw-logo.png",
        alt: "GFW"
    },
    usaid: {
        href: "http://www.usaid.gov/",
        src: "img/logo/usaid-logo-bw.png",
        srcActive: "img/logo/usaid-logo.png",
        alt: "USAID"
    },
    ukaid: {
        href: "https://www.gov.uk/government/organisations/department-for-international-development",
        src: "img/logo/ukaid-logo-bw.png",
        srcActive: "img/logo/ukaid-logo.png",
        alt: "UKAID"
    },
    nmce: {
        href: "https://www.regjeringen.no/en/dep/kld/id668/",
        src: "img/logo/nmce-logo-bw.png",
        srcActive: "img/logo/nmce-logo.png",
        alt: "Norway Ministry of the Environment"
    },
    hexagon: {
        href: "http://www.hexagongeospatial.com/",
        src: "img/logo/hexagon-logo-bw.png",
        srcActive: "img/logo/hexagon-logo.png",
        alt: "Hexagon Geospatial"
    },
    esri: {
        href: "http://www.esri.com/",
        src: "img/logo/esri-logo-bw.png",
        srcActive: "img/logo/esri-logo.png",
        alt: "Esri"
    }
}
<commit_msg>reslved conflict<commit_after>   var lang = {
    en: {
        EngButton: "English",
        FrButton: "Français",
        Title: "Interactive Forest Atlas of Cameroon",
        SubTitle: "A practical tool for understanding and working within Cameroon's forest sector",
        MapModule: "Explore the Map",
        DownloadModule: "Download the Data",
        AnalyzeModule: "Analyze the Data",
        TutorialModule: "View the Tutorials",
        AboutTitle: "About the Atlas",
        AboutText: "
The Interactive forest atlas of Cameroon is a living, dynamic forest monitoring system that provides unbiased and up-to-date information on the Cameroonian forest sector. Built on a geographic information system (GIS) platform, the Atlas aims to strengthen forest management and land use planning by bringing information on all major land use categories onto the same standardized platform.

The underlying forest atlas database is supported and kept up-to-date by the Ministry of Forestry and Wildlife (MINFOF) and the World Resources Institute (WRI), releasing new information as it becomes available via this mapping application. Other publications are released periodically and can be found in the download section.

The Interactive forest atlas of Cameroon overcomes a key data challenge by integrating forest management classes with forest cover extent and change data from Global Forest Watch’s near-real-time monitoring system. With a simple click, users can run complex analyses and explore the most up-to-date land cover changes within a variety of land allocations. To learn about the wide range of functionalities, visit the online tutorial.

Unless otherwise noted, Atlas data are licensed under a Creative Commons Attribution 4.0 International License. You are free to copy and redistribute the material in any medium or format, and to transform and build upon the material for any purpose, even commercially. You must give appropriate credit, provide a link to the license, and indicate if changes were made. When displaying and citing the data, use the appropriate credit as listed for the corresponding dataset in the download section.
",
        PartnerTitle: "A partnership between",
        SupporterTitle: "Supported by",
        Share: "Share the Atlas",
        TermsConditions: "Terms of Service",
        ContactUs: "Contact us"
    },

    fr: {
        EngButton: "English",
        FrButton: "Français",
        Title: "Atlas Forestier Interactif du Cameroun",
        SubTitle: "Un outil pratique pour comprendre et travailler dans le secteur forestier du Cameroun",
        MapModule: "Explorer le Plan",
        DownloadModule: "Télécharger les Données",
        AnalyzeModule: "Analyzer les Données",
        TutorialModule: "Regarder les Didacticiels",
        AboutTitle: "A Propos l'Atlas",
        AboutText: "
L’Atlas forestier interactif du Cameroun est un système de suivi forestier dynamique qui fournit des informations crédibles et actualisées sur le secteur forestier au Cameroun. Construit sur une plateforme SIG (Système d’Information Géographique), l’Atlas a pour but de renforcer la gestion des forêts et la planification de l’utilisation des terres en réunissant sur une même plateforme standardisée les informations sur toutes les principales catégories d’utilisation des terres.

La base de données sous-jacente de l’Atlas forestier est géré et mis à jour par le Ministère des Forêts et de la Faune (MINFOF) et le World Resources Institute (WRI), apportant de nouvelles informations à travers une application cartographique lorsque celles sont disponibles. D’autres publications sont produites périodiquement et peuvent être trouvés dans la section téléchargement.

L’Atlas Forestier Interactif répond à un défi en données clés en combinant les classes de gestion des forêts avec les données sur l’étendu et les changements de la couverture forestière provenant du système de suivi en temps quasi-réel Global Forest Watch. Par un simple clic, les utilisateurs peuvent effectuer des analyses complexes et explorer les changements de la couverture terrestre les plus récentes au sein d’une variété d’affectation des terres. Pour apprendre la large gamme de fonctionnalités, visiter le cours en ligne.

A moins que cela soit indiqué autrement, les données de l’Atlas forestier interactif sont sous licence Creative Commons Attribution 4.0 International License. Vous êtes libres de copier et redistribuer le matériel sous tous les formats, et de transformer et de mettre à profit le matériel à d’autres fins, y compris commerciales. Vous donnez donner du crédit, fournir le lien vers la licence et indiquer si des modifications ont été effectuées. Lorsque vous affichez ou citez les données, utiliser le crédit approprié tel que listé pour la série de données correspondante dans la section de téléchargement.
",
        PartnerTitle: "Un partenariat entre",
        SupporterTitle: "Supporté par",
        Share: "Partager l'Atlas",
        TermsConditions: "Conditions d’Utilisation",
        ContactUs: "Contactez nous"
    }
}

var flag = {
    href: "http://www.minfof.cm/",
    src: "img/flag/flag-cameroon.png",
}

var bcgImage = {
    src: "url(img/title-bg-1.jpg) no-repeat center center scroll"
}

var link = {
    en: {
        mapLink: "http://cmr.forest-atlas.org/map",
        downloadLink: "http://cmr-data.forest-atlas.org"
    },
    fr: {
        mapLink: "http://cmr.atlas-forestier.org/map/#v=atlas&l=fr&init=y",
        downloadLink: "http://cmr-data.atlas-forestier.org"
    }
}

var partners = {
    cmrMin: {
        href: "http://www.minfof.cm/",
        src: "img/logo/mifw-logo.png",
        alt: "MIFW Logo"
    },
    wri: {
        href: "http://www.wri.org/",
        src: "img/logo/wri-logo.png",
        alt: "WRI Logo"
    }
}

var sponsors = {
    gfw: {
        href: "http://globalforestwatch.org/",
        src: "img/logo/gfw-logo-bw.png",
        srcActive: "img/logo/gfw-logo.png",
        alt: "GFW"
    },
    usaid: {
        href: "http://www.usaid.gov/",
        src: "img/logo/usaid-logo-bw.png",
        srcActive: "img/logo/usaid-logo.png",
        alt: "USAID"
    },
    ukaid: {
        href: "https://www.gov.uk/government/organisations/department-for-international-development",
        src: "img/logo/ukaid-logo-bw.png",
        srcActive: "img/logo/ukaid-logo.png",
        alt: "UKAID"
    },
    nmce: {
        href: "https://www.regjeringen.no/en/dep/kld/id668/",
        src: "img/logo/nmce-logo-bw.png",
        srcActive: "img/logo/nmce-logo.png",
        alt: "Norway Ministry of the Environment"
    },
    hexagon: {
        href: "http://www.hexagongeospatial.com/",
        src: "img/logo/hexagon-logo-bw.png",
        srcActive: "img/logo/hexagon-logo.png",
        alt: "Hexagon Geospatial"
    },
    esri: {
        href: "http://www.esri.com/",
        src: "img/logo/esri-logo-bw.png",
        srcActive: "img/logo/esri-logo.png",
        alt: "Esri"
    }
}
<|endoftext|>