<commit_before>'use strict';

var leapHands = require('./leap-hands');
var objects = require('./objects');
var skybox = require('./skybox');
var vr = require('./vr');
var loading = require('./loading');

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

var viewport = document.getElementById('viewport');

var scene = new THREE.Scene();

function main(vrEnabled, vrHMD, vrHMDSensor) {
  var renderer = new THREE.WebGLRenderer();
  renderer.shadowMapEnabled = true;
  // to antialias the shadow
  renderer.shadowMapType = THREE.PCFSoftShadowMap;
  renderer.setSize(window.innerWidth, window.innerHeight);

  viewport.appendChild(renderer.domElement);

  if (vrHMD) {
    var vrrenderer = new THREE.VRRenderer(renderer, vrHMD);
  }

  // Camera control by mouse
  var controls = new THREE.OrbitControls(camera, renderer.domElement);

  // Needed to show textures
  var ambientLight = new THREE.AmbientLight(0x404040);
  scene.add(ambientLight);

  var spotLight	= new THREE.SpotLight( 0xFFFFFF );
  spotLight.target.position.set( 0, 0, -300 );
  spotLight.castShadow = true;
  spotLight.position.z	= 1000;
  spotLight.position.x	= 500;
  scene.add( spotLight );

  var sun = objects.sun;
  sun.position.copy(spotLight.position);
  scene.add(sun);

  scene.add(skybox);

  addObjectsToScene({
    onComplete() {
      scene.add(leapHands.right.group);
      scene.add(leapHands.left.group);

      scene.leapHandsAdded = true;

      leapHands.setUpHandEventHandlers();
    }
  });
  render();

  // set up click handling

  var projector = new THREE.Projector();
  var mouseVector = new THREE.Vector3();

  function onMouseDown(e) {
    var vector = new THREE.Vector3();
    var raycaster = new THREE.Raycaster();

    vector.set( (event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, 0.5);
    vector.unproject( camera );
    raycaster.set( camera.position, vector.sub( camera.position ).normalize() )
    var intersects = raycaster.intersectObjects(objects.objects);

    manualDisplayToggle(intersects[0]);
  }

  window.addEventListener( 'mousedown', onMouseDown, false );

  function render() {
    updateObjects();

    determineIfObjectsAreHeld();

    if (vrEnabled) {
      var state = vrHMDSensor.getState();
      camera.quaternion.set(
        state.orientation.x,
        state.orientation.y,
        state.orientation.z,
        state.orientation.w
      );
      vrrenderer.render(scene, camera);
    }
    else {
      renderer.render(scene, camera);
    }
    requestAnimationFrame(render);
  }
}

loading(function() {
  vr.init(main);
});

var manualDisplaySlots = {
  left: null,
  right: null
};

var manualDisplaySlotPositions = {
  left: new THREE.Vector3(-100, 0, 200),
  right: new THREE.Vector3(100, 0, 0)
};

function manualDisplayToggle(object) {
  if (manualDisplaySlots.left === object) {
    object.moveToHomePosition({duration: 300});
    manualDisplaySlots.left = null;
    object.animateOutInfoView();
  }
  else if (!manualDisplaySlots.left) {
    object.moveToPosition({destination: manualDisplaySlotPositions.left, duration: 300}, () => object.animateInInfoView());
    manualDisplaySlots.left = object;
  }
}

function addObjectsToScene(options) {
  objects.objects.forEach((obj, i) => {
    obj.attachToScene(scene);

    // If last object, trigger callback
    if (i === objects.objects.length - 1) {
      options.onComplete();
    }
  });
}

function updateObjects() {
  var options = {
    objectInLeftHand: leapHands.left.getHeldObject(),
    objectInRightHand: leapHands.right.getHeldObject(),
  };

  objects.objects.forEach((obj) => {
    obj.update(options);
  });
}

function determineIfObjectsAreHeld() {
  if (scene.leapHandsAdded) {
    objects.objects.forEach(determineIfObjectIsHeld);
  }
}

var throwVelocityThreshold = -850;
var waitBeforeHoldingObjectAgain = 1000;
var timeWhenLastThrownObject = Date.now();

function determineIfObjectIsHeld(object) {
  leapHands.hands.forEach((hand) => {
    if (!hand.isVisible) return;

    var velocity = hand.velocity;

    // Hand is holding this object
    if (hand.isHoldingThisObject(object)) {
      if (velocity && velocity[2] <= throwVelocityThreshold) {
        object.moveToHomePosition({duration: 500});
        object.animateOutInfoView();

        hand.stopHoldingObject();
        timeWhenLastThrownObject = Date.now();
      } else {
        object.positionRelativeToHand(hand);
        object.determineIfShowInfoView();
      }
    }

    // Hand is holding nothing, neither hand is holding object, so check if object is close enough to be held
    else if (!hand.isHoldingAnyObject() && !leapHands.isEitherHandHoldingObject(object)) {
      if (hand.isInRangeOf(object)) {

        // If not enough time has elapsed since last held an object, don't hold
        if (Date.now() - timeWhenLastThrownObject < waitBeforeHoldingObjectAgain) {
          return;
        }

        hand.holdObject(object);
      }
    }

  });
}
<commit_msg>clean up raycast code<commit_after>'use strict';

var leapHands = require('./leap-hands');
var objects = require('./objects');
var skybox = require('./skybox');
var vr = require('./vr');
var loading = require('./loading');

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

var viewport = document.getElementById('viewport');

var scene = new THREE.Scene();

function main(vrEnabled, vrHMD, vrHMDSensor) {
  var renderer = new THREE.WebGLRenderer();
  renderer.shadowMapEnabled = true;
  // to antialias the shadow
  renderer.shadowMapType = THREE.PCFSoftShadowMap;
  renderer.setSize(window.innerWidth, window.innerHeight);

  viewport.appendChild(renderer.domElement);

  if (vrHMD) {
    var vrrenderer = new THREE.VRRenderer(renderer, vrHMD);
  }

  // Camera control by mouse
  var controls = new THREE.OrbitControls(camera, renderer.domElement);

  // Needed to show textures
  var ambientLight = new THREE.AmbientLight(0x404040);
  scene.add(ambientLight);

  var spotLight	= new THREE.SpotLight( 0xFFFFFF );
  spotLight.target.position.set( 0, 0, -300 );
  spotLight.castShadow = true;
  spotLight.position.z	= 1000;
  spotLight.position.x	= 500;
  scene.add( spotLight );

  var sun = objects.sun;
  sun.position.copy(spotLight.position);
  scene.add(sun);

  scene.add(skybox);

  addObjectsToScene({
    onComplete() {
      scene.add(leapHands.right.group);
      scene.add(leapHands.left.group);

      scene.leapHandsAdded = true;

      leapHands.setUpHandEventHandlers();
    }
  });
  render();

  // set up click handling
  function onMouseDown(event) {
    var vector = new THREE.Vector3();
    var raycaster = new THREE.Raycaster();

    vector.set( (event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, 0.5);
    vector.unproject(camera);
    raycaster.set(camera.position, vector.sub( camera.position ).normalize());
    var intersects = raycaster.intersectObjects(objects.objects);

    manualDisplayToggle(intersects[0]);
  }

  window.addEventListener( 'mousedown', onMouseDown, false );

  function render() {
    updateObjects();

    determineIfObjectsAreHeld();

    if (vrEnabled) {
      var state = vrHMDSensor.getState();
      camera.quaternion.set(
        state.orientation.x,
        state.orientation.y,
        state.orientation.z,
        state.orientation.w
      );
      vrrenderer.render(scene, camera);
    }
    else {
      renderer.render(scene, camera);
    }
    requestAnimationFrame(render);
  }
}

loading(function() {
  vr.init(main);
});

var manualDisplaySlots = {
  left: null,
  right: null
};

var manualDisplaySlotPositions = {
  left: new THREE.Vector3(-100, 0, 200),
  right: new THREE.Vector3(100, 0, 0)
};

function manualDisplayToggle(object) {
  if (manualDisplaySlots.left === object) {
    object.moveToHomePosition({duration: 300});
    manualDisplaySlots.left = null;
    object.animateOutInfoView();
  }
  else if (!manualDisplaySlots.left) {
    object.moveToPosition({destination: manualDisplaySlotPositions.left, duration: 300}, () => object.animateInInfoView());
    manualDisplaySlots.left = object;
  }
}

function addObjectsToScene(options) {
  objects.objects.forEach((obj, i) => {
    obj.attachToScene(scene);

    // If last object, trigger callback
    if (i === objects.objects.length - 1) {
      options.onComplete();
    }
  });
}

function updateObjects() {
  var options = {
    objectInLeftHand: leapHands.left.getHeldObject(),
    objectInRightHand: leapHands.right.getHeldObject(),
  };

  objects.objects.forEach((obj) => {
    obj.update(options);
  });
}

function determineIfObjectsAreHeld() {
  if (scene.leapHandsAdded) {
    objects.objects.forEach(determineIfObjectIsHeld);
  }
}

var throwVelocityThreshold = -850;
var waitBeforeHoldingObjectAgain = 1000;
var timeWhenLastThrownObject = Date.now();

function determineIfObjectIsHeld(object) {
  leapHands.hands.forEach((hand) => {
    if (!hand.isVisible) return;

    var velocity = hand.velocity;

    // Hand is holding this object
    if (hand.isHoldingThisObject(object)) {
      if (velocity && velocity[2] <= throwVelocityThreshold) {
        object.moveToHomePosition({duration: 500});
        object.animateOutInfoView();

        hand.stopHoldingObject();
        timeWhenLastThrownObject = Date.now();
      } else {
        object.positionRelativeToHand(hand);
        object.determineIfShowInfoView();
      }
    }

    // Hand is holding nothing, neither hand is holding object, so check if object is close enough to be held
    else if (!hand.isHoldingAnyObject() && !leapHands.isEitherHandHoldingObject(object)) {
      if (hand.isInRangeOf(object)) {

        // If not enough time has elapsed since last held an object, don't hold
        if (Date.now() - timeWhenLastThrownObject < waitBeforeHoldingObjectAgain) {
          return;
        }

        hand.holdObject(object);
      }
    }

  });
}
<|endoftext|>


<commit_before>'use strict';

const ipc = require('electron').ipcRenderer;
var map = require('./js/map');
var d3 = require('d3');
var topojson = require('topojson');

var map;
var svg;
var path;
var layer1;
var layer2;
var idx;

var color = d3.scale.log()
  .range(["blue", "red"]);

var scale = 200;

var width = 1200,
  height = 800,
  rotate = [0, 0],
  visible = false;

var projection = d3.geo.equirectangular()
  .precision(.1);

var drag = d3.behavior.drag()
  .origin(function() {
    return {
      x: rotate[0],
      y: -rotate[1]
    };
  })
  .on("drag", dragged);

var zoom = d3.behavior.zoom()
  .scaleExtent([200, 10000])
  .on("zoom", zoomed);

function dragged() {
  rotate[0] = d3.event.x;
  rotate[1] = -d3.event.y;
  redrawMap();
}

function zoomed() {
  if (d3.event.sourceEvent.type == "wheel") {
    scale = d3.event.scale;
    redrawMap();
  }
}

function clearVoronoi() {
  d3.selectAll(".voronoi").remove();
  visible = false;
}

function redrawVoronoi() {
  idx = 0;

  d3.geom.voronoi(map.map(projection)).forEach(function(v) {
    layer1.append("path")
      .datum(v)
      .attr("fill", function(d) {
        return color(map[idx++][2]);
      })
      .attr("class", "voronoi")
      .attr("d", function(d) {
        return "M" + d.join("L") + "Z";
      });
  });
}

function redrawMap() {
  clearVoronoi();

  var mapElement = document.getElementById("map");
  width = mapElement.clientWidth;
  height = mapElement.clientHeight;

  projection.translate([width / 2, height / 2])
    .scale(scale)
    .rotate(rotate);

  path = d3.geo.path().projection(projection);
  d3.selectAll("path").attr("d", path);
}

function onResize() {
  redrawMap();
}

function onToggle() {
  if (visible) {
    d3.selectAll(".voronoi").remove();
    visible = false;
  } else {
    redrawVoronoi();
    visible = true;
  }
}

function onFullscreen() {
  ipc.send("fullscreen");
}

function onReload() {
  ipc.send("reload");
}

function onDevTools() {
  ipc.send("dev-tools");
}

function onEquirectangular() {
  projection = d3.geo.equirectangular()
    .precision(.1);
  redrawMap();
}

function onOrthographic() {
  projection = d3.geo.orthographic()
    .clipAngle(90)
    .precision(.1);
  redrawMap();
}

function onInit() {
  svg = d3.select("#mapBox").append("svg")
    .attr("id", "map")
    .attr("width", "100%")
    .attr("height", "100%")
    .call(drag)
    .call(zoom);

  layer1 = svg.append("g");
  layer2 = svg.append("g");

  d3.json("world.json", function(error, data) {
    if (error) throw error;

    layer2.append("path")
      .datum(topojson.feature(data, data.objects.land))
      .attr("class", "land")
      .attr("fill-opacity", "0.0")
      .attr("d", path);
  });

  d3.tsv("map.tsv", function(error, data) {
    if (error) throw error;

    map = data;
  });

}
<commit_msg>Voronoi border fix<commit_after>'use strict';

const ipc = require('electron').ipcRenderer;
var map = require('./js/map');
var d3 = require('d3');
var topojson = require('topojson');

var map;
var svg;
var path;
var layer1;
var layer2;
var idx;

var color = d3.scale.log()
  .range(["blue", "red"]);

var scale = 200;

var width = 1200,
  height = 800,
  rotate = [0, 0],
  visible = false;

var projection = d3.geo.equirectangular()
  .precision(.1);

var drag = d3.behavior.drag()
  .origin(function() {
    return {
      x: rotate[0],
      y: -rotate[1]
    };
  })
  .on("drag", dragged);

var zoom = d3.behavior.zoom()
  .scaleExtent([200, 10000])
  .on("zoom", zoomed);

function dragged() {
  rotate[0] = d3.event.x;
  rotate[1] = -d3.event.y;
  redrawMap();
}

function zoomed() {
  if (d3.event.sourceEvent.type == "wheel") {
    scale = d3.event.scale;
    redrawMap();
  }
}

function clearVoronoi() {
  d3.selectAll(".voronoi").remove();
  visible = false;
}

function redrawVoronoi() {
  idx = 0;

  d3.geom.voronoi(map.map(projection)).forEach(function(v) {
    layer1.append("path")
      .datum(v)
      .attr("fill", function(d) {
        return color(map[idx][2]);
      })
      .attr("stroke", function(d) {
        return color(map[idx++][2]);
      })
      .attr("stroke-width", "1")
      .attr("class", "voronoi")
      .attr("d", function(d) {
        return "M" + d.join("L") + "Z";
      });
  });
}

function redrawMap() {
  clearVoronoi();

  var mapElement = document.getElementById("map");
  width = mapElement.clientWidth;
  height = mapElement.clientHeight;

  projection.translate([width / 2, height / 2])
    .scale(scale)
    .rotate(rotate);

  path = d3.geo.path().projection(projection);
  d3.selectAll("path").attr("d", path);
}

function onResize() {
  redrawMap();
}

function onToggle() {
  if (visible) {
    d3.selectAll(".voronoi").remove();
    visible = false;
  } else {
    redrawVoronoi();
    visible = true;
  }
}

function onFullscreen() {
  ipc.send("fullscreen");
}

function onReload() {
  ipc.send("reload");
}

function onDevTools() {
  ipc.send("dev-tools");
}

function onEquirectangular() {
  projection = d3.geo.equirectangular()
    .precision(.1);
  redrawMap();
}

function onOrthographic() {
  projection = d3.geo.orthographic()
    .clipAngle(90)
    .precision(.1);
  redrawMap();
}

function onInit() {
  svg = d3.select("#mapBox").append("svg")
    .attr("id", "map")
    .attr("width", "100%")
    .attr("height", "100%")
    .call(drag)
    .call(zoom);

  layer1 = svg.append("g");
  layer2 = svg.append("g");

  d3.json("world.json", function(error, data) {
    if (error) throw error;

    layer2.append("path")
      .datum(topojson.feature(data, data.objects.land))
      .attr("class", "land")
      .attr("fill-opacity", "0.0")
      .attr("d", path);
  });

  d3.tsv("map.tsv", function(error, data) {
    if (error) throw error;

    map = data;
  });

}
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */
class Modal {
  /* eslint-enable no-unused-vars */
  constructor(contents) {
    this.contents = contents;
    this.open = false;

    this.modalContainer = document.getElementById('modal-container');
    // Initialize if initialization hasn't taken place
    if (this.modalContainer === null) {
      Modal.init();
      this.modalContainer = document.getElementById('modal-container');
    }

    this.elem = document.createElement('div');
    this.elem.className = 'modal';
    this.elem.innerHTML = this.contents;
    this.modalContainer.appendChild(this.elem);

    const closeButton = document.createElement('a');
    closeButton.setAttribute('href', '#');
    closeButton.className = 'close-button';
    closeButton.innerText = '\uf12a';
    this.elem.appendChild(closeButton);

    closeButton.addEventListener('click', this.close);
  }

  static init() {
    if (!document.getElementById('modal-container')) {
      this.modalContainer = document.createElement('div');
      this.modalContainer.setAttribute('id', 'modal-container');
      document.body.appendChild(this.modalContainer);
    }
  }

  present() {
    document.body.className = 'modal-open';
    this.open = true;
  }

  close() {
    document.body.className = '';
    this.open = false;
  }

  static destroy() {
    document.body.removeChild(this.modalContainer);
  }
}
<commit_msg>Allow closing modal by clicking background<commit_after>/* eslint-disable no-unused-vars */
class Modal {
  /* eslint-enable no-unused-vars */
  constructor(contents) {
    this.contents = contents;
    this.open = false;

    this.modalContainer = document.getElementById('modal-container');
    // Initialize if initialization hasn't taken place
    if (this.modalContainer === null) {
      Modal.init();
      this.modalContainer = document.getElementById('modal-container');
    }

    this.elem = document.createElement('div');
    this.elem.className = 'modal';
    this.elem.innerHTML = this.contents;
    this.modalContainer.appendChild(this.elem);

    const closeButton = document.createElement('a');
    closeButton.setAttribute('href', '#');
    closeButton.className = 'close-button';
    closeButton.innerText = '\uf12a';
    this.elem.appendChild(closeButton);

    closeButton.addEventListener('click', this.close);
    this.modalContainer.addEventListener('click', (e) => {
      if (e.target === this.modalContainer) this.close();
    });
  }

  static init() {
    if (!document.getElementById('modal-container')) {
      this.modalContainer = document.createElement('div');
      this.modalContainer.setAttribute('id', 'modal-container');
      document.body.appendChild(this.modalContainer);
    }
  }

  present() {
    document.body.className = 'modal-open';
    this.open = true;
  }

  close() {
    document.body.className = '';
    this.open = false;
  }

  static destroy() {
    document.body.removeChild(this.modalContainer);
  }
}
<|endoftext|>


<commit_before>key('w', function() {
	ngApply('pilotController', function($scope) {
		$scope.move('forward');
	});
});

key('s', function() {
	ngApply('pilotController', function($scope) {
		$scope.move('backward');
	});
});

key('a', function() {
	ngApply('pilotController', function($scope) {
		$scope.move('left');
	});
});

key('d', function() {
	ngApply('pilotController', function($scope) {
		$scope.move('right');
	});
});

key('q', function() {
	ngApply('pilotController', function($scope) {
		$scope.rotate('antiClockwise');
	});
});

key('e', function() {
	ngApply('pilotController', function($scope) {
		$scope.rotate('clockwise');
	});
});

key('space', function() {
	ngApply('pilotController', function($scope) {
		$scope.action('land');
	});
});

key('p', function() {
	ngApply('pilotController', function($scope) {
		$scope.altitude('up');
	});
});

key('l', function() {
	ngApply('pilotController', function($scope) {
		$scope.altitude('down');
	});
});

key(['backspace', 'r'], function() {
	ngApply('pilotController', function($scope) {
		$scope.action('reset');
	});
});

key('escape', function() {
	ngApply('pilotController', function($scope) {
		$scope.action('stop');
	});
});
<commit_msg>BUGFIX: Mysterious error where Angular would object to keymaster being passed an array<commit_after>key('w', function() {
	ngApply('pilotController', function($scope) {
		$scope.move('forward');
	});
});

key('s', function() {
	ngApply('pilotController', function($scope) {
		$scope.move('backward');
	});
});

key('a', function() {
	ngApply('pilotController', function($scope) {
		$scope.move('left');
	});
});

key('d', function() {
	ngApply('pilotController', function($scope) {
		$scope.move('right');
	});
});

key('q', function() {
	ngApply('pilotController', function($scope) {
		$scope.rotate('antiClockwise');
	});
});

key('e', function() {
	ngApply('pilotController', function($scope) {
		$scope.rotate('clockwise');
	});
});

key('space', function() {
	ngApply('pilotController', function($scope) {
		$scope.action('land');
	});
});

key('p', function() {
	ngApply('pilotController', function($scope) {
		$scope.altitude('up');
	});
});

key('l', function() {
	ngApply('pilotController', function($scope) {
		$scope.altitude('down');
	});
});

key('backspace', function() {
	ngApply('pilotController', function($scope) {
		$scope.action('reset');
	});
});

key('r', function() {
	ngApply('pilotController', function($scope) {
		$scope.action('reset');
	});
});

key('escape', function() {
	ngApply('pilotController', function($scope) {
		$scope.action('stop');
	});
});
<|endoftext|>


<commit_before>const
  fs = require('fs'),
  gc = require("./gcode"),
  Arduino = require('./arduino.js'),
  config  = require('./config.json')
;

function getMiliSeg ()  {
  return config.motor.xy.steps * config.motor.xy.time / config.motor.xy.advance ;
}

var File = {
  gcode   : [],
  dir     : '' ,
  name    : 'Sin Archivo',
  lines   : 0 ,
  travel    : 0 ,
  segTotal  : 0
}

function setFile ( dirfile ) {
  if (!dirfile) return {};
  File.dir = dirfile[0];
  File.gcode = gc(fs.readFileSync(dirfile[0]).toString());
  File.name = dirfile[0].split('/')[dirfile[0].split('/').length-1];
  File.lines = File.gcode.length;
  File.travel = File.gcode[File.gcode.length-1].travel;
  File.segTotal = File.gcode[File.gcode.length-1].travel * getMiliSeg();
  return File;
  //cb(File) ;
}

function Line (code) {
 return {
    nro : '',
    type : 'none',
    ejes : [],
    steps : [],
    travel : '',
    code
  }
}
Line.prototype._clone = (code) => {
  return {
    code : Line(code),
    nro : this.nro,
    type : this.type,
    ejes : this.ejes,
    steps : this.steps,
    travel : this.travel
  }
}

function sendCommand ( type , code ){
  console.log(`sendCommand, type: ${type}, code: ${code}`);
  if( Arduino.port.comName !== '' ){
    switch (type) {
      case 'steps':
        var line = Line(`Comando manual ${type}: ${code}`);
        line.steps = code.split(',');
        line.ejes = [
          line.steps[0] * config.motor.xy.advance / config.motor.xy.steps,
          line.steps[1] * config.motor.xy.advance / config.motor.xy.steps,
          line.steps[2] * config.motor.z.advance  / config.motor.z.steps
        ];
        realSendCommand( code , line );
        break;
      case 'mm':
        var line = Line(`Comando manual ${type}: ${code}`);
        line.ejes = code.split(',');
        line.steps = [
          Math.round(line.ejes[0] * (config.motor.xy.steps / config.motor.xy.advance)),
          Math.round(line.ejes[1] * (config.motor.xy.steps / config.motor.xy.advance)),
          Math.round(line.ejes[2] * (config.motor.z.steps  / config.motor.z.advance))
        ];
        realSendCommand( line.steps[0]+','+line.steps[1]+','+line.steps[2] , line );
        break;
      default:
        realSendCommand( code , line );
        break;
    }
  } else {
    console.error('sendCommand Arduino not selected');
    throw new Error('Arduino no seleccionado');
  }
}

function realSendCommand( code , line ){
  req.io.broadcast('lineaGCode', line ); // emitir enviar lines procesada a app.js
  // pasar code a arduino.js
  Arduino.sendCommand( code , ( dataReceived ) => {
    var d = dataReceived.split(',');
    if(d[0]==0 && d[1]==0 && d[2]==0){
      // arduino al terminar para aca y ese a app.js
      req.io.broadcast('closeConex', line._clone('Terminado') );
    }else{//Pause
      // arduino al terminar para aca y ese a app.js
      req.io.broadcast('closeConex', line._clone('Pausado') );
    }
  });
}

module.exports = {
  Arduino , File , Line , setFile , sendCommand
};<commit_msg>volver a grunt :D<commit_after>const
  fs = require('fs'),
  gc = require("./gcode"),
  Arduino = require('./arduino.js'),
  config  = require('./config.json')
;

function getMiliSeg ()  {
  return config.motor.xy.steps * config.motor.xy.time / config.motor.xy.advance ;
}

var File = {
  gcode   : [],
  dir     : '' ,
  name    : 'Sin Archivo',
  lines   : 0 ,
  travel    : 0 ,
  segTotal  : 0
}

function setFile ( dirfile ) {
  if (!dirfile) return {};
  File.dir = dirfile[0];
  File.gcode = gc(fs.readFileSync(dirfile[0]).toString());
  File.name = dirfile[0].split('/')[dirfile[0].split('/').length-1];
  File.lines = File.gcode.length;
  File.travel = File.gcode[File.gcode.length-1].travel;
  File.segTotal = File.gcode[File.gcode.length-1].travel * getMiliSeg();
  return File;
  //cb(File) ;
}

function Line (code) {
  return { nro : '', type : 'none', ejes : [], steps : [], travel : '', code }
}
Line.prototype._clone = (code) => {
  return {  code : Line(code), nro : this.nro, type : this.type, ejes : this.ejes, steps : this.steps, travel : this.travel }
}

function sendCommand ( type , code ){
  console.log(`sendCommand, type: ${type}, code: ${code}`);
  if( Arduino.port.comName !== '' ){
    switch (type) {
      case 'steps':
        var line = Line(`Comando manual ${type}: ${code}`);
        line.steps = code.split(',');
        line.ejes = [
          line.steps[0] * config.motor.xy.advance / config.motor.xy.steps,
          line.steps[1] * config.motor.xy.advance / config.motor.xy.steps,
          line.steps[2] * config.motor.z.advance  / config.motor.z.steps
        ];
        realSendCommand( code , line );
        break;
      case 'mm':
        var line = Line(`Comando manual ${type}: ${code}`);
        line.ejes = code.split(',');
        line.steps = [
          Math.round(line.ejes[0] * (config.motor.xy.steps / config.motor.xy.advance)),
          Math.round(line.ejes[1] * (config.motor.xy.steps / config.motor.xy.advance)),
          Math.round(line.ejes[2] * (config.motor.z.steps  / config.motor.z.advance))
        ];
        realSendCommand( line.steps[0]+','+line.steps[1]+','+line.steps[2] , line );
        break;
      default:
        realSendCommand( code , line );
        break;
    }
  } else {
    console.error('sendCommand Arduino not selected');
    throw new Error('Arduino no seleccionado');
  }
}

function realSendCommand( code , line ){
  req.io.broadcast('lineaGCode', line ); // emitir enviar lines procesada a app.js
  // pasar code a arduino.js
  Arduino.sendCommand( code , ( dataReceived ) => {
    var d = dataReceived.split(',');
    if(d[0]==0 && d[1]==0 && d[2]==0){
      // arduino al terminar para aca y ese a app.js
      req.io.broadcast('closeConex', line._clone('Terminado') );
    }else{//Pause
      // arduino al terminar para aca y ese a app.js
      req.io.broadcast('closeConex', line._clone('Pausado') );
    }
  });
}

module.exports = {
  Arduino , File , Line , setFile , sendCommand
};<|endoftext|>


<commit_before>import { combineReducers } from 'redux'
import {
  REQUEST_SELECT_RECORD, CANCEL_SELECT_RECORD,

  REQUEST_RECORD, RECEIVE_RECORD, SELECT_RECORD,

  SET_LENGTH_UNIT, LENGTH_UNITS,

  ADD_SCALE, REMOVE_SCALE,
  START_DRAWING_SCALE, STOP_DRAWING_SCALE,

  ADD_LINE, REMOVE_LINE,
  START_DRAWING_LINE, STOP_DRAWING_LINE,
} from './actions.js';

function selectedRecordId(state = null, action) {
  switch(action.type) {
    case SELECT_RECORD:
      return action.id;
    default:
      return state;
  }
}

const initialRecordState = {
  isFetching: false,
  record: null,
};

function record(state = initialRecordState, action) {
  switch(action.type) {
    case REQUEST_RECORD:
      return Object.assign({}, state, {
        isFetching: true, record: null
      });
    case RECEIVE_RECORD:
      return Object.assign({}, state, {
        isFetching: false, record: action.record
      });
    default:
      return state;
  }
}

function recordsById(state = {}, action) {
  switch(action.type) {
    case RECEIVE_RECORD:
    case REQUEST_RECORD:
      return Object.assign({}, state, {
        [action.id]: record(state[action.id], action),
      });
    default:
      return state;
  }
}

function showSelectRecordModal(state = false, action) {
  switch(action.type) {
    case REQUEST_SELECT_RECORD:
      return true;
    case CANCEL_SELECT_RECORD:
      return false;
    default:
      return state;
  }
}

// Scales
let nextScaleId = 1;
function scale(state, action) {
  switch(action.type) {
    case ADD_SCALE:
      let { startPoint, endPoint, length } = action;
      return { id: nextScaleId++, startPoint, endPoint, length };
    default:
      return state;
  }
}

function scales(state = [], action) {
  switch(action.type) {
    case ADD_SCALE:
      return [...state, scale(undefined, action)];
    case REMOVE_SCALE:
      return state.filter(s => s.id !== action.id);
    default:
      return state;
  }
}

// Lines
let nextLineId = 1;
function line(state, action) {
  switch(action.type) {
    case ADD_LINE:
      let { startPoint, endPoint, length } = action;
      return { id: nextLineId++, startPoint, endPoint, length };
    default:
      return state;
  }
}

function lines(state = [], action) {
  switch(action.type) {
    case ADD_LINE:
      return [...state, line(undefined, action)];
    case REMOVE_LINE:
      return state.filter(s => s.id !== action.id);
    default:
      return state;
  }
}

const features = combineReducers({
  scales, lines,
});

function lengthUnit(state = LENGTH_UNITS[0], action) {
  switch(action.type) {
    case SET_LENGTH_UNIT:
      return action.unit;
    default:
      return state;
  }
}

const options = combineReducers({
  lengthUnit,
});

const initialScaleInteractionState = { isDrawing: false, length: null };

function scaleInteraction(state = initialScaleInteractionState, action) {
  switch(action.type) {
    case START_DRAWING_SCALE:
      let { length } = action.payload;
      return Object.assign({}, state, { isDrawing: true, length });
    case STOP_DRAWING_SCALE:
      return Object.assign({}, state, { isDrawing: false, length: null });
    default:
      return state;
  }
}

const initialLineInteractionState = { isDrawing: false };

function lineInteraction(state = initialLineInteractionState, action) {
  switch(action.type) {
    case START_DRAWING_LINE:
      let { length } = action.payload;
      return Object.assign({}, state, { isDrawing: true });
    case STOP_DRAWING_LINE:
      return Object.assign({}, state, { isDrawing: false });
    default:
      return state;
  }
}

const interactions = combineReducers({
  scale: scaleInteraction,
  line: lineInteraction,
});

const app = combineReducers({
  selectedRecordId,
  recordsById,
  showSelectRecordModal,
  interactions,
  features,
  options,
});

export default app;

<commit_msg>fix use of undefined object<commit_after>import { combineReducers } from 'redux'
import {
  REQUEST_SELECT_RECORD, CANCEL_SELECT_RECORD,

  REQUEST_RECORD, RECEIVE_RECORD, SELECT_RECORD,

  SET_LENGTH_UNIT, LENGTH_UNITS,

  ADD_SCALE, REMOVE_SCALE,
  START_DRAWING_SCALE, STOP_DRAWING_SCALE,

  ADD_LINE, REMOVE_LINE,
  START_DRAWING_LINE, STOP_DRAWING_LINE,
} from './actions.js';

function selectedRecordId(state = null, action) {
  switch(action.type) {
    case SELECT_RECORD:
      return action.id;
    default:
      return state;
  }
}

const initialRecordState = {
  isFetching: false,
  record: null,
};

function record(state = initialRecordState, action) {
  switch(action.type) {
    case REQUEST_RECORD:
      return Object.assign({}, state, {
        isFetching: true, record: null
      });
    case RECEIVE_RECORD:
      return Object.assign({}, state, {
        isFetching: false, record: action.record
      });
    default:
      return state;
  }
}

function recordsById(state = {}, action) {
  switch(action.type) {
    case RECEIVE_RECORD:
    case REQUEST_RECORD:
      return Object.assign({}, state, {
        [action.id]: record(state[action.id], action),
      });
    default:
      return state;
  }
}

function showSelectRecordModal(state = false, action) {
  switch(action.type) {
    case REQUEST_SELECT_RECORD:
      return true;
    case CANCEL_SELECT_RECORD:
      return false;
    default:
      return state;
  }
}

// Scales
let nextScaleId = 1;
function scale(state, action) {
  switch(action.type) {
    case ADD_SCALE:
      let { startPoint, endPoint, length } = action;
      return { id: nextScaleId++, startPoint, endPoint, length };
    default:
      return state;
  }
}

function scales(state = [], action) {
  switch(action.type) {
    case ADD_SCALE:
      return [...state, scale(undefined, action)];
    case REMOVE_SCALE:
      return state.filter(s => s.id !== action.id);
    default:
      return state;
  }
}

// Lines
let nextLineId = 1;
function line(state, action) {
  switch(action.type) {
    case ADD_LINE:
      let { startPoint, endPoint, length } = action;
      return { id: nextLineId++, startPoint, endPoint, length };
    default:
      return state;
  }
}

function lines(state = [], action) {
  switch(action.type) {
    case ADD_LINE:
      return [...state, line(undefined, action)];
    case REMOVE_LINE:
      return state.filter(s => s.id !== action.id);
    default:
      return state;
  }
}

const features = combineReducers({
  scales, lines,
});

function lengthUnit(state = LENGTH_UNITS[0], action) {
  switch(action.type) {
    case SET_LENGTH_UNIT:
      return action.unit;
    default:
      return state;
  }
}

const options = combineReducers({
  lengthUnit,
});

const initialScaleInteractionState = { isDrawing: false, length: null };

function scaleInteraction(state = initialScaleInteractionState, action) {
  switch(action.type) {
    case START_DRAWING_SCALE:
      let { length } = action.payload;
      return Object.assign({}, state, { isDrawing: true, length });
    case STOP_DRAWING_SCALE:
      return Object.assign({}, state, { isDrawing: false, length: null });
    default:
      return state;
  }
}

const initialLineInteractionState = { isDrawing: false };

function lineInteraction(state = initialLineInteractionState, action) {
  switch(action.type) {
    case START_DRAWING_LINE:
      return Object.assign({}, state, { isDrawing: true });
    case STOP_DRAWING_LINE:
      return Object.assign({}, state, { isDrawing: false });
    default:
      return state;
  }
}

const interactions = combineReducers({
  scale: scaleInteraction,
  line: lineInteraction,
});

const app = combineReducers({
  selectedRecordId,
  recordsById,
  showSelectRecordModal,
  interactions,
  features,
  options,
});

export default app;

<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var readline = require('line-input-stream');
var exec = require('child_process').exec;
var execSync = require('sync-exec');
var args = process.argv.slice(2);
var colors = require('colors');
var os = require('os');
var path = require('path');
var verbose = false;
if (args[1] === 'verbose' || args[2] === 'verbose') {
  verbose = true;
}
var Replacer = module.exports = function Replacer(file, options) {
  var module = {},
          searches = [],
          seds = [],
          countLines = 0;
  /*
   * Add string for the replace
   *
   * @param string search
   * @param string replace
   */
  module.add = function (search, replace) {
    searches.push({search: search, replace: replace});
  };

  /*
   * Remove the string with a blank line
   *
   * @param string search
   */
  module.rm = function (search) {
    searches.push({search: "        " + search, replace: ''});
    searches.push({search: search, replace: ''});
  };

  /*
   * The rows for sed
   *
   * @param number startok
   * @param number _end
   */
  module.addsed = function (startok, endok) {
    seds.push({start: startok, end: endok});
  };

  /*
   * Workaround count the line of a file
   *
   * @param string file
   */
  module.getlines = function (file) {
    if (countLines === 0) {
      var wc = execSync("wc -l < " + process.cwd() + '/' + file);
      if (wc.stderr !== undefined) {
        console.log((wc.stderr).red);
      }
      countLines = parseInt(wc.stdout) - 1;
    }
  };

  module.file = file;

  //Base replacements
  module.add(/plugin-name/g, options.pluginSlug);
  module.add(/Plugin_Name_Admin/g, options.pluginClassName + '_Admin');
  module.add(/Plugin_Name/g, options.pluginClassName);
  module.add(/Plugin Name\./g, options.pluginName);
  module.add(/Plugin Name/g, options.pluginName);
  module.add(new RegExp(options.pluginName + ':', 'g'), 'Plugin Name:');
  module.add(/$plugin_name = 'Plugin Name';/g, '$plugin_name = ' + options.pluginName + '\';');
  module.add(/Plugin Name:( {7})@TODO/g, 'Plugin Name:       ' + options.pluginName);
  module.add(/Your Name <email@example\.com>/g, options.author + ' <' + options.authorEmail + '>');
  module.add(/1\.0\.0/g, options.pluginVersion);
  module.add(/Your Name or Company Name/g, options.pluginCopyright);
  module.add(new RegExp('http://example.com', 'g'), options.authorURI);
  module.add(/pn_/g, options.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '_');
  module.add(/Pn_/g, options.pluginName.match(/\b(\w)/g).join('') + '_');
  module.add(/pn-/g, options.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '-');

  /*
   * Replace the strings
   *
   */
  module.replace = function () {
    file = module.file;
    var exists = fs.readFileSync(process.cwd() + '/' + file);
    if (exists) {
      var data = exists;
      data = data.toString();
      module.add(/\n\n\n/g, "\n");
      var i, total;

      total = searches.length;
      for (i = 0; i < total; i += 1) {
        data = data.replace(searches[i].search, searches[i].replace);
      }

      fs.writeFileSync(process.cwd() + '/' + file, data);
      if (verbose) {
        console.log(('Replace ' + file).italic);
      }
    } else {
      console.log(('File not exist: ' + file).red);
    }
  };

  /*
   * Search the block of rows for sed
   *
   * @param number start
   * @param number end
   * @param number count_initial
   * @param number count_end
   */
  module.rmsearch = function (start, end, count_initial, count_end) {
    var stream_, startok, endok;
    var i = -1;
    var startspace = start;
    start = start.replace(/ /g, '');
    var endspace = end;
    if (end.length > 0) {
      end = end.replace(/ /g, '');
    }
    var exists = fs.readFileSync(process.cwd() + '/' + file);
    if (exists) {
      stream_ = readline(fs.createReadStream(file, {flags: 'r'}));
      stream_.setDelimiter("\n");
      module.getlines(file);

      //start reading the file
      stream_.on('line', function (line) {
        i++;
        line = line.replace(/(\r\n|\n|\r|\t)/gm, '').replace(/ /g, '');

        if (line === start) {
          startok = i - count_initial;
          if (!end.length) {
            endok = i + count_end;
          }
        } else if (line === end && end && (i - count_end > startok)) {
          endok = i - count_end;
        }

        //Fallback when end event is not emitted
        // Check the line number if is the last
        if (countLines === i) {
          if (typeof startok === 'undefined' || isNaN(startok)) {
            return console.log(('Not found start line: ' + startspace + ' in ' + file).yellow);
          }

          if (typeof endok === 'undefined' || isNaN(endok)) {
            return console.log(('Not found end line: ' + endspace + ' in ' + file).yellow);
          }

          if (endok !== '' && startok > endok) {
            return console.log(('Problem when parsing ' + file).red);
          }

          module.addsed(startok, endok);
        }

      });

      stream_.on("end", function () {
        if (typeof startok === 'undefined' || isNaN(startok)) {
          return console.log(('Not found start line <<' + startspace + '>> in ' + file).red);
        }

        if (typeof endok === 'undefined' || isNaN(endok)) {
          return console.log(('Not found end line <<' + endspace + '>> in ' + file).red);
        }

        if (endok !== '' && startok > endok) {
          return console.log(('Problem when parsing ' + file).red);
        }

        module.addsed(startok, endok);
      });

    } else {
      console.log(('File not exist: ' + file).red);
    }
  };

  /*
   * Call sed command and replace method
   *
   */
  module.sed = function () {
    file = module.file;
    try {
      var exists = fs.readFileSync(process.cwd() + '/' + file);
      if (exists) {
        if (seds.length !== 0) {
          var total = seds.length;
          var line = '';
          var i;

          for (i = 0; i < total; i += 1) {
            line += seds[i].start + ',' + seds[i].end + "d;";
          }
          var sedcmd = "sed -i '" + line + "' " + process.cwd() + '/' + file;
          //Detect OSX for a compatible sed command
          if(os.platform() === 'darwin') {
            sedcmd = "sed -i '" + path.extname(file) + "' '" + line + "' " + process.cwd() + '/' + file;
          }
          exec(sedcmd, {cwd: process.cwd() + '/'},
          function (err, stdout, stderr) {
            if (stderr.length > 0) {
              console.log((sedcmd).red);
              return console.log(('stderr: ' + stderr).red);
            }
            if (err !== null) {
              return console.log(('exec error: ' + err).red);
            }
            if (verbose) {
              console.log(('Sed ' + file).italic);
            }
            module.replace();
          });
        } else {
          module.replace();
        }
      } else {
        console.log(('File not exist: ' + file).red);
      }
    } catch (err) {

    }
  };

  return module;
};
<commit_msg>working on #11<commit_after>'use strict';

var fs = require('fs');
var readline = require('line-input-stream');
var exec = require('child_process').exec;
var execSync = require('sync-exec');
var args = process.argv.slice(2);
var colors = require('colors');
var os = require('os');
var path = require('path');
var verbose = false;
if (args[1] === 'verbose' || args[2] === 'verbose') {
  verbose = true;
}
var Replacer = module.exports = function Replacer(file, options) {
  var module = {},
          searches = [],
          seds = [],
          countLines = 0;
  /*
   * Add string for the replace
   *
   * @param string search
   * @param string replace
   */
  module.add = function (search, replace) {
    searches.push({search: search, replace: replace});
  };

  /*
   * Remove the string with a blank line
   *
   * @param string search
   */
  module.rm = function (search) {
    searches.push({search: "        " + search, replace: ''});
    searches.push({search: search, replace: ''});
  };

  /*
   * The rows for sed
   *
   * @param number startok
   * @param number _end
   */
  module.addsed = function (startok, endok) {
    seds.push({start: startok, end: endok});
  };

  /*
   * Workaround count the line of a file
   *
   * @param string file
   */
  module.getlines = function (file) {
    if (countLines === 0) {
      var wc = execSync("wc -l < " + process.cwd() + '/' + file);
      if (wc.stderr !== undefined) {
        console.log((wc.stderr).red);
      }
      countLines = parseInt(wc.stdout) - 1;
    }
  };

  module.file = file;

  //Base replacements
  module.add(/plugin-name/g, options.pluginSlug);
  module.add(/Plugin_Name_Admin/g, options.pluginClassName + '_Admin');
  module.add(/Plugin_Name/g, options.pluginClassName);
  module.add(/Plugin Name\./g, options.pluginName);
  module.add(/Plugin Name/g, options.pluginName);
  module.add(new RegExp(options.pluginName + ':', 'g'), 'Plugin Name:');
  module.add(/$plugin_name = 'Plugin Name';/g, '$plugin_name = ' + options.pluginName + '\';');
  module.add(/Plugin Name:( {7})@TODO/g, 'Plugin Name:       ' + options.pluginName);
  module.add(/Your Name <email@example\.com>/g, options.author + ' <' + options.authorEmail + '>');
  module.add(/1\.0\.0/g, options.pluginVersion);
  module.add(/Your Name or Company Name/g, options.pluginCopyright);
  module.add(new RegExp('http://example.com', 'g'), options.authorURI);
  module.add(/pn_/g, options.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '_');
  module.add(/Pn_/g, options.pluginName.match(/\b(\w)/g).join('') + '_');
  module.add(/pn-/g, options.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '-');

  /*
   * Replace the strings
   *
   */
  module.replace = function () {
    file = module.file;
    var exists = fs.readFileSync(process.cwd() + '/' + file);
    if (exists) {
      var data = exists;
      data = data.toString();
      module.add(/\n\n\n/g, "\n");
      var i, total;

      total = searches.length;
      for (i = 0; i < total; i += 1) {
        data = data.replace(searches[i].search, searches[i].replace);
      }

      fs.writeFileSync(process.cwd() + '/' + file, data);
      if (verbose) {
        console.log(('Replace ' + file).italic);
      }
    } else {
      console.log(('File not exist: ' + file).red);
    }
  };

  /*
   * Search the block of rows for sed
   *
   * @param number start
   * @param number end
   * @param number count_initial
   * @param number count_end
   */
  module.rmsearch = function (start, end, count_initial, count_end) {
    var stream_, startok, endok;
    var i = -1;
    var startspace = start;
    start = start.replace(/ /g, '');
    var endspace = end;
    if (end.length > 0) {
      end = end.replace(/ /g, '');
    }
    var exists = fs.readFileSync(process.cwd() + '/' + file);
    if (exists) {
      stream_ = readline(fs.createReadStream(file, {flags: 'r'}));
      stream_.setDelimiter("\n");
      module.getlines(file);

      //start reading the file
      stream_.on('line', function (line) {
        i++;
        line = line.replace(/(\r\n|\n|\r|\t)/gm, '').replace(/ /g, '');

        if (line === start) {
          startok = i - count_initial;
          if (!end.length) {
            endok = i + count_end;
          }
        } else if (line === end && end && (i - count_end > startok)) {
          endok = i - count_end;
        }

        //Fallback when end event is not emitted
        // Check the line number if is the last
        if (countLines === i) {
          if (typeof startok === 'undefined' || isNaN(startok)) {
            return console.log(('Not found start line: ' + startspace + ' in ' + file).yellow);
          }

          if (typeof endok === 'undefined' || isNaN(endok)) {
            return console.log(('Not found end line: ' + endspace + ' in ' + file).yellow);
          }

          if (endok !== '' && startok > endok) {
            return console.log(('Problem when parsing ' + file).red);
          }

          module.addsed(startok, endok);
        }

      });

      stream_.on("end", function () {
        if (typeof startok === 'undefined' || isNaN(startok)) {
          return console.log(('Not found start line <<' + startspace + '>> in ' + file).red);
        }

        if (typeof endok === 'undefined' || isNaN(endok)) {
          return console.log(('Not found end line <<' + endspace + '>> in ' + file).red);
        }

        if (endok !== '' && startok > endok) {
          return console.log(('Problem when parsing ' + file).red);
        }

        module.addsed(startok, endok);
      });

    } else {
      console.log(('File not exist: ' + file).red);
    }
  };

  /*
   * Call sed command and replace method
   *
   */
  module.sed = function () {
    file = module.file;
    try {
      var exists = fs.readFileSync(process.cwd() + '/' + file);
      if (exists) {
        if (seds.length !== 0) {
          var total = seds.length;
          var line = '';
          var i;

          for (i = 0; i < total; i += 1) {
            line += seds[i].start + ',' + seds[i].end + "d;";
          }
          var sedcmd = "sed -i '" + line + "' " + process.cwd() + '/' + file;
          //Detect OSX for a compatible sed command
          if(os.platform() === 'darwin') {
            sedcmd = "sed -i '" + path.extname(file) + "' '" + line + "' " + process.cwd() + '/' + file.substr( 0, file.lastIndexOf( "." ) );
          }
          exec(sedcmd, {cwd: process.cwd() + '/'},
          function (err, stdout, stderr) {
            if (stderr.length > 0) {
              console.log((sedcmd).red);
              return console.log(('stderr: ' + stderr).red);
            }
            if (err !== null) {
              return console.log(('exec error: ' + err).red);
            }
            if (verbose) {
              console.log(('Sed ' + file).italic);
            }
            module.replace();
          });
        } else {
          module.replace();
        }
      } else {
        console.log(('File not exist: ' + file).red);
      }
    } catch (err) {

    }
  };

  return module;
};
<|endoftext|>


<commit_before>/**
 * settings loads the config file (using config) and also preapares other
 * types of arrays etc that are useful based on that configuration.
 *
 * Any of the variables set in the config file can be accessed as
 * settings.var_name, so long as it's added to the _.each() array in here.
 */
module.exports = function(_) {

  var settings = this;

  var config = require('config');

  var default_config = {
    env: {
      heroku: false
    },
    menu: {
      font: '',
      theme: 'default',
      intro_text: 'Select your Twelescreen',
      outro_text: ''
    },
    categories: {
      _defaults: {
        font: '',
        theme: 'default',
        number_of_tweets: 10,
        disconnect_warning: 'Connection to server lost',
        slide_wait_time: 8000,
        slide_transition_time: 1000,
        greeting_time: 2000,
        chance_of_slogan: 5,
        show_on_menu: true,
        burn_in_text: '',
        greetings: ['Attention'],
        screen_names: [],
        slogans: []
        // title - If not present, we use the category's key.
      }
    },
    google_analytics_id: '',
    twitter: {}
  };

  _.each(_.keys(default_config), function(key) {
    // All the user's settings will be in config.
    // We mirror them into settings, for slightly easier access.
    // (Otherwise we'd have to use settings.config everywhere else.)
    if (_.has(config, key) && config[key] != null) {
      settings[key] = config[key];
    };

    if (key == 'categories' && '_defaults' in settings.categories) {
      // In case the user didn't set a categories._defaults:
      if ( ! settings.categories._defaults) {
        settings.categories._defaults = {};
      };

      // If the user's _defaults is missing anything, use the system defaults.
      _.defaults(settings.categories._defaults, default_config.categories._defaults);

      // For each of the user's categories, set any missing properties with the
      // default values.
      _.each(settings.categories, function(cat_settings, cat_key) {
        if (cat_key != '_defaults') {
          _.defaults(settings.categories[cat_key], settings.categories._defaults);

          // If no title is set for this category, use the category's key.
          if ( ! _.has(settings.categories[cat_key], 'title')
              || ! settings.categories[cat_key].title) {
            settings.categories[cat_key].title = cat_key;
          };
        };
      });

      // We don't need the user's category defaults now they're copied to the real
      // categories.
      delete settings.categories._defaults;

    } else {
      // All the other non-category settings are much simpler.
      _.defaults(settings[key], default_config[key]);
    };
  });

  // If the Twitter keys are set in ENV variables, use those instead.
  if (process.env.TWITTER_CONSUMER_KEY) {
    settings.twitter.consumer_key = process.env.TWITTER_CONSUMER_KEY;
    settings.twitter.consumer_secret = process.env.TWITTER_CONSUMER_SECRET;
    settings.twitter.access_token_key = process.env.TWITTER_ACCESS_TOKEN_KEY;
    settings.twitter.access_token_secret = process.env.TWITTER_ACCESS_TOKEN_SECRET;
  };

  /**
   * Will be an array of valid category keys, like: ['uk', 'us'].
   */
  settings.valid_categories = _.map(settings.categories,
                          function(category_data, category, l) { return category; });

  /**
   * Will be an array of all the data in settings.categories, but in a list
   * ordered by title. Used for the menu screen.
   */
  settings.categories_list = _.sortBy(
    _.map(settings.categories, function(category_data, category, l) {
      // Put the keys ('uk') into the category data.
      category_data.key = category;
      return category_data;
    }),
    function(data){
      return data.title;
    }
  );

  /**
   * Will be an array of all the twitter account screen_names for all of the
   * categories. like: ['ukhomeoffice', 'dhsgov'] (All lowercased.)
   */
  settings.watched_screen_names = _.uniq(
    _.map(settings.categories, function(v, k, l) {
      return _.map(v.screen_names, function(name) { return name.toLowerCase(); })
    })
  );

  /**
   * Will map Twitter screen_names to all the categories they're in.
   * Like: {'ukhomeoffice': ['uk'], 'dhsgov': ['us']}
   * All screen_names are lowercased.
   */
  settings.screen_name_to_category = {};
  _.each(settings.categories, function(category_data, category, l) {
    _.each(category_data.screen_names, function(screen_name) {
      screen_name = screen_name.toLowerCase();
      if (screen_name in screen_name_to_category) {
        screen_name_to_category[screen_name].push(category);
      } else {
        screen_name_to_category[screen_name] = [category];
      }
    })
  });

  /**
   * Will be populated by streamer.get_user_ids().
   */
  settings.watched_ids = [];

  settings.max_number_of_tweets = _.max(settings.categories,
      function(category){ return category.number_of_tweets; })['number_of_tweets']

  return settings;
};
<commit_msg>Fix setting of config defaults if the config file is missing whole sections<commit_after>/**
 * settings loads the config file (using config) and also preapares other
 * types of arrays etc that are useful based on that configuration.
 *
 * Any of the variables set in the config file can be accessed as
 * settings.var_name, so long as it's added to the _.each() array in here.
 */
module.exports = function(_) {

  var settings = this;

  var config = require('config');

  var default_config = {
    menu: {
      font: '',
      theme: 'default',
      intro_text: 'Select your Twelescreen',
      outro_text: ''
    },
    categories: {
      _defaults: {
        font: '',
        theme: 'default',
        number_of_tweets: 10,
        disconnect_warning: 'Connection to server lost',
        slide_wait_time: 8000,
        slide_transition_time: 1000,
        greeting_time: 2000,
        chance_of_slogan: 5,
        show_on_menu: true,
        burn_in_text: '',
        greetings: ['Attention'],
        screen_names: [],
        slogans: []
        // title - If not present, we use the category's key.
      }
    },
    google_analytics_id: '',
    twitter: {}
  };

  // We'll replace any missing settings from the user's config with the default.
  _.each(_.keys(default_config), function(key) {
    // All the user's settings will be in config.
    // We first mirror them into settings, for slightly easier access.
    // (Otherwise we'd have to use settings.config everywhere else.)
    if (_.has(config, key) && config[key] != null) {
      settings[key] = config[key];
    };

    if (key == 'categories' && '_defaults' in settings.categories) {
      // In case the user didn't set a categories._defaults:
      if ( ! settings.categories._defaults) {
        settings.categories._defaults = {};
      };

      // If the user's _defaults is missing anything, use the system defaults.
      _.defaults(settings.categories._defaults, default_config.categories._defaults);

      // For each of the user's categories, set any missing properties with the
      // default values.
      _.each(settings.categories, function(cat_settings, cat_key) {
        if (cat_key != '_defaults') {
          _.defaults(settings.categories[cat_key], settings.categories._defaults);

          // If no title is set for this category, use the category's key.
          if ( ! _.has(settings.categories[cat_key], 'title')
              || ! settings.categories[cat_key].title) {
            settings.categories[cat_key].title = cat_key;
          };
        };
      });

      // We don't need the user's category defaults now they're copied to the real
      // categories.
      delete settings.categories._defaults;

    } else {
      // All the other non-category settings are simpler.
      if ( ! _.has(settings, key)) {
        if (typeof default_config[key] == 'object') {
          // 'menu' or 'twitter'.
          settings[key] = {};
        } else {
          // 'google_analytics_id'.
          settings[key] = '';
        };
      };
      // Now copy the defaults in, if needed.
      _.defaults(settings[key], default_config[key]);
    };
  });

  // If the Twitter keys are set in ENV variables, use those instead.
  if (process.env.TWITTER_CONSUMER_KEY) {
    settings.twitter.consumer_key = process.env.TWITTER_CONSUMER_KEY;
    settings.twitter.consumer_secret = process.env.TWITTER_CONSUMER_SECRET;
    settings.twitter.access_token_key = process.env.TWITTER_ACCESS_TOKEN_KEY;
    settings.twitter.access_token_secret = process.env.TWITTER_ACCESS_TOKEN_SECRET;
  };

  /**
   * Will be an array of valid category keys, like: ['uk', 'us'].
   */
  settings.valid_categories = _.map(settings.categories,
                          function(category_data, category, l) { return category; });

  /**
   * Will be an array of all the data in settings.categories, but in a list
   * ordered by title. Used for the menu screen.
   */
  settings.categories_list = _.sortBy(
    _.map(settings.categories, function(category_data, category, l) {
      // Put the keys ('uk') into the category data.
      category_data.key = category;
      return category_data;
    }),
    function(data){
      return data.title;
    }
  );

  /**
   * Will be an array of all the twitter account screen_names for all of the
   * categories. like: ['ukhomeoffice', 'dhsgov'] (All lowercased.)
   */
  settings.watched_screen_names = _.uniq(
    _.map(settings.categories, function(v, k, l) {
      return _.map(v.screen_names, function(name) { return name.toLowerCase(); })
    })
  );

  /**
   * Will map Twitter screen_names to all the categories they're in.
   * Like: {'ukhomeoffice': ['uk'], 'dhsgov': ['us']}
   * All screen_names are lowercased.
   */
  settings.screen_name_to_category = {};
  _.each(settings.categories, function(category_data, category, l) {
    _.each(category_data.screen_names, function(screen_name) {
      screen_name = screen_name.toLowerCase();
      if (screen_name in screen_name_to_category) {
        screen_name_to_category[screen_name].push(category);
      } else {
        screen_name_to_category[screen_name] = [category];
      }
    })
  });

  /**
   * Will be populated by streamer.get_user_ids().
   */
  settings.watched_ids = [];

  settings.max_number_of_tweets = _.max(settings.categories,
      function(category){ return category.number_of_tweets; })['number_of_tweets']

  return settings;
};
<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.

// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd

'use strict';

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

/**
 * Fetches the metadata associated with the file at the given path from the
 * WebDAV server.
 * @param {Object} options Input options.
 * @param {function} onSuccess Function to be called if the metadata was
 *     fetched successfully.
 * @param {function} onError Function to be called if an error occured while
 *     attempting to fetch the metadata.
 */
module.exports = function(options, onSuccess, onError) {
  // Remove the leading slash from the path -- this isn't used in S3 keys.
  var path = options.entryPath.substring(1);;

  var metadata;
  // Handle the special case for the root directory.
  if (path === '') {
    metadata = util.makeDirectory('/');
    onSuccess(metadata, false);
    return;
  }

  // First check if the path corresponds to a valid directory by seeing if
  // there are any objects in the bucket with the path as a prefix.
  var parameters = s3fs.parameters({
    Prefix: path + '/',
    Delimiter: '/'
  });

  s3fs.s3.listObjects(parameters, function(error, data) {
    if (data && data.Contents.length > 0) {
      metadata = util.makeDirectory(path);
      onSuccess(metadata, false);
      return;
    }

    // If it isn't a directory, it might still be a file, so send another
    // request to fetch the metadata for that.
    parameters = s3fs.parameters({Key: path});

    s3fs.s3.getObject(parameters, function(error, data) {
      // If there's still an error, it's not a file or a directory, so call
      // the error callback.
      if (error) {
        console.log(error);
        onError('NOT_FOUND');
        return;
      }

      // If there's no error, it's a file, so convert the metadata into the
      // right format and return it to the API.
      metadata = {
        isDirectory: false,
        name: path,
        size: data.Body.length,
        modificationTime: new Date(data.LastModified),
        mimeType: data.ContentType
      };

      onSuccess(metadata, false);
    });
  });
};
<commit_msg>remove console.log<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.

// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd

'use strict';

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

/**
 * Fetches the metadata associated with the file at the given path from the
 * WebDAV server.
 * @param {Object} options Input options.
 * @param {function} onSuccess Function to be called if the metadata was
 *     fetched successfully.
 * @param {function} onError Function to be called if an error occured while
 *     attempting to fetch the metadata.
 */
module.exports = function(options, onSuccess, onError) {
  // Remove the leading slash from the path -- this isn't used in S3 keys.
  var path = options.entryPath.substring(1);;

  var metadata;
  // Handle the special case for the root directory.
  if (path === '') {
    metadata = util.makeDirectory('/');
    onSuccess(metadata, false);
    return;
  }

  // First check if the path corresponds to a valid directory by seeing if
  // there are any objects in the bucket with the path as a prefix.
  var parameters = s3fs.parameters({
    Prefix: path + '/',
    Delimiter: '/'
  });

  s3fs.s3.listObjects(parameters, function(error, data) {
    if (data && data.Contents.length > 0) {
      metadata = util.makeDirectory(path);
      onSuccess(metadata, false);
      return;
    }

    // If it isn't a directory, it might still be a file, so send another
    // request to fetch the metadata for that.
    parameters = s3fs.parameters({Key: path});

    s3fs.s3.getObject(parameters, function(error, data) {
      // If there's still an error, it's not a file or a directory, so call
      // the error callback.
      if (error) {
        onError('NOT_FOUND');
        return;
      }

      // If there's no error, it's a file, so convert the metadata into the
      // right format and return it to the API.
      metadata = {
        isDirectory: false,
        name: path,
        size: data.Body.length,
        modificationTime: new Date(data.LastModified),
        mimeType: data.ContentType
      };

      onSuccess(metadata, false);
    });
  });
};
<|endoftext|>


<commit_before>"use strict";
var screenshot = require('../../lib/pipes/screenshot.js');
var testcases = require('../files/hash.json');
var restbase = require('../../lib/pipes/restbase');
var pipe = require('../..');

describe('screenshot', function () {
    testcases.forEach(function (tc) {
        it('should take screenshot of svg from ' + JSON.stringify(tc.input), function () {
            var folder = pipe.getFolder(tc.input, pipe.config.conf.out_dir);
            var getCheck = restbase.check(tc.input, pipe.config.conf.restbase_url);
            var getFormats = restbase.getOutputs(folder, getCheck);
            return getFormats
                .then(function (res) {
                    return res.get('svg')
                        .then(function (svg) {
                            return screenshot.snapshot(svg);
                        });
                });
        });
    });
});<commit_msg>Increase timeout to allow travis tests to pass<commit_after>"use strict";
var screenshot = require('../../lib/pipes/screenshot.js');
var testcases = require('../files/hash.json');
var restbase = require('../../lib/pipes/restbase');
var pipe = require('../..');

describe('screenshot', function () {
    testcases.forEach(function (tc) {
        it('should take screenshot of svg from ' + JSON.stringify(tc.input), function () {
            this.timeout(50000);
            var folder = pipe.getFolder(tc.input, pipe.config.conf.out_dir);
            var getCheck = restbase.check(tc.input, pipe.config.conf.restbase_url);
            var getFormats = restbase.getOutputs(folder, getCheck);
            return getFormats
                .then(function (res) {
                    return res.get('svg')
                        .then(function (svg) {
                            return screenshot.snapshot(svg);
                        });
                });
        });
    });
});<|endoftext|>


<commit_before>'use strict';

var grunt = require('grunt');

exports.css_url_replace = {
  setUp: function(done) {
    // setup here if necessary
    done();
  },

  task: function(test) {
    test.expect(1);

    var expected = grunt.file.read('test/expected/schema_urls.css');
    var actual = grunt.file.read('tmp/schema_urls.css');
    test.equal(actual, expected, 'Css url replaced failed.');

    test.done();
  },
};
<commit_msg>remove unless file<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2017, Feedeo AB <hugo@feedeo.io>.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

describe('Send API Request', () => {
  let subject
  let Health
  let Request

  before(() => {
    Health = td.object([ 'addCheck' ])

    Request = td.constructor([])
  })

  afterEach(() => td.reset())

  describe('when exporting', () => {
    beforeEach(() => {
      td.replace('request-on-steroids', Request)

      subject = require('../src/send-api-request')
    })

    it('should be instance of request-on-steroids', () => {
      subject.should.be.instanceOf(Request)
    })
  })

  describe('when exporting and loading request-on-steroids', () => {
    beforeEach(() => {
      td.replace('health-checkup', Health)

      subject = require('../src/send-api-request')
    })

    it('should create a request-on-steroids with post function', () => {
      subject.should.have.property('post')
      subject.post.should.be.instanceOf(Function)
    })
  })

  describe('when constructing', () => {
    beforeEach(() => {
      td.replace('request-on-steroids', Request)

      td.replace('health-checkup', Health)

      subject = require('../src/send-api-request')
    })

    it('should add send api health check', () => {
      td.verify(Health.addCheck('send-api', td.matchers.isA(Function)), { times: 1 })
    })
  })
})
<commit_msg>test: minor tweaks<commit_after>/*
 * Copyright (c) 2017, Feedeo AB <hugo@feedeo.io>.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

describe('Send API Request', () => {
  let subject
  let Health
  let Request

  before(() => {
    Health = td.object([ 'addCheck' ])

    Request = td.constructor([])
  })

  afterEach(() => td.reset())

  describe('when exporting', () => {
    beforeEach(() => {
      td.replace('request-on-steroids', Request)

      subject = require('../src/send-api-request')
    })

    it('should be instance of request-on-steroids', () => {
      subject.should.be.instanceOf(Request)
    })
  })

  describe('when exporting and loading request-on-steroids', () => {
    beforeEach(() => {
      td.replace('health-checkup', Health)

      subject = require('../src/send-api-request')
    })

    it('should create a request-on-steroids with post function', () => {
      subject.should.have.property('post')
      subject.post.should.be.instanceOf(Function)
    })

    it('should create a request-on-steroids with circuitBreaker function', () => {
      subject.should.have.property('circuitBreaker')
      subject.post.should.be.instanceOf(Function)
    })
  })

  describe('when constructing', () => {
    beforeEach(() => {
      td.replace('request-on-steroids', Request)

      td.replace('health-checkup', Health)

      subject = require('../src/send-api-request')
    })

    it('should add send api health check', () => {
      td.verify(Health.addCheck('send-api', td.matchers.isA(Function)), { times: 1 })
    })
  })
})
<|endoftext|>


<commit_before>import webdriver from 'selenium-webdriver';

export function doBefore(done, action, load = './build/extension', port = 9515, browser = 'chrome') {
  this.driver = new webdriver.Builder()
    .usingServer(`http://localhost:${port}`)
    .withCapabilities({
      chromeOptions: {
        args: [ `load-extension=${load}` ]
      }
    })
    .forBrowser(browser)
    .build();
  action().then(() => done());
}

export function doAfter(done) {
  this.driver.quit().then(done);
}
<commit_msg>Wait 1 second before executing e2e test<commit_after>import webdriver from 'selenium-webdriver';

export function doBefore(done, action, load = './build/extension', port = 9515, browser = 'chrome') {
  this.driver = new webdriver.Builder()
    .usingServer(`http://localhost:${port}`)
    .withCapabilities({
      chromeOptions: {
        args: [ `load-extension=${load}` ]
      }
    })
    .forBrowser(browser)
    .build();
  action().then(() => {
    setTimeout(done, 1000);
  });
}

export function doAfter(done) {
  this.driver.quit().then(done);
}
<|endoftext|>


<commit_before>const { configureStore } = require('../store');
const readline = require('readline');
const draw = require('./draw');
const { keys } = require('./input');
const actions = require('../actions');

const resize = (proc, store) => {
    const action = actions.resize({
        rows: proc.stdout.rows,
        columns: proc.stdout.columns
    });
    store.dispatch(action);
};

module.exports = (initialState, proc = process) => {
    const store = configureStore(proc, initialState);
    const onStateChange = draw(process, store);
    store.subscribe(onStateChange);
    onStateChange();
    proc.stdin.addListener('keypress', keys(store));
    proc.stdout.addListener('resize', () => resize(proc, store));
    resize(proc, store);
    readline.emitKeypressEvents(proc.stdin);
    proc.stdin.setRawMode(true);
};<commit_msg>Remove use of process from global<commit_after>const { configureStore } = require('../store');
const readline = require('readline');
const draw = require('./draw');
const { keys } = require('./input');
const actions = require('../actions');

const resize = (proc, store) => {
    const action = actions.resize({
        rows: proc.stdout.rows,
        columns: proc.stdout.columns
    });
    store.dispatch(action);
};

module.exports = (initialState, proc = process) => {
    const store = configureStore(proc, initialState);
    const onStateChange = draw(proc, store);
    store.subscribe(onStateChange);
    onStateChange();
    proc.stdin.addListener('keypress', keys(store));
    proc.stdout.addListener('resize', () => resize(proc, store));
    resize(proc, store);
    readline.emitKeypressEvents(proc.stdin);
    proc.stdin.setRawMode(true);
};<|endoftext|>


<commit_before>/* global describe, it */

var exec = require('child_process').exec,
  expect = require('chai').expect// ,
  // assert = require('assert')

require('chai').should()
require('tap').mochaGlobals()

process.env.NYC_TEST = 'yep'

describe('signal-exit', function () {
  it('receives an exit event when a process exits normally', function (done) {
    exec(process.execPath + ' ./test/fixtures/end-of-execution.js', function (err, stdout, stderr) {
      expect(err).to.equal(null)
      stdout.should.match(/reached end of execution, 0, undefined/)
      done()
    })
  })

  it('receives an exit event when a process is terminated with sigint', function (done) {
    exec(process.execPath + ' ./test/fixtures/sigint.js', function (err, stdout, stderr) {
      stdout.should.match(/exited with sigint, 130, SIGINT/)
      done()
    })
  })

  it('receives an exit event when a process is terminated with sigterm', function (done) {
    exec(process.execPath + ' ./test/fixtures/sigterm.js', function (err, stdout, stderr) {
      stdout.should.match(/exited with sigterm, 143, SIGTERM/)
      done()
    })
  })

  it('receives an exit event when process.exit() is called', function (done) {
    exec(process.execPath + ' ./test/fixtures/exit.js', function (err, stdout, stderr) {
      err.code.should.equal(32)
      stdout.should.match(/exited with process\.exit\(\), 32, undefined/)
      done()
    })
  })

  it('does not exit if user handles signal', function (done) {
    exec(process.execPath + ' ./test/fixtures/signal-listener.js', function (err, stdout, stderr) {
      assert.equal(err.code, null)
      assert.equal(stdout, 'exited calledListener=4, code=129, signal="SIGHUP"\n')
      done()
    })
  })

  it('ensures that if alwaysLast=true, the handler is run last', function (done) {
    exec(process.execPath + ' ./test/fixtures/signal-last.js', function (err, stdout, stderr) {
      assert.equal(err.code, null)
      stdout.should.match(/first counter=1/)
      stdout.should.match(/last counter=2/)
      done()
    })
  })
})
<commit_msg>travis you'll be the death of me<commit_after>/* global describe, it */

var exec = require('child_process').exec,
  expect = require('chai').expect,
  assert = require('assert')

require('chai').should()
require('tap').mochaGlobals()

process.env.NYC_TEST = 'yep'

describe('signal-exit', function () {
  it('receives an exit event when a process exits normally', function (done) {
    exec(process.execPath + ' ./test/fixtures/end-of-execution.js', function (err, stdout, stderr) {
      expect(err).to.equal(null)
      stdout.should.match(/reached end of execution, 0, undefined/)
      done()
    })
  })

  it('receives an exit event when a process is terminated with sigint', function (done) {
    exec(process.execPath + ' ./test/fixtures/sigint.js', function (err, stdout, stderr) {
      expect(err.code).to.equal(null)
      stdout.should.match(/exited with sigint, 130, SIGINT/)
      done()
    })
  })

  it('receives an exit event when a process is terminated with sigterm', function (done) {
    exec(process.execPath + ' ./test/fixtures/sigterm.js', function (err, stdout, stderr) {
      expect(err.code).to.equal(null)
      stdout.should.match(/exited with sigterm, 143, SIGTERM/)
      done()
    })
  })

  it('receives an exit event when process.exit() is called', function (done) {
    exec(process.execPath + ' ./test/fixtures/exit.js', function (err, stdout, stderr) {
      err.code.should.equal(32)
      stdout.should.match(/exited with process\.exit\(\), 32, undefined/)
      done()
    })
  })

  it('does not exit if user handles signal', function (done) {
    exec(process.execPath + ' ./test/fixtures/signal-listener.js', function (err, stdout, stderr) {
      assert.equal(err.code, null)
      assert.equal(stdout, 'exited calledListener=4, code=129, signal="SIGHUP"\n')
      done()
    })
  })

  it('ensures that if alwaysLast=true, the handler is run last', function (done) {
    exec(process.execPath + ' ./test/fixtures/signal-last.js', function (err, stdout, stderr) {
      assert.equal(err.code, null)
      stdout.should.match(/first counter=1/)
      stdout.should.match(/last counter=2/)
      done()
    })
  })
})
<|endoftext|>


<commit_before>/**
 * The GeoExt.panel.Map used in the application.  Useful to define map options
 * and stuff.
 * @extends GeoExt.panel.Map
 */
Ext.define('CF.view.Map', {
    // Ext.panel.Panel-specific options:
    extend: 'GeoExt.panel.Map',
    alias : 'widget.cf_mappanel',
    requires: [
        'Ext.window.MessageBox',
        'GeoExt.Action',
        'CF.view.help.Action'
    ],
    border: 'false',
    region: 'center',
    // GeoExt.panel.Map-specific options :
    center: '-67.336,52.451',
    zoom: 9,

    initComponent: function() {
        var me = this,
            items = [],
            ctrl;

        var map = new OpenLayers.Map();

        // ZoomToMaxExtent control, a "button" control
        items.push(Ext.create('Ext.button.Button', Ext.create('GeoExt.Action', {
            control: new OpenLayers.Control.ZoomToMaxExtent(),
            map: map,
            text: "max extent",
            tooltip: "zoom to max extent"
        })));

        items.push("-");

        // Navigation control
        items.push(Ext.create('Ext.button.Button',Ext.create('GeoExt.Action', {
            text: "nav",
            control: new OpenLayers.Control.Navigation(),
            map: map,
            // button options
            toggleGroup: "draw",
            allowDepress: false,
            pressed: true,
            tooltip: "navigate",
            // check item options
            group: "draw",
            checked: true
        })));

        items.push("-");

        // Navigation history - two "button" controls
        ctrl = new OpenLayers.Control.NavigationHistory();
        map.addControl(ctrl);

        items.push(Ext.create('Ext.button.Button', Ext.create('GeoExt.Action', {
            text: "previous",
            control: ctrl.previous,
            disabled: true,
            tooltip: "previous in history"
        })));

        items.push(Ext.create('Ext.button.Button', Ext.create('GeoExt.Action', {
            text: "next",
            control: ctrl.next,
            disabled: true,
            tooltip: "next in history"
        })));
        items.push("->");

        // Help action
        items.push(
            Ext.create('Ext.button.Button', Ext.create('CF.view.help.Action', {
                windowContentEl: "help"
            }))
        );

        Ext.apply(me, {
            map: map,
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'top',
                items: items,
                style: {
                    border: 0,
                    padding: 0
                }
                    }]
        });

        me.callParent(arguments);
    }
});
<commit_msg>Fix map default controls<commit_after>/**
 * The GeoExt.panel.Map used in the application.  Useful to define map options
 * and stuff.
 * @extends GeoExt.panel.Map
 */
Ext.define('CF.view.Map', {
    // Ext.panel.Panel-specific options:
    extend: 'GeoExt.panel.Map',
    alias : 'widget.cf_mappanel',
    requires: [
        'Ext.window.MessageBox',
        'GeoExt.Action',
        'CF.view.help.Action'
    ],
    border: 'false',
    region: 'center',
    // GeoExt.panel.Map-specific options :
    center: '-67.336,52.451',
    zoom: 9,

    initComponent: function() {
        var me = this,
            items = [],
            ctrl;

        var map = new OpenLayers.Map({
            controls: [
                new OpenLayers.Control.Zoom()
            ]
        });

        // ZoomToMaxExtent control, a "button" control
        items.push(Ext.create('Ext.button.Button', Ext.create('GeoExt.Action', {
            control: new OpenLayers.Control.ZoomToMaxExtent(),
            map: map,
            text: "max extent",
            tooltip: "zoom to max extent"
        })));

        items.push("-");

        // Navigation control
        items.push(Ext.create('Ext.button.Button',Ext.create('GeoExt.Action', {
            text: "nav",
            control: new OpenLayers.Control.Navigation(),
            map: map,
            // button options
            toggleGroup: "draw",
            allowDepress: false,
            pressed: true,
            tooltip: "navigate",
            // check item options
            group: "draw",
            checked: true
        })));

        items.push("-");

        // Navigation history - two "button" controls
        ctrl = new OpenLayers.Control.NavigationHistory();
        map.addControl(ctrl);

        items.push(Ext.create('Ext.button.Button', Ext.create('GeoExt.Action', {
            text: "previous",
            control: ctrl.previous,
            disabled: true,
            tooltip: "previous in history"
        })));

        items.push(Ext.create('Ext.button.Button', Ext.create('GeoExt.Action', {
            text: "next",
            control: ctrl.next,
            disabled: true,
            tooltip: "next in history"
        })));
        items.push("->");

        // Help action
        items.push(
            Ext.create('Ext.button.Button', Ext.create('CF.view.help.Action', {
                windowContentEl: "help"
            }))
        );

        Ext.apply(me, {
            map: map,
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'top',
                items: items,
                style: {
                    border: 0,
                    padding: 0
                }
                    }]
        });

        me.callParent(arguments);
    }
});
<|endoftext|>


<commit_before>/* test/site_routes_test.js -- test Site routes
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */

var expect = require('expect.js');
var Routes = require('../routes/site');
var router = require('./support/router');
var Site = require('../models/site');

var siteAttrs = {
  name: "Some site",
};

describe('Site routes', function() {
  var site, count, last;
  before(function(done) {
    Factory.create('site', 26, function (l) {
      site = l[0];
      Site.count(function (err, c) {
        if (err) throw err;
        count = c;
        last = (count + 24) / 25;
        done();
      });
    });
  });

  var operator;
  before(function(done) {
    Factory.create('user', function (u) { operator = u; done(); });
  });

  var admin;
  before(function(done) {
    Factory.create('admin', function (a) { admin = a; done(); });
  });

  describe("#load", function() {
    it("should find by id and assign site to req", function(done) {
      var req = { },
      id = site._id;

      Routes.load(req, {}, function() {
        expect(req.site.toJSON()).to.eql(site.toJSON());
        done();
      }, id);
    });

    it("should respond with not found code", function(done) {
      var res = {
        send: function(code) {
          expect(code).to.eql(404);
          done();
        }
      };
      Routes.load({}, res, null, 0);
    });
  });

  describe("#show", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.show, req, res);
    });

    describe("when operator logged in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should return 404 if no device", function(done) {
        var res = {
          locals: {},
          send: function(code) {
            expect(code).to.be(404);
            done();
          },
        };
        router(Routes.show, req, res);
      });

      it("should return only accessible fields", function(done) {
        var res = {
          locals: {},
          json_ng: function(st) {
            expect(Object.keys(st)).to.eql(['_id', 'name']);
            expect(st._id).to.eql(site._id);
            expect(st.name).to.eql(site.name);
            done();
          },
        };
        req.site = site;
        req.site.some_field = true;
        router(Routes.show, req, res);
      });
    });
  });

  describe("#update", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.update, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should deny non-admins", function(done) {
        res = {
          locals: {},
          send: function(code) {
            expect(code).to.eql(403);
            done();
          },
        };
        router(Routes.update, req, res);
      });
    });

    describe("when administrator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: admin._id } };
      });

      it("should fail", function(done) {
        var res = {
          locals: {},
          json: function(code) {
            expect(code).to.eql(500);
            done();
          },
        };
        req.body = {
          name: "Some name",
        };
        req.site = site;
        router(Routes.update, req, res);
      });
    });
  });

  describe("#index", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.index, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
        req.query = {};
        res = {
          locals: {},
        };
      });

      it("should retrieve first page if not specified", function(done) {
        res.json_ng = function(sites) {
          expect(sites.length).to.be(26);
          expect(sites[25].count).to.be(count);
          done();
        };
        router(Routes.index, req, res);
      });

      it("should sort results by name", function(done) {
        var original = [];
        res.json_ng = function(sites) {
          var fetched = sites.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        Site.find({}, "_id").sort({name: 1}).limit(25).exec(function(err, sites) {
          original = sites.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve requested page", function(done) {
        var original = [];
        res.json_ng = function(sites) {
          var fetched = sites.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = last;
        Site.find({}, "_id").sort({name: 1}).skip(25).limit(25).exec(function(err, sites) {
          original = sites.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve first one if page is less then 1", function(done) {
        var original = [];
        res.json_ng = function(sites) {
          var fetched = sites.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        Site.find({}, "_id").sort({name: 1}).limit(25).exec(function(err, sites) {
          original = sites.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve last one if page is too big", function(done) {
        var original = [];
        res.json_ng = function(sites) {
          var fetched = sites.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = last + 1;
        Site.find({}, "_id").sort({name: 1}).skip(25).limit(25).exec(function(err, sites) {
          original = sites.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });
    });
  });

  describe("#create", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.index, req, res);
    });
  });
});

// vim:ts=2 sts=2 sw=2 et:

<commit_msg>tests: routes: create site authorization<commit_after>/* test/site_routes_test.js -- test Site routes
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */

var expect = require('expect.js');
var Routes = require('../routes/site');
var router = require('./support/router');
var Site = require('../models/site');

var siteAttrs = {
  name: "Some site",
};

describe('Site routes', function() {
  var site, count, last;
  before(function(done) {
    Factory.create('site', 26, function (l) {
      site = l[0];
      Site.count(function (err, c) {
        if (err) throw err;
        count = c;
        last = (count + 24) / 25;
        done();
      });
    });
  });

  var operator;
  before(function(done) {
    Factory.create('user', function (u) { operator = u; done(); });
  });

  var admin;
  before(function(done) {
    Factory.create('admin', function (a) { admin = a; done(); });
  });

  describe("#load", function() {
    it("should find by id and assign site to req", function(done) {
      var req = { },
      id = site._id;

      Routes.load(req, {}, function() {
        expect(req.site.toJSON()).to.eql(site.toJSON());
        done();
      }, id);
    });

    it("should respond with not found code", function(done) {
      var res = {
        send: function(code) {
          expect(code).to.eql(404);
          done();
        }
      };
      Routes.load({}, res, null, 0);
    });
  });

  describe("#show", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.show, req, res);
    });

    describe("when operator logged in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should return 404 if no device", function(done) {
        var res = {
          locals: {},
          send: function(code) {
            expect(code).to.be(404);
            done();
          },
        };
        router(Routes.show, req, res);
      });

      it("should return only accessible fields", function(done) {
        var res = {
          locals: {},
          json_ng: function(st) {
            expect(Object.keys(st)).to.eql(['_id', 'name']);
            expect(st._id).to.eql(site._id);
            expect(st.name).to.eql(site.name);
            done();
          },
        };
        req.site = site;
        req.site.some_field = true;
        router(Routes.show, req, res);
      });
    });
  });

  describe("#update", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.update, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should deny non-admins", function(done) {
        res = {
          locals: {},
          send: function(code) {
            expect(code).to.eql(403);
            done();
          },
        };
        router(Routes.update, req, res);
      });
    });

    describe("when administrator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: admin._id } };
      });

      it("should fail", function(done) {
        var res = {
          locals: {},
          json: function(code) {
            expect(code).to.eql(500);
            done();
          },
        };
        req.body = {
          name: "Some name",
        };
        req.site = site;
        router(Routes.update, req, res);
      });
    });
  });

  describe("#index", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.index, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
        req.query = {};
        res = {
          locals: {},
        };
      });

      it("should retrieve first page if not specified", function(done) {
        res.json_ng = function(sites) {
          expect(sites.length).to.be(26);
          expect(sites[25].count).to.be(count);
          done();
        };
        router(Routes.index, req, res);
      });

      it("should sort results by name", function(done) {
        var original = [];
        res.json_ng = function(sites) {
          var fetched = sites.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        Site.find({}, "_id").sort({name: 1}).limit(25).exec(function(err, sites) {
          original = sites.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve requested page", function(done) {
        var original = [];
        res.json_ng = function(sites) {
          var fetched = sites.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = last;
        Site.find({}, "_id").sort({name: 1}).skip(25).limit(25).exec(function(err, sites) {
          original = sites.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve first one if page is less then 1", function(done) {
        var original = [];
        res.json_ng = function(sites) {
          var fetched = sites.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        Site.find({}, "_id").sort({name: 1}).limit(25).exec(function(err, sites) {
          original = sites.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });

      it("should retrieve last one if page is too big", function(done) {
        var original = [];
        res.json_ng = function(sites) {
          var fetched = sites.slice(0, -1).map(function(item) {
            return item._id.toString();
          });
          expect(fetched).to.eql(original);
          done();
        };
        req.query.page = last + 1;
        Site.find({}, "_id").sort({name: 1}).skip(25).limit(25).exec(function(err, sites) {
          original = sites.map(function(item) { return item._id.toString(); });
          router(Routes.index, req, res);
        });
      });
    });
  });

  describe("#create", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.index, req, res);
    });

    describe("when operator signed in", function() {
      var req;

      beforeEach(function() {
        req = { session: { operatorId: operator._id } };
      });

      it("should deny non-admins", function(done) {
        res = {
          locals: {},
          send: function(code) {
            expect(code).to.eql(403);
            done();
          },
        };
        router(Routes.create, req, res);
      });
    });
  });
});

// vim:ts=2 sts=2 sw=2 et:

<|endoftext|>