<commit_before>document.addEventListener('DOMContentLoaded', function() {
	changeIPInput();
	document.getElementById("ip").disabled=true;
	//add listenser for save
	var save = document.getElementById("save");

	save.addEventListener("click", saveInfo);

	//add listenser for usePrivateIP checkbox
	var usePrivateIP = document.getElementById("usePrivateIP");

	usePrivateIP.addEventListener('change', function(){
		if(usePrivateIP.checked){
			localStorage.setItem("option_usePrivateIP","true");
			changeIPInput();
		}
		else{
			localStorage.setItem("option_usePrivateIP","false");
			changeIPInput();
		}
	});

	//add listenser for force update
	var forceUpdate = document.getElementById("forceUpdate");
	forceUpdate.addEventListener("click", function() {
		var hostname = document.getElementById("hostname");
		var token = document.getElementById("token");
		var ip = document.getElementById("ip");
		var updateInterval = document.getElementById("updateInterval");
		updateCsieIoDDNS(ip.value, token.value, hostname.value);
	});

	//display saved value
	var hostname = document.getElementById("hostname");
	var token = document.getElementById("token");
	var ip = document.getElementById("ip");
	var updateInterval = document.getElementById("updateInterval");

	hostname.value = localStorage.getItem('hostname', hostname.value);
	token.value = localStorage.getItem('token', token.value);
	/*	don't show token in option
	 token.value = localStorage.getItem('token', token.value).replace(/(.*?-)(.*)/g, function ($0, $1, $2) {
        return $1 + (new Array($2.length + 1).join("*"));
    });
    */
	ip.value = localStorage.getItem('ip', ip.value);
	updateInterval.value = localStorage.getItem('updateInterval', updateInterval.value);

	//check isSave before leave

	window.addEventListener("beforeunload", function(e) {
		var unSaveMsg = "Not save yet!";

		if (localStorage.getItem('hostname', hostname.value) && localStorage.getItem('token', token.value) && localStorage.getItem('ip', ip.value) && localStorage.getItem('updateInterval', updateInterval.value)) {
			return undefined;
		}

		(e || window.event).returnValue = unSaveMsg;
		return unSaveMsg;
	});

});

function saveInfo() {
	var hostname = document.getElementById("hostname");
	var token = document.getElementById("token");
	var ip = document.getElementById("ip");
	var updateInterval = document.getElementById("updateInterval");

	localStorage.setItem('hostname', hostname.value);
	localStorage.setItem('token', token.value);
	localStorage.setItem('ip', ip.value);
	localStorage.setItem('updateInterval', updateInterval.value);

	chrome.alarms.create("updateDDNS", {
		delayInMinutes : parseInt(updateInterval.value),
		periodInMinutes : parseInt(updateInterval.value)
	});

}
function changeIPInput(){

	var ip = document.getElementById("ip");
	var usePrivateIP = localStorage.getItem("option_usePrivateIP");
	if (usePrivateIP === "true") {
		getLocalIPs(function(privateIPs) {
			var ip_local = privateIPs[0];
			ip.value = ip_local;
		});
		return ;
	}

	//jsonp for ip
	var xhr = new XMLHttpRequest();
	xhr.open('GET', "http://api.hostip.info/get_json.php");
	xhr.onreadystatechange = function() {
		if (xhr.readyState == XMLHttpRequest.DONE) {
			if (xhr.status == 200) {
				try {
					var data = JSON.parse(xhr.responseText);
					ip.value = data.ip;
				} catch(e) {
					return false;
				}
			} else {
				console.error(xhr.responseText);
			}
		}
	};
	xhr.send();
}
function updateCsieIoDDNS(ip, token, hostname) {
	var xhr = new XMLHttpRequest();
	xhr.open('GET', 'https://csie.io/update?hn=' + hostname + '&token=' + token + '&ip=' + ip);
	xhr.onreadystatechange = function() {
		if (xhr.readyState == XMLHttpRequest.DONE) {
			if (xhr.status == 200) {
				console.log(xhr.responseText);
			} else {
				console.error(xhr.responseText);
			}
		}
	};
	xhr.send();
}

function getLocalIPs(callback) {
    var ips = [];
    var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection;
    var pc = new RTCPeerConnection({
        iceServers: []
    });
    pc.createDataChannel('');
    pc.onicecandidate = function(e) {
        if (!e.candidate) {
            callback(ips);
            return;
        }
        var ip = /^candidate:.+ (\S+) \d+ typ.*/.exec(e.candidate.candidate)[1];
        if (ips.indexOf(ip) == -1)
            ips.push(ip);
    };
    pc.createOffer(function(sdp) {
        pc.setLocalDescription(sdp);
    }, function onerror() {});
}
<commit_msg>default intervalTime:60min<commit_after>document.addEventListener('DOMContentLoaded', function() {
	changeIPInput();
	document.getElementById("ip").disabled=true;
	//add listenser for save
	var save = document.getElementById("save");

	save.addEventListener("click", saveInfo);

	//add listenser for usePrivateIP checkbox
	var usePrivateIP = document.getElementById("usePrivateIP");

	usePrivateIP.addEventListener('change', function(){
		if(usePrivateIP.checked){
			localStorage.setItem("option_usePrivateIP","true");
			changeIPInput();
		}
		else{
			localStorage.setItem("option_usePrivateIP","false");
			changeIPInput();
		}
	});

	//add listenser for force update
	var forceUpdate = document.getElementById("forceUpdate");
	forceUpdate.addEventListener("click", function() {
		var hostname = document.getElementById("hostname");
		var token = document.getElementById("token");
		var ip = document.getElementById("ip");
		var updateInterval = document.getElementById("updateInterval");
		updateCsieIoDDNS(ip.value, token.value, hostname.value);
	});

	//display saved value
	var hostname = document.getElementById("hostname");
	var token = document.getElementById("token");
	var ip = document.getElementById("ip");
	var updateInterval = document.getElementById("updateInterval");

	hostname.value = localStorage.getItem('hostname', hostname.value);
	token.value = localStorage.getItem('token', token.value);
	/*	don't show token in option
	 token.value = localStorage.getItem('token', token.value).replace(/(.*?-)(.*)/g, function ($0, $1, $2) {
        return $1 + (new Array($2.length + 1).join("*"));
    });
    */
	ip.value = localStorage.getItem('ip', ip.value);
	updateInterval.value = localStorage.getItem('updateInterval', updateInterval.value) || 60;

	//check isSave before leave

	window.addEventListener("beforeunload", function(e) {
		var unSaveMsg = "Not save yet!";

		if (localStorage.getItem('hostname', hostname.value) && localStorage.getItem('token', token.value) && localStorage.getItem('ip', ip.value) && localStorage.getItem('updateInterval', updateInterval.value)) {
			return undefined;
		}

		(e || window.event).returnValue = unSaveMsg;
		return unSaveMsg;
	});

});

function saveInfo() {
	var hostname = document.getElementById("hostname");
	var token = document.getElementById("token");
	var ip = document.getElementById("ip");
	var updateInterval = document.getElementById("updateInterval");

	localStorage.setItem('hostname', hostname.value);
	localStorage.setItem('token', token.value);
	localStorage.setItem('ip', ip.value);
	localStorage.setItem('updateInterval', updateInterval.value);

	chrome.alarms.create("updateDDNS", {
		delayInMinutes : parseInt(updateInterval.value),
		periodInMinutes : parseInt(updateInterval.value)
	});

}
function changeIPInput(){

	var ip = document.getElementById("ip");
	var usePrivateIP = localStorage.getItem("option_usePrivateIP");
	if (usePrivateIP === "true") {
		getLocalIPs(function(privateIPs) {
			var ip_local = privateIPs[0];
			ip.value = ip_local;
		});
		return ;
	}

	//jsonp for ip
	var xhr = new XMLHttpRequest();
	xhr.open('GET', "http://api.hostip.info/get_json.php");
	xhr.onreadystatechange = function() {
		if (xhr.readyState == XMLHttpRequest.DONE) {
			if (xhr.status == 200) {
				try {
					var data = JSON.parse(xhr.responseText);
					ip.value = data.ip;
				} catch(e) {
					return false;
				}
			} else {
				console.error(xhr.responseText);
			}
		}
	};
	xhr.send();
}
function updateCsieIoDDNS(ip, token, hostname) {
	var xhr = new XMLHttpRequest();
	xhr.open('GET', 'https://csie.io/update?hn=' + hostname + '&token=' + token + '&ip=' + ip);
	xhr.onreadystatechange = function() {
		if (xhr.readyState == XMLHttpRequest.DONE) {
			if (xhr.status == 200) {
				console.log(xhr.responseText);
			} else {
				console.error(xhr.responseText);
			}
		}
	};
	xhr.send();
}

function getLocalIPs(callback) {
    var ips = [];
    var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection;
    var pc = new RTCPeerConnection({
        iceServers: []
    });
    pc.createDataChannel('');
    pc.onicecandidate = function(e) {
        if (!e.candidate) {
            callback(ips);
            return;
        }
        var ip = /^candidate:.+ (\S+) \d+ typ.*/.exec(e.candidate.candidate)[1];
        if (ips.indexOf(ip) == -1)
            ips.push(ip);
    };
    pc.createOffer(function(sdp) {
        pc.setLocalDescription(sdp);
    }, function onerror() {});
}
<|endoftext|>


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

  // --------------------------------------------------- variable initialisation
  /*
   * HACK: we are passing a parameter to this scripts through a data-* balise.
   * more here: http://stackoverflow.com/a/32589923/6320039
   */
  var isExam = 'exam' == document.currentScript.getAttribute('data-id');

  var id = 0;

  // JQuery quick access to important nodes
  var $domain       = $('#domain');
  var $question     = $('#question');
  var $answers      = $('#answers');
  var $nextQuestion = $('#next-question');
  var $dashboard    = $('#dashboard');

  if (isExam) var counter = 0;

  // ---------------------------------------------------- main logic (functions)
  /**
   * Change DOM elements relative to a question :
   *  - question
   *  - domain
   *  - answers
   *
   * The question is randomly retrieved from the database. If the global
   * parameter isExam is set, then the question can be only in domains
   * contained in sessionStorage.domains; and it also increment the counter.
   * If the counter is greater than sessionStorage.numberOfQuestions, then exam
   * is over and window is redirected to /result.
   * @return undefined
   */
  function changeQuestion() {
    var url;
    if (isExam) {
      if (++counter == sessionStorage.numberOfQuestions)
        $nextQuestion.find('span').html('Fin de l’examen');
      else if (counter > sessionStorage.numberOfQuestions) {
        window.location = '/result';
        return;
      }
      url = "/api/ask/rand/" + sessionStorage.domains;
    } else {
      url = "/api/ask/rand/";
    }
    $.get(url)
      .done(function(data) {
        id = data.id;
        console.log(id);
        $domain.html(data.domain);
        $question.html(data.question);
        // clean everything except first answer (bones)
        $answers.find('.answer:not(:first)').remove()
        for (var answer of data.answers) {
          $answers
            // clone body of an answer
            .find('.answer:first')
            .clone()
            // append current answer elements to the clone
            .find('input')
              .attr('name', answer)
            .end()
            .find('label')
              .attr('for', answer)
              .html(answer)
            .end()
            // append the clone to DOM (#answer)
            .appendTo($answers)
            // show the clone
            .show();
        }

        dragndrop();
      })
      .fail(function (data) {
        console.log(data);
      });

    }

    function dragndrop(){
      var draggable = document.querySelectorAll(".answer");
      var droptarget = document.getElementById("droptarget");

      droptarget.innerHTML = "Glisser la réponse !"
      droptarget.classList.remove("false");
      droptarget.classList.remove("right");
      droptarget.classList.add("free");

      for(var i = 1; i < draggable.length; i++){
        (function(i){
          draggable[i].classList.add("draggable");
          draggable[i].setAttribute("draggable", "true");
          draggable[i].addEventListener('dragstart', dragStart, false);  //the user starts dragging the element
          draggable[i].addEventListener('dragend'  , dragEnd  , false);
        })(i)
      }

      droptarget.addEventListener('dragenter', dragEnter  , false); //fired when the user drags the draggable onto the drop target (only fires when the draggable element changes from being outside to being over)
      droptarget.addEventListener('dragover' , dragOver   , false); //Fired once the draggable element is over the drop target and keeps firing for as long as the draggable element is being dragged over the drop target.
      droptarget.addEventListener('dragleave', dragLeave  , false); //If the user drags the draggable object out of the drop target again, the dragleave event is fired.
      droptarget.addEventListener('drop'     , drop       , false); //If the user drops the draggable object on the drop target, the drop event is fired.

      /* Draggable event handlers */
      function dragStart(event) {
          var dataToSet = event.target.getElementsByTagName('label')[0].getAttribute('for');
          event.dataTransfer.setData("text", dataToSet); //data that is transfered to the drop target when the element is dropped. (MIME, data)
          event.dataTransfer.effectsAllowed = "copy";

          for(var i = 1; i < draggable.length; i++){
            (function(i){
              if(document.getElementsByTagName('label')[i].getAttribute('for') == event.target.getElementsByTagName('label')[0].getAttribute('for')){
                draggable[i].classList.add("dragged");
              }
            })(i)
          }
      }

      function dragEnd(event) {
        for(var i = 1; i < draggable.length; i++){
          (function(i){
            if(document.getElementsByTagName('label')[i].getAttribute('for') == event.target.getElementsByTagName('label')[0].getAttribute('for')){
              draggable[i].classList.remove("dragged");
            }
          })(i)
        }
      }

      /* Drop target event handlers */
      function dragEnter(event) {
        droptarget.classList.remove("free");
        droptarget.classList.add("enter");
      }

      function dragOver(event) {

          event.preventDefault();
          return false; //Necessary to avoid default browsers behaviours
      }

      function dragLeave(event) {
        droptarget.classList.remove("enter");
        droptarget.classList.add("free");
      }

      function drop(event) {
          var data = event.dataTransfer.getData('text'); //reads the data set in dragStart()
          var url = "/api/ans/" + id + "/";
          var isGoodAnswer = 0;
          var choice = 0;

          droptarget.classList.remove("enter");

          for(var i = 1; i < draggable.length; i++){
            (function(i){
              if(document.getElementsByTagName('label')[i].getAttribute('for') == data){
                url += i-1;
                choice = draggable[i];
                choice.classList.add("hidden");
                event.target.innerHTML = data;
              }
            })(i)
          }

          console.log(url);

          $.get(url)
            .done(function(data) {
              isGoodAnswer = data.isGoodAnswer;
              console.log(isGoodAnswer);
              if(isGoodAnswer){
                droptarget.classList.add("right");
                //We indicate that the choosen answer is the good one
              }else{
                droptarget.classList.add("false");
                //We indicate that the the choosen answer is not the good one
              }

              //When an element is dropped, we need to remove draggable class and attribute on other items in order to avoid multiple d&d
              for(var j = 1; j < draggable.length; j++ ){
                if(draggable[j] != undefined){
                  (function(j){
                    draggable[j].removeEventListener("dragstart", dragStart);
                    draggable[j].removeEventListener("dragend", dragEnd);
                    draggable[j].setAttribute("draggable", "false");
                    draggable[j].classList.remove("draggable");
                  })(j)
                }
              }

              droptarget.removeEventListener("dragenter", dragEnter);
              droptarget.removeEventListener("dragover", dragOver);
              droptarget.removeEventListener("dragleave", dragLeave);
              droptarget.removeEventListener("drop", drop);

              event.preventDefault();
              return false; //Necessary to avoid default browsers behaviours
            });

      }
    }

    // ------------------------------------------------------------- DOM binding
    $(document).ready(changeQuestion);
    $nextQuestion.click(changeQuestion);
})();
<commit_msg>La bonne réponse est montrée lorsque l'utilisateur à valider une mauvaise réponse<commit_after>(function () {
  'use strict';

  // --------------------------------------------------- variable initialisation
  /*
   * HACK: we are passing a parameter to this scripts through a data-* balise.
   * more here: http://stackoverflow.com/a/32589923/6320039
   */
  var isExam = 'exam' == document.currentScript.getAttribute('data-id');

  var id = 0;

  // JQuery quick access to important nodes
  var $domain       = $('#domain');
  var $question     = $('#question');
  var $answers      = $('#answers');
  var $nextQuestion = $('#next-question');
  var $dashboard    = $('#dashboard');

  if (isExam) var counter = 0;

  // ---------------------------------------------------- main logic (functions)
  /**
   * Change DOM elements relative to a question :
   *  - question
   *  - domain
   *  - answers
   *
   * The question is randomly retrieved from the database. If the global
   * parameter isExam is set, then the question can be only in domains
   * contained in sessionStorage.domains; and it also increment the counter.
   * If the counter is greater than sessionStorage.numberOfQuestions, then exam
   * is over and window is redirected to /result.
   * @return undefined
   */
  function changeQuestion() {
    var url;
    if (isExam) {
      if (++counter == sessionStorage.numberOfQuestions)
        $nextQuestion.find('span').html('Fin de l’examen');
      else if (counter > sessionStorage.numberOfQuestions) {
        window.location = '/result';
        return;
      }
      url = "/api/ask/rand/" + sessionStorage.domains;
    } else {
      url = "/api/ask/rand/";
    }
    $.get(url)
      .done(function(data) {
        id = data.id;
        console.log(id);
        $domain.html(data.domain);
        $question.html(data.question);
        // clean everything except first answer (bones)
        $answers.find('.answer:not(:first)').remove()
        for (var answer of data.answers) {
          $answers
            // clone body of an answer
            .find('.answer:first')
            .clone()
            // append current answer elements to the clone
            .find('input')
              .attr('name', answer)
            .end()
            .find('label')
              .attr('for', answer)
              .html(answer)
            .end()
            // append the clone to DOM (#answer)
            .appendTo($answers)
            // show the clone
            .show();
        }

        dragndrop();
      })
      .fail(function (data) {
        console.log(data);
      });

    }

    function dragndrop(){
      var draggable = document.querySelectorAll(".answer");
      var droptarget = document.getElementById("droptarget");
      //draggable[0].classList.remove("right");

      droptarget.innerHTML = "Glisser la réponse !"
      droptarget.classList.remove("false");
      droptarget.classList.remove("right");
      droptarget.classList.add("free");

      for(var i = 1; i < draggable.length; i++){
        (function(i){
          draggable[i].classList.add("draggable");
          draggable[i].setAttribute("draggable", "true");
          draggable[i].addEventListener('dragstart', dragStart, false);  //the user starts dragging the element
          draggable[i].addEventListener('dragend'  , dragEnd  , false);
        })(i)
      }

      droptarget.addEventListener('dragenter', dragEnter  , false); //fired when the user drags the draggable onto the drop target (only fires when the draggable element changes from being outside to being over)
      droptarget.addEventListener('dragover' , dragOver   , false); //Fired once the draggable element is over the drop target and keeps firing for as long as the draggable element is being dragged over the drop target.
      droptarget.addEventListener('dragleave', dragLeave  , false); //If the user drags the draggable object out of the drop target again, the dragleave event is fired.
      droptarget.addEventListener('drop'     , drop       , false); //If the user drops the draggable object on the drop target, the drop event is fired.

      /* Draggable event handlers */
      function dragStart(event) {
          var dataToSet = event.target.getElementsByTagName('label')[0].getAttribute('for');
          event.dataTransfer.setData("text", dataToSet); //data that is transfered to the drop target when the element is dropped. (MIME, data)
          event.dataTransfer.effectsAllowed = "copy";

          for(var i = 1; i < draggable.length; i++){
            (function(i){
              if(document.getElementsByTagName('label')[i].getAttribute('for') == event.target.getElementsByTagName('label')[0].getAttribute('for')){
                draggable[i].classList.add("dragged");
              }
            })(i)
          }
      }

      function dragEnd(event) {
        for(var i = 1; i < draggable.length; i++){
          (function(i){
            if(document.getElementsByTagName('label')[i].getAttribute('for') == event.target.getElementsByTagName('label')[0].getAttribute('for')){
              draggable[i].classList.remove("dragged");
            }
          })(i)
        }
      }

      /* Drop target event handlers */
      function dragEnter(event) {
        droptarget.classList.remove("free");
        droptarget.classList.add("enter");
      }

      function dragOver(event) {

          event.preventDefault();
          return false; //Necessary to avoid default browsers behaviours
      }

      function dragLeave(event) {
        droptarget.classList.remove("enter");
        droptarget.classList.add("free");
      }

      function drop(event) {
          var data = event.dataTransfer.getData('text'); //reads the data set in dragStart()
          var url = "/api/ans/" + id + "/";
          var isGoodAnswer = 0;
          var indexAnswer = 0;
          var choice = 0;

          droptarget.classList.remove("enter");

          for(var i = 1; i < draggable.length; i++){
            (function(i){
              if(document.getElementsByTagName('label')[i].getAttribute('for') == data){
                url += i-1;
                choice = draggable[i];
                choice.classList.add("hidden");
                event.target.innerHTML = data;
              }
            })(i)
          }

          console.log(url);

          $.get(url)
            .done(function(data) {
              isGoodAnswer = data.isGoodAnswer;
              indexAnswer = data.goodAnswerIndex;
              console.log(isGoodAnswer);
              if(isGoodAnswer){
                droptarget.classList.add("right");
                //We indicate that the choosen answer is the good one
              }else{
                droptarget.classList.add("false");
                draggable[indexAnswer+1].classList.add("right");
                //We indicate that the the choosen answer is not the good one and we show the good one
              }

              //When an element is dropped, we need to remove draggable class and attribute on other items in order to avoid multiple d&d
              for(var j = 1; j < draggable.length; j++ ){
                if(draggable[j] != undefined){
                  (function(j){
                    draggable[j].removeEventListener("dragstart", dragStart);
                    draggable[j].removeEventListener("dragend", dragEnd);
                    draggable[j].setAttribute("draggable", "false");
                    draggable[j].classList.remove("draggable");
                  })(j)
                }
              }

              droptarget.removeEventListener("dragenter", dragEnter);
              droptarget.removeEventListener("dragover", dragOver);
              droptarget.removeEventListener("dragleave", dragLeave);
              droptarget.removeEventListener("drop", drop);

            });

            event.preventDefault();
            return false; //Necessary to avoid default browsers behaviours
      }
    }

    // ------------------------------------------------------------- DOM binding
    $(document).ready(changeQuestion);
    $nextQuestion.click(changeQuestion);
})();
<|endoftext|>


<commit_before>
var nconf = require('nconf');
var lodash = require('lodash');

permissions = {
	'isMe': 'Você não está autorizado a continuar.',
	'selfOwns': 'Ação não autorizada.',
	'selfDoesntOwn': 'Ação não autorizada.',
	'login': 'Ação não autorizada.',
	'isStaff': 'Ação não autorizada.',
	'isEditor': 'Ação não autorizada.',
}

Error.stackTraceLimit = 60

module.exports = function(err, req, res, next) {

	// wrong/abscent CSRF token
	if (err.code === "EBADCSRFTOKEN") {
		// Can't user renderError here!, because the method is only attached to the
		// res object after the csrf middleware is run.
		reg.logger.info("Auth error: Wrong CSRF token.");
		return res.status(401).send({ msg: "Erro de autenticação." });
	}

	// Check for errors of type 404
	if (err.type === 'ObsoleteId' //
		|| err.type === 'InvalidId' // Wrong ID format (FIXME: shoudl this be a 404?)
		|| (err.obj && err.obj.name === 'CastError' && err.obj.type == 'ObjectId') // failed to cast to _id
	) {
		// TODO? find way to detect while model type we couldn't find and customize 404 message.
		if (err.type === 'ObsoleteId') {
			return res.render404({ msg: 'Não encontramos o objeto que você estava procurando...'});
		}
		return res.render404(); // 'Esse usuário não existe.');
	}

	// Test permissions and don't trace/log them.
	if (err.permission) {
		res.status(403);
		if (err.permission === 'login') {
			if (~(req.headers.accept || '').indexOf('html')) {
				res.redirect('/');
			} else {
				// Don't use middleware.
				res.endJSON({ error: true, message: 'Unauthenticated user.' });
			}
			// Keep track of unauthorized access (lots of they may indicate a problem).
			req.logger.debug('IP '+req.connection.remoteAddress+' can\'t '+req.method+' path '+req.url);
			return;
		}

		if (err.permission in permissions) {
			res.renderError(403, {msg: permissions[err.permission]})
			return;
		}
		req.logger.warn('Permission '+err.permission+' not found in list.');
		res.renderError(403, {msg: 'Ação não autorizada.'});
		return;
	}

	// Test mongoose errors.
	if (err.name === 'ValidationError' || err.obj && err.obj.name === 'ValidationError') {
		res.renderError(400, {msg:'Não foi possível completar a sua ligação.'})
		return;
	}

	if (err.name === 'InternalOAuthError') {
		req.logger.info(err)
		console.trace();
		res.renderError(401, {msg: 'Não conseguimos te autenticar. Tente novamente.'})
		return;
	}

	if (err instanceof TypeError) {
		// May be express complaining of a url with invalid stuff (%A23 or whatever)
		// TODO: find a better way to distill the url problem from other TypeErrors!
		if (err.stack)
			req.logger.info(err.stack)
		console.trace();
		res.render404();
		return;
	}

	// Set status.
	if (err.status)
		res.status(err.status);
	else if (res.statusCode < 400)
		res.status(500);

	// hack to use middleware conditionally
	// require('express-bunyan-logger').errorLogger({
	// 	format: ':remote-address - - :method :url',
	// })(err, res, res, function(){});
	// app.use(require('express-bunyan-logger')({
	// 	format: ':remote-address - :user-agent[major] custom logger'
	// }));

	if (req.app.get('env') === 'production') {
		try {
			var newrelic = require('newrelic');
			newrelic.noticeError(err);
		} catch (e) {
			req.logger.warn('Failed to call newrelic.noticeError.', e);
		}
	}

	req.logger.fatal('Error detected:', err, err.args &&
		JSON.stringify(err.args.err && err.args.err.errors), lodash.keys(err), err.status);
	Error.stackTraceLimit = 60
	if (err.stack)
		req.logger.info(err.stack)
	console.trace();

	// from http://nodejs.org/api/domain.html#domain_warning_don_t_ignore_errors
	try {
		// Close server and force exit after 10 if CLUSTERING.
		if (nconf.get('env') === 'production' && process.env.__CLUSTERING) {
			req.app.preKill(10*1000);
		}

		// try to send error callback
		res.renderError(500, {
			error_code: res.statusCode,
			error_msg: err.msg,
			error_stack: (err.stack || '').split('\n').slice(1).join('
'),
			msg: err.human_message,
		});
	} catch (e) {
		// oh well, not much we can do at this point.
		res.end();
		req.logger.fatal('Failed to renderError. Empty response returned.', e);
		console.trace();
	}
}<commit_msg>Typo in errorHandler<commit_after>
var nconf = require('nconf');
var lodash = require('lodash');

permissions = {
	'isMe': 'Você não está autorizado a continuar.',
	'selfOwns': 'Ação não autorizada.',
	'selfDoesntOwn': 'Ação não autorizada.',
	'login': 'Ação não autorizada.',
	'isStaff': 'Ação não autorizada.',
	'isEditor': 'Ação não autorizada.',
}

Error.stackTraceLimit = 60

module.exports = function(err, req, res, next) {

	// wrong/abscent CSRF token
	if (err.code === "EBADCSRFTOKEN") {
		// Can't user renderError here!, because the method is only attached to the
		// res object after the csrf middleware is run.
		req.logger.info("Auth error: Wrong CSRF token.");
		return res.status(401).send({ msg: "Erro de autenticação." });
	}

	// Check for errors of type 404
	if (err.type === 'ObsoleteId' //
		|| err.type === 'InvalidId' // Wrong ID format (FIXME: shoudl this be a 404?)
		|| (err.obj && err.obj.name === 'CastError' && err.obj.type == 'ObjectId') // failed to cast to _id
	) {
		// TODO? find way to detect while model type we couldn't find and customize 404 message.
		if (err.type === 'ObsoleteId') {
			return res.render404({ msg: 'Não encontramos o objeto que você estava procurando...'});
		}
		return res.render404(); // 'Esse usuário não existe.');
	}

	// Test permissions and don't trace/log them.
	if (err.permission) {
		res.status(403);
		if (err.permission === 'login') {
			if (~(req.headers.accept || '').indexOf('html')) {
				res.redirect('/');
			} else {
				// Don't use middleware.
				res.endJSON({ error: true, message: 'Unauthenticated user.' });
			}
			// Keep track of unauthorized access (lots of they may indicate a problem).
			req.logger.debug('IP '+req.connection.remoteAddress+' can\'t '+req.method+' path '+req.url);
			return;
		}

		if (err.permission in permissions) {
			res.renderError(403, {msg: permissions[err.permission]})
			return;
		}
		req.logger.warn('Permission '+err.permission+' not found in list.');
		res.renderError(403, {msg: 'Ação não autorizada.'});
		return;
	}

	// Test mongoose errors.
	if (err.name === 'ValidationError' || err.obj && err.obj.name === 'ValidationError') {
		res.renderError(400, {msg:'Não foi possível completar a sua ligação.'})
		return;
	}

	if (err.name === 'InternalOAuthError') {
		req.logger.info(err)
		console.trace();
		res.renderError(401, {msg: 'Não conseguimos te autenticar. Tente novamente.'})
		return;
	}

	if (err instanceof TypeError) {
		// May be express complaining of a url with invalid stuff (%A23 or whatever)
		// TODO: find a better way to distill the url problem from other TypeErrors!
		if (err.stack)
			req.logger.info(err.stack)
		console.trace();
		res.render404();
		return;
	}

	// Set status.
	if (err.status)
		res.status(err.status);
	else if (res.statusCode < 400)
		res.status(500);

	// hack to use middleware conditionally
	// require('express-bunyan-logger').errorLogger({
	// 	format: ':remote-address - - :method :url',
	// })(err, res, res, function(){});
	// app.use(require('express-bunyan-logger')({
	// 	format: ':remote-address - :user-agent[major] custom logger'
	// }));

	if (req.app.get('env') === 'production') {
		try {
			var newrelic = require('newrelic');
			newrelic.noticeError(err);
		} catch (e) {
			req.logger.warn('Failed to call newrelic.noticeError.', e);
		}
	}

	req.logger.fatal('Error detected:', err, err.args &&
		JSON.stringify(err.args.err && err.args.err.errors), lodash.keys(err), err.status);
	Error.stackTraceLimit = 60
	if (err.stack)
		req.logger.info(err.stack)
	console.trace();

	// from http://nodejs.org/api/domain.html#domain_warning_don_t_ignore_errors
	try {
		// Close server and force exit after 10 if CLUSTERING.
		if (nconf.get('env') === 'production' && process.env.__CLUSTERING) {
			req.app.preKill(10*1000);
		}

		// try to send error callback
		res.renderError(500, {
			error_code: res.statusCode,
			error_msg: err.msg,
			error_stack: (err.stack || '').split('\n').slice(1).join('
'),
			msg: err.human_message,
		});
	} catch (e) {
		// oh well, not much we can do at this point.
		res.end();
		req.logger.fatal('Failed to renderError. Empty response returned.', e);
		console.trace();
	}
}<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var keys     = require('./../secrets.json');
var mongo_url;

// BEFORE DEPLOY MAKE SURE YOU ARE USING THE REMOTE DB
mongo_url = process.env.MONGOURL
// mongo_url = 'mongodb://localhost/livebots_dev';

require('./models/bots');
require('./models/commands');

module.exports = function() {
  mongoose.connect(mongo_url);
  var db = mongoose.connection;

  db.on('error', console.error.bind(console, 'connection error:'));
  db.once('open', function (){
    console.log('Successfuly connected to mongoDB');
  });
};<commit_msg>added how to deploy<commit_after>var mongoose = require('mongoose');
var mongo_url;

mongo_url = process.env.MONGOURL
// mongo_url = 'mongodb://localhost/livebots_dev';

require('./models/bots');
require('./models/commands');

module.exports = function() {
  mongoose.connect(mongo_url);
  var db = mongoose.connection;

  db.on('error', console.error.bind(console, 'connection error:'));
  db.once('open', function (){
    console.log('Successfuly connected to mongoDB');
  });
};<|endoftext|>


<commit_before>/**
 * Combobox that searches from LM with type ahead.
 */
Ext.define('OpenEMap.form.SearchRegisterenhet', {
    extend : 'Ext.form.field.ComboBox',
    alias: 'widget.searchregisterenhet',
    require: ['Ext.data.*',
              'Ext.form.*'],
    initComponent : function() {
        var registeromrade;
        var zoom;
        if (this.search && this.search.options){
            registeromrade = this.search.options.municipalities.join(',');
            zoom = this.search.options.zoom;
        }
        var layer = this.mapPanel.searchLayer;

        function doSearch(id) {
            this.mapPanel.setLoading(true);
            this.mapPanel.searchLayer.destroyFeatures();
            OpenEMap.requestLM({
                url: 'registerenheter/' + id + '/enhetsomraden?',
                success: function(response) {
                    this.resultPanel.expand();
                    var features = new OpenLayers.Format.GeoJSON().read(response.responseText);
                    layer.addFeatures(features);
                    var extent = layer.getDataExtent();
                    if (zoom) {
                        this.mapPanel.map.setCenter(extent.getCenterLonLat(), zoom);
                    } else {
                        this.mapPanel.map.zoomToExtent(extent);
                    }
                },
                failure: function() {
                    Ext.Msg.alert('Fel', 'Ingen träff.');
                },
                callback: function() {
                    this.mapPanel.setLoading(false);
                },
                scope: this
            });
        }

        this.store = Ext.create('Ext.data.Store', {
            proxy: {
                type: 'ajax',
                url : OpenEMap.basePathLM + 'registerenheter',
                extraParams: {
                    lmuser: OpenEMap.lmUser
                },
                reader: {
                    type: 'json',
                    root: 'features'
                }
            },
            fields: [
                 {name: 'id', mapping: 'properties.objid'},
                 {name: 'name', mapping: 'properties.name'}
             ]
        });

        this.labelWidth = 60;
        this.displayField = 'name';
        this.valueField = 'id';
        this.queryParam = 'q';
        this.typeAhead = true;
        this.forceSelection = true;

        this.listeners = {
            'select':  function(combo, records) {
                var id = records[0].get('id');
                doSearch.call(this, id);
            },
            'beforequery': function(queryPlan) {
                if (registeromrade && queryPlan.query.match(registeromrade) === null) {
                    queryPlan.query = registeromrade + ' ' + queryPlan.query;
                }
            },
            scope: this
        };

        this.callParent(arguments);
    }
});
<commit_msg>Change from default delay to 800 ms (#91)<commit_after>/**
 * Combobox that searches from LM with type ahead.
 */
Ext.define('OpenEMap.form.SearchRegisterenhet', {
    extend : 'Ext.form.field.ComboBox',
    alias: 'widget.searchregisterenhet',
    require: ['Ext.data.*',
              'Ext.form.*'],
    queryDelay: 800,
    initComponent : function() {
        var registeromrade;
        var zoom;
        if (this.search && this.search.options){
            registeromrade = this.search.options.municipalities.join(',');
            zoom = this.search.options.zoom;
        }
        var layer = this.mapPanel.searchLayer;

        function doSearch(id) {
            this.mapPanel.setLoading(true);
            this.mapPanel.searchLayer.destroyFeatures();
            OpenEMap.requestLM({
                url: 'registerenheter/' + id + '/enhetsomraden?',
                success: function(response) {
                    this.resultPanel.expand();
                    var features = new OpenLayers.Format.GeoJSON().read(response.responseText);
                    layer.addFeatures(features);
                    var extent = layer.getDataExtent();
                    if (zoom) {
                        this.mapPanel.map.setCenter(extent.getCenterLonLat(), zoom);
                    } else {
                        this.mapPanel.map.zoomToExtent(extent);
                    }
                },
                failure: function() {
                    Ext.Msg.alert('Fel', 'Ingen träff.');
                },
                callback: function() {
                    this.mapPanel.setLoading(false);
                },
                scope: this
            });
        }

        this.store = Ext.create('Ext.data.Store', {
            proxy: {
                type: 'ajax',
                url : OpenEMap.basePathLM + 'registerenheter',
                extraParams: {
                    lmuser: OpenEMap.lmUser
                },
                reader: {
                    type: 'json',
                    root: 'features'
                }
            },
            fields: [
                 {name: 'id', mapping: 'properties.objid'},
                 {name: 'name', mapping: 'properties.name'}
             ]
        });

        this.labelWidth = 60;
        this.displayField = 'name';
        this.valueField = 'id';
        this.queryParam = 'q';
        this.typeAhead = true;
        this.forceSelection = true;

        this.listeners = {
            'select':  function(combo, records) {
                var id = records[0].get('id');
                doSearch.call(this, id);
            },
            'beforequery': function(queryPlan) {
                if (registeromrade && queryPlan.query.match(registeromrade) === null) {
                    queryPlan.query = registeromrade + ' ' + queryPlan.query;
                }
            },
            scope: this
        };

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


<commit_before>function soramame(source){
  // ソースコード
  this.source = source;

  // 文の終端記号
  this.CRLF0 = ["\n", "\r", "。"];

  // 文の終端記号
  var pat_CRLF = "(。|\n|\r)+";
  var pat_CRLF2 = "。";
  this.CRLF = new RegExp("^" + pat_CRLF);
  this.CRLF3 = new RegExp(pat_CRLF);

  //行コメント
　　var pat_comment_line = "\/\/";
  this.comment_line = new RegExp("^" + pat_comment_line);

  //関数定義
　　var pat_def_function = "---";
  this.def_function = new RegExp("^" + pat_def_function);

  // 助詞
  var pat_josi = "[はのとにでを]";	//助詞の判定用
  var pat_josi2 = "はのとにでを";	//助詞以外の判定用
  this.josi = new RegExp("^" + pat_josi);

  // 文字列リテラル
  var pat_kakko = "(「.*」|『.*』)";
  var pat_kakko2 = "「」『』";
  this.string_literal = new RegExp("^" + pat_kakko);

  // 数字
  var pat_num2 = "0123456789０１２３４５６７８９";

 　// 記号
  var pat_symbol2 = "\*=\+\-\/%^\(\)\[\\]{}@!&|<>\.,:＝＋－×＊÷／％＾（）［］｛｝．、：＠！＆｜＜＞";

  //単語(識別子)
  var pat_word1 = "[^" + pat_josi2 + pat_kakko2 + pat_symbol2 + pat_CRLF2 + pat_num2 + "]";
  var pat_word2 = "[^" + pat_josi2 + pat_kakko2 + pat_symbol2 + pat_CRLF2 + "]";
  this.word = new RegExp("^" + pat_word1 + pat_word2 + "*");

  // その他
  this.yylval;
  this.Escreen = document.getElementById("screen");
  this.debug_clean();
}

soramame.prototype.yylex = function(){
  var retval = WORD;

    // 文の終端を読み飛ばす
  while(this.isCRLF(this.source.charAt(0))){
    this.source = this.source.substring(1);
  }

/*   // 文の終端を読み飛ばす
  var p = this.source.match(this.CRCF);
  if (p != null) {
	this.source = this.source.substring(p[0].length);
  } */

  //スペース(全角、半角)とタブを読み飛ばす
  p = this.source.match(/^[\s　]+/);
  if (p != null) {
	this.source = this.source.substring(p[0].length);
  }

  // 1文を取り出す
  var line = this.source;
  var l = this.CRLF0.length;
  for(var i = 0; i < l; i++){
    var CRLF0 = this.CRLF0[i];
    var p = this.source.indexOf(CRLF0);
    if(p > 0){
      line = this.source.substring(0, p);
    }
  }

/*   // 1文を取り出す
  var line = this.source;
  var p = line.match(this.CRLF3);
  if (p != null) {
	line = line.substring(0, p[0].index);
  } */

  //行コメント
  p = line.match(this.comment_line);
  if (p != null) {
    var index = line.indexOf("\n");
	if (index != "-1") {
		line = line.substr(0, index);
	}
	this.source = this.source.substr(line.length);
	this.yylval= line + "";
	return COMMENT;
  }

  // 文字列
  p = line.match(this.string_literal);
  if (p != null) {
  	var bracket = "'";
    if (p[0].substring(0,1) == "『") {
		bracket = '"';
	}
	var line = bracket + p[0].substring(1, p[0].length - 1) + bracket;

	this.source = this.source.substring(p[0].length);
    this.yylval = line + "";
	return STRING;
  }

  // 関数定義
  p = line.match(this.def_function);
  if (p != null) {
	var def_function = p[0];
	this.source = this.source.substring(def_function.length);
    this.yylval = def_function + "";
	return DEF_FUNC;
  }

  // 助詞
  p = line.match(this.josi);
  if (p != null) {
	var josi = p[0];
	this.source = this.source.substring(josi.length);
    this.yylval = josi + "";
	return JOSI;
  }

  // 数字
  if(this.isdigit(line.charAt(0))){
    var token = '';
    var l = line.length;
    for(var i = 0; i < l; i++){
      var c = this.isdigit(line.charAt(i));
      if(!c){
        break;
      }
      token += c;
    }
    this.source = this.source.substring(i);
    this.yylval = token - 0;
	return NUMBER;
  }

  // 記号
  var c = this.issymbol(line.charAt(0));
  if(c){
    this.source = this.source.substring(1);
    this.yylval = c;
    return c.charCodeAt(0);
  }

  // 単語
  var token = line.match(this.word);
  if(token != null){
    token = String(token[0]);
  } else {
    token = "";
  }
  if(token){
    this.source = this.source.substring(token.length);
  } else {
    token = line;
    this.source = this.source.substring(line.length);
  }
  this.yylval = token;
  if(!token){
    retval = 0;
  }
  return retval;
  /*
  this.debug("line = "+line);
  this.debug("token.length = "+token.length);
  this.debug("this.source = "+this.source);
  this.debug("this.source = "+this.source);
  */
}

soramame.prototype.isCRLF = function(c){
  var l = this.CRLF0.length;
  for(var i = 0; i < l; i++){
    if(c == this.CRLF0[i]){
      return true;
    }
  }
  return false;
}

soramame.prototype.isdigit = function(c){
  if('0' <= c && c <= '9'){
    return c;
  }
  if('０' <= c && c <= '９'){
    return this.zen2han(c);
  }
  if(c == '.'){
    return c;
  }
  if(c == '．'){
    return this.zen2han(c);
  }
  return false;
}

soramame.prototype.issymbol = function(c){
  switch(c){
  case "=":
  case "+":
  case "-":
  case "*":
  case "/":
  case "^":
  case "(":
  case ")":
  case "[":
  case "]":
  case "{":
  case "}":
  case ",":
  case ":":
  case "@":
  case "!":
  case "&":
  case "|":
  case "<":
  case ">":
    return c;

  case "＝":
  case "＋":
  case "－":
  case "×":
  case "＊":
  case "÷":
  case "／":
  case "％":
  case "＾":
  case "（":
  case "）":
  case "［":
  case "］":
  case "｛":
  case "｝":
  case "、":
  case "：":
  case "＠":
  case "！":
  case "＆":
  case "｜":
  case "＜":
  case "＞":
  return this.zen2han(c);
  }

  switch(c.charCodeAt(0)){
  case 65288:
    return c;
    return this.zen2han(c);
  }

  return false;
}

soramame.prototype.zen2han = function(c){
  var hankaku = "0123456789=+-**//%^()[]{}.,:@!&|<>";
  var zenkaku = "０１２３４５６７８９＝＋－×＊÷／％＾（）［］｛｝．、：＠！＆｜＜＞";
  return hankaku.charAt(zenkaku.indexOf(c));
}

soramame.prototype.debug = function(str){
  str = str.replace(/\</g, "&lt");
  str = str.replace(/\>/g, "&gt");
  this.Escreen.innerHTML += str+"
\n";
}

soramame.prototype.debug_clean = function(){
  this.Escreen.innerHTML = '';
}
<commit_msg>関数定義を、予約語の検出に切り替え中。<commit_after>function soramame(source){
  // ソースコード
  this.source = source;

  // 文の終端記号
  this.CRLF0 = ["\n", "\r", "。"];

  // 文の終端記号
  var pat_CRLF = "(。|\n|\r)+";
  var pat_CRLF2 = "。";
  this.CRLF = new RegExp("^" + pat_CRLF);
  this.CRLF3 = new RegExp(pat_CRLF);

  //行コメント
　　var pat_comment_line = "\/\/";
  this.comment_line = new RegExp("^" + pat_comment_line);

  //予約語
　　var pat_yoyaku = "---";
  this.yoyaku = new RegExp("^" + pat_yoyaku);

  // 助詞
  var pat_josi = "[はのとにでを]";	//助詞の判定用
  var pat_josi2 = "はのとにでを";	//助詞以外の判定用
  this.josi = new RegExp("^" + pat_josi);

  // 文字列リテラル
  var pat_kakko = "(「.*」|『.*』)";
  var pat_kakko2 = "「」『』";
  this.string_literal = new RegExp("^" + pat_kakko);

  // 数字
  var pat_num2 = "0123456789０１２３４５６７８９";

 　// 記号
  var pat_symbol2 = "\*=\+\-\/%^\(\)\[\\]{}@!&|<>\.,:＝＋－×＊÷／％＾（）［］｛｝．、：＠！＆｜＜＞";

  //単語(識別子)
  var pat_word1 = "[^" + pat_josi2 + pat_kakko2 + pat_symbol2 + pat_CRLF2 + pat_num2 + "]";
  var pat_word2 = "[^" + pat_josi2 + pat_kakko2 + pat_symbol2 + pat_CRLF2 + "]";
  this.word = new RegExp("^" + pat_word1 + pat_word2 + "*");

  // その他
  this.yylval;
  this.Escreen = document.getElementById("screen");
  this.debug_clean();
}

soramame.prototype.yylex = function(){
  var retval = WORD;

    // 文の終端を読み飛ばす
  while(this.isCRLF(this.source.charAt(0))){
    this.source = this.source.substring(1);
  }

/*   // 文の終端を読み飛ばす
  var p = this.source.match(this.CRCF);
  if (p != null) {
	this.source = this.source.substring(p[0].length);
  } */

  //スペース(全角、半角)とタブを読み飛ばす
  p = this.source.match(/^[\s　]+/);
  if (p != null) {
	this.source = this.source.substring(p[0].length);
  }

  // 1文を取り出す
  var line = this.source;
  var l = this.CRLF0.length;
  for(var i = 0; i < l; i++){
    var CRLF0 = this.CRLF0[i];
    var p = this.source.indexOf(CRLF0);
    if(p > 0){
      line = this.source.substring(0, p);
    }
  }

/*   // 1文を取り出す
  var line = this.source;
  var p = line.match(this.CRLF3);
  if (p != null) {
	line = line.substring(0, p[0].index);
  } */

  //行コメント
  p = line.match(this.comment_line);
  if (p != null) {
    var index = line.indexOf("\n");
	if (index != "-1") {
		line = line.substr(0, index);
	}
	this.source = this.source.substr(line.length);
	this.yylval= line + "";
	return COMMENT;
  }

  // 文字列
  p = line.match(this.string_literal);
  if (p != null) {
  	var bracket = "'";
    if (p[0].substring(0,1) == "『") {
		bracket = '"';
	}
	var line = bracket + p[0].substring(1, p[0].length - 1) + bracket;

	this.source = this.source.substring(p[0].length);
    this.yylval = line + "";
	return STRING;
  }

  // 予約語
  p = line.match(this.yoyaku);
  if (p != null) {
	var yoyaku = p[0];
	this.source = this.source.substring(yoyaku.length);
    this.yylval = yoyaku + "";
	var yoyaku_token;
	switch(this.yylval){
		case '---':
			yoyaku_token = DEF_FUNC;
			break;
	}
	return yoyaku_token;
  }

  // 助詞
  p = line.match(this.josi);
  if (p != null) {
	var josi = p[0];
	this.source = this.source.substring(josi.length);
    this.yylval = josi + "";
	return JOSI;
  }

  // 数字
  if(this.isdigit(line.charAt(0))){
    var token = '';
    var l = line.length;
    for(var i = 0; i < l; i++){
      var c = this.isdigit(line.charAt(i));
      if(!c){
        break;
      }
      token += c;
    }
    this.source = this.source.substring(i);
    this.yylval = token - 0;
	return NUMBER;
  }

  // 記号
  var c = this.issymbol(line.charAt(0));
  if(c){
    this.source = this.source.substring(1);
    this.yylval = c;
    return c.charCodeAt(0);
  }

  // 単語
  var token = line.match(this.word);
  if(token != null){
    token = String(token[0]);
  } else {
    token = "";
  }
  if(token){
    this.source = this.source.substring(token.length);
  } else {
    token = line;
    this.source = this.source.substring(line.length);
  }
  this.yylval = token;
  if(!token){
    retval = 0;
  }
  return retval;
  /*
  this.debug("line = "+line);
  this.debug("token.length = "+token.length);
  this.debug("this.source = "+this.source);
  this.debug("this.source = "+this.source);
  */
}

soramame.prototype.isCRLF = function(c){
  var l = this.CRLF0.length;
  for(var i = 0; i < l; i++){
    if(c == this.CRLF0[i]){
      return true;
    }
  }
  return false;
}

soramame.prototype.isdigit = function(c){
  if('0' <= c && c <= '9'){
    return c;
  }
  if('０' <= c && c <= '９'){
    return this.zen2han(c);
  }
  if(c == '.'){
    return c;
  }
  if(c == '．'){
    return this.zen2han(c);
  }
  return false;
}

soramame.prototype.issymbol = function(c){
  switch(c){
  case "=":
  case "+":
  case "-":
  case "*":
  case "/":
  case "^":
  case "(":
  case ")":
  case "[":
  case "]":
  case "{":
  case "}":
  case ",":
  case ":":
  case "@":
  case "!":
  case "&":
  case "|":
  case "<":
  case ">":
    return c;

  case "＝":
  case "＋":
  case "－":
  case "×":
  case "＊":
  case "÷":
  case "／":
  case "％":
  case "＾":
  case "（":
  case "）":
  case "［":
  case "］":
  case "｛":
  case "｝":
  case "、":
  case "：":
  case "＠":
  case "！":
  case "＆":
  case "｜":
  case "＜":
  case "＞":
  return this.zen2han(c);
  }

  switch(c.charCodeAt(0)){
  case 65288:
    return c;
    return this.zen2han(c);
  }

  return false;
}

soramame.prototype.zen2han = function(c){
  var hankaku = "0123456789=+-**//%^()[]{}.,:@!&|<>";
  var zenkaku = "０１２３４５６７８９＝＋－×＊÷／％＾（）［］｛｝．、：＠！＆｜＜＞";
  return hankaku.charAt(zenkaku.indexOf(c));
}

soramame.prototype.debug = function(str){
  str = str.replace(/\</g, "&lt");
  str = str.replace(/\>/g, "&gt");
  this.Escreen.innerHTML += str+"
\n";
}

soramame.prototype.debug_clean = function(){
  this.Escreen.innerHTML = '';
}
<|endoftext|>


<commit_before>/**
 * Created by chendi on 9/3/16.
 */
var mkdirp = require('mkdirp');
var fs = require('fs');
var app = require('../../app');
var path = require ('path');
var del = require('del');
var File = require('../Models/File');

/**
 * Get user file directory, if directory not exists then create one
 *
 * @param userID
 * @return directory path
 * */
var getUserDirectory = function(userID) {
    var userDirPath = generateUserDirPath(userID);
    if(!dirExists(userDirPath)) {
        createDirectory(userDirPath);
    }
    return userDirPath;
};

/**
 * Get the stardard path of a user directory
 *
 * @param userID
 * @return directory path
 * */
var generateUserDirPath = function(userID) {
    var USER_FILE_PATH = app.get('userFiles');
    return path.join(USER_FILE_PATH, userID);
};

/**
 * Check if a directory exists
 *
 * @param directory path
 * @return <boolean>
 * */
var dirExists = function(userDirPath) {
    try {
        fs.accessSync(userDirPath, fs.F_OK, function(){});
        return true;
    } catch (e) {
        return false;
    }
};

/**
 * Create directory
 *
 * Create directory, do nothing if directory already exists
 *
 * @param directory path
 * @return void
 * */
var createDirectory = function(path) {
    mkdirp.sync(path, function(err) {
        throw "Cannot create path" + err;
    });
};

/**
 * Create User directory
 *
 * Create user directory, do nothing if directory already exists
 *
 * @param userID
 * @return void
 * */
var createUserDirectory = function(userID) {
    var userDirPath = generateUserDirPath(userID);
    if(!dirExists(userDirPath)) {
        createDirectory(userDirPath);
    }
};

/**
 * Remove Directory
 *
 * @param directory path
 * @return void
 * */
var removeDirectory = function(path) {
    del.sync(path, function(err) {
        console.log(err);
    })
};

/**
 * Remove User Directory
 *
 * Remove a user's file directory and all the files inside
 *
 * @param userID
 * @return void
 * */
var removeUserDirectory = function(userID) {
    var userFileDirPath = generateUserDirPath(userID);
    removeDirectory(userFileDirPath);
};

/**
 * File filter
 *
 * @param mimeType
 * @return boolean
 * */
var isValidFileTypeUpload = function(mimeType) {
    return mimeType == 'application/pdf' || mimeType == 'image/jpeg';
};

/**
 * Save File to database
 *
 * @param userID
 * @filepath filepath
 * @return void
 * */
var saveFileInfoToDatabase = function(userID, fileName, fileOriginalName, fileMimeType, filePath) {
    File.create(
        {
            name: fileName,
            mimeType: fileMimeType,
            filePath: filePath,
            userID: userID
        }
    );
};

var getAllUserFiles = function(userID) {
    return File.getAllUserFiles(userID).then(function(result) {
        return result;
    })
};

module.exports.getUserDirectory = getUserDirectory;
module.exports.generateUserDirPath = generateUserDirPath;
module.exports.dirExists = dirExists;
module.exports.createDirectory = createDirectory;
module.exports.removeDirectory = removeDirectory;
module.exports.removeUserDirectory = removeUserDirectory;
module.exports.createUserDirectory = createUserDirectory;
module.exports.isValidFileTypeUpload = isValidFileTypeUpload;
module.exports.saveFileInfoToDatabase = saveFileInfoToDatabase;
module.exports.getAllUserFiles = getAllUserFiles;<commit_msg>fix file sys test<commit_after>/**
 * Created by chendi on 9/3/16.
 */
var mkdirp = require('mkdirp');
var fs = require('fs');
var app = require('../../app');
var path = require ('path');
var del = require('del');
var File = require('../models/File');

/**
 * Get user file directory, if directory not exists then create one
 *
 * @param userID
 * @return directory path
 * */
var getUserDirectory = function(userID) {
    var userDirPath = generateUserDirPath(userID);
    if(!dirExists(userDirPath)) {
        createDirectory(userDirPath);
    }
    return userDirPath;
};

/**
 * Get the stardard path of a user directory
 *
 * @param userID
 * @return directory path
 * */
var generateUserDirPath = function(userID) {
    var USER_FILE_PATH = app.get('userFiles');
    return path.join(USER_FILE_PATH, userID);
};

/**
 * Check if a directory exists
 *
 * @param directory path
 * @return <boolean>
 * */
var dirExists = function(userDirPath) {
    try {
        fs.accessSync(userDirPath, fs.F_OK, function(){});
        return true;
    } catch (e) {
        return false;
    }
};

/**
 * Create directory
 *
 * Create directory, do nothing if directory already exists
 *
 * @param directory path
 * @return void
 * */
var createDirectory = function(path) {
    mkdirp.sync(path, function(err) {
        throw "Cannot create path" + err;
    });
};

/**
 * Create User directory
 *
 * Create user directory, do nothing if directory already exists
 *
 * @param userID
 * @return void
 * */
var createUserDirectory = function(userID) {
    var userDirPath = generateUserDirPath(userID);
    if(!dirExists(userDirPath)) {
        createDirectory(userDirPath);
    }
};

/**
 * Remove Directory
 *
 * @param directory path
 * @return void
 * */
var removeDirectory = function(path) {
    del.sync(path, function(err) {
        console.log(err);
    })
};

/**
 * Remove User Directory
 *
 * Remove a user's file directory and all the files inside
 *
 * @param userID
 * @return void
 * */
var removeUserDirectory = function(userID) {
    var userFileDirPath = generateUserDirPath(userID);
    removeDirectory(userFileDirPath);
};

/**
 * File filter
 *
 * @param mimeType
 * @return boolean
 * */
var isValidFileTypeUpload = function(mimeType) {
    return mimeType == 'application/pdf' || mimeType == 'image/jpeg';
};

/**
 * Save File to database
 *
 * @param userID
 * @filepath filepath
 * @return void
 * */
var saveFileInfoToDatabase = function(userID, fileName, fileOriginalName, fileMimeType, filePath) {
    File.create(
        {
            name: fileName,
            mimeType: fileMimeType,
            filePath: filePath,
            userID: userID
        }
    );
};

var getAllUserFiles = function(userID) {
    return File.getAllUserFiles(userID).then(function(result) {
        return result;
    })
};

module.exports.getUserDirectory = getUserDirectory;
module.exports.generateUserDirPath = generateUserDirPath;
module.exports.dirExists = dirExists;
module.exports.createDirectory = createDirectory;
module.exports.removeDirectory = removeDirectory;
module.exports.removeUserDirectory = removeUserDirectory;
module.exports.createUserDirectory = createUserDirectory;
module.exports.isValidFileTypeUpload = isValidFileTypeUpload;
module.exports.saveFileInfoToDatabase = saveFileInfoToDatabase;
module.exports.getAllUserFiles = getAllUserFiles;<|endoftext|>


<commit_before>
MAP_SIZE = 50;
CSIZE = 900;

/* Based on the formulae:
 * xS = (xW-zW)cos(a)s
 * yS = ((xW+zW)sin(a)-yW)s
 */
var get_coords = function(x, y, z, s){
	return [(x-z) * 0.8944 *s, ((x+z) * 0.4472 - y)*s]
}

var drawHeightField = function(canv,plotf){
	var midx = CSIZE/2;
	var midy = CSIZE/4;

	var inset = (canv.width - CSIZE)/2;
	var top = canv.height - CSIZE/2 - inset;
	//Draw grid
	var ctx = canv.getContext('2d');
	ctx.fillStyle = "#222";
	tile_size = Math.sqrt(0.375) * CSIZE;
/*
	ctx.beginPath();
	ctx.moveTo(midx, top + midy*2);
	ctx.lineTo(CSIZE, top +midy);
	ctx.lineTo(midx, top);
	ctx.lineTo(0, top + midy)
	ctx.closePath();
	ctx.stroke();
*/
	for (var i = 0; i<MAP_SIZE; i++){
		for(var j = 0; j<MAP_SIZE; j++){
			var c = get_coords(i, 0, j, tile_size/MAP_SIZE);
			plotf([inset + midx + c[0], top + c[1]],  Math.sqrt(5) * ( tile_size/MAP_SIZE));
		}
	}

}

$(function(){

	var canv = $("#isocanv")[0];
	var ctx = canv.getContext('2d');
	ctx.fillStyle = "#eee";
	ctx.fillRect (0, 0, screen.width, screen.height);

	var point = function(c, s){
		var g = $('#grass')[0];
		var t = $('#tree')[0];
		var t2 = $('#tree2')[0];
		var r = $('#rock')[0];

		var x = Math.random() > 0.95 ? t : Math.random() > 0.95 ? Math.random() >0.5 ? r : t2 : g;
		ctx.drawImage(x, c[0]-s/2, c[1] - s* x.height/x.width , s,s * x.height/x.width);
		ctx.fillRect(c[0], c[1], 1, 1);
	}

	drawHeightField(canv, point);
});

<commit_msg>WIP on iometric canvas<commit_after>
MAP_SIZE = 50;
CSIZE = 900;

/* Based on the formulae:
 * xS = (xW-zW)cos(a)s
 * yS = ((xW+zW)sin(a)-yW)s
 */
var get_coords = function(x, y, z, s){
	return [(x-z) * 0.8944 *s, ((x+z) * 0.4472 - y)*s]
}

var drawHeightField = function(canv, plotf, heightf){
	var midx = CSIZE/2;
	var midy = CSIZE/4;

	var inset = (canv.width - CSIZE)/2; //Allows border round edge
	var top = canv.height - CSIZE/2 - inset; //border on top

	var ctx = canv.getContext('2d');
	ctx.fillStyle = "#222";
	var tile_size = Math.sqrt(0.375) * CSIZE;

	for (var i = 0; i<MAP_SIZE; i++){
		for(var j = 0; j<MAP_SIZE; j++){
			var c = get_coords(i, heightf(i,j), j, tile_size/MAP_SIZE);
			plotf(i, j, [inset + midx + c[0], top + c[1]],  Math.sqrt(5) * ( tile_size/MAP_SIZE));
		}
	}

}

var generateMap = function(){
	map = new Array(MAP_SIZE*MAP_SIZE);
	for (var i = 0; i<map.length; i++){
		var x = Math.random() > 0.95 ?
			'tree' : Math.random() > 0.95 ?
				Math.random() >0.5 ? 'rock'
				: 'tree2'
			: 'grass';
		map[i] = {
			height:0,
			terrain:x,
			open:true,
		}
	}

	return map;
}

$(function(){

	var canv = $("#isocanv")[0];
	var ctx = canv.getContext('2d');
	ctx.fillStyle = "#eee";
	ctx.fillRect (0, 0, screen.width, screen.height);

	var MAP = generateMap();

	var point = function(x, y, c, s){
		var x = $('#' + MAP[parseInt(x + y*MAP_SIZE)]['terrain'])[0];
		ctx.drawImage(
			x,
			c[0]-s/2, c[1] - s* x.height/x.width,
			s, s * x.height/x.width
			);
		//ctx.fillRect(c[0], c[1], 1, 1);
	}

	var heightf = function(x, y){return MAP[parseInt(x + y*MAP_SIZE)]['height'];}

	drawHeightField(canv, point, heightf);
});

<|endoftext|>


<commit_before>/* global angular, FB, BASE_URL */
angular.module('i-like-solar').factory('fb',
  function ($rootScope, $http) {
    'use strict';

    var appId = '582937771761901';

    FB.init({
      appId: appId,
      channelUrl: BASE_URL + '/channel.html',
      status: true,
      xfbml: true
    });

    function getLoginStatus(cb) {
      FB.getLoginStatus(function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function login(cb, perms) {
      var obj = null;
      if (perms) obj = { scope: perms };

      FB.login(function (res) {
        cb(res);
        $rootScope.$apply();
      }, obj);
    }

    function getUser(cb) {
      FB.api('/me', function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function getCoverUrl(cb) {
      FB.api('/me', { width: '851', height: '315', fields: 'cover' }, function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function getProfileUrl(cb) {
      FB.api('/me/picture', {width: '250', height: '250', fields: 'pic_crop'}, function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function createProfilePhoto(url, id, cb) {
      $http.post(BASE_URL + '/createProfilePhoto', {
        url: url,
        id: id
      }).then(function (res) {
        cb(res.data);
      });
    }

    function createCoverPhoto(url, id, cb) {
      $http.post(BASE_URL + '/createCoverPhoto', {
        url: url,
        id: id
      }).then(function (res) {
        cb(res.data);
      });
    }

    function uploadPhoto(url, cb) {
      if (url.indexOf('//local') === 0)
        url = 'http://www.seia.org:3000/img/profile.jpg';
      else
        url = 'http:' + url;
      if (url.indexOf(':4000') !== -1)
        url = url.replace(':4000', ':3000');
      FB.api('/me/photos', 'post', {
        no_story: 1,
        url: url
      }, function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function ui(publish, cb) {
      publish.appId = appId;
      FB.ui(publish, function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

	function revokelogin() {
		FB.api('/me/permissions', 'delete', function(response) {
    	console.log(response); // true
		});
	}

    return {
      getLoginStatus:     getLoginStatus,
      login:              login,
      getUser:            getUser,
      getProfileUrl:      getProfileUrl,
      getCoverUrl:        getCoverUrl,
      createProfilePhoto: createProfilePhoto,
      createCoverPhoto:   createCoverPhoto,
      uploadPhoto:        uploadPhoto,
      ui:                 ui,
      revokelogin:        revokelogin
    };
  }
);

<commit_msg>profile pic size fix<commit_after>/* global angular, FB, BASE_URL */
angular.module('i-like-solar').factory('fb',
  function ($rootScope, $http) {
    'use strict';

    var appId = '582937771761901';

    FB.init({
      appId: appId,
      channelUrl: BASE_URL + '/channel.html',
      status: true,
      xfbml: true
    });

    function getLoginStatus(cb) {
      FB.getLoginStatus(function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function login(cb, perms) {
      var obj = null;
      if (perms) obj = { scope: perms };

      FB.login(function (res) {
        cb(res);
        $rootScope.$apply();
      }, obj);
    }

    function getUser(cb) {
      FB.api('/me', function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function getCoverUrl(cb) {
      FB.api('/me', { width: '851', height: '315', fields: 'cover' }, function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function getProfileUrl(cb) {
      FB.api('/me/picture', {width: '200', height: '200', type: 'normal'}, function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function createProfilePhoto(url, id, cb) {
      $http.post(BASE_URL + '/createProfilePhoto', {
        url: url,
        id: id
      }).then(function (res) {
        cb(res.data);
      });
    }

    function createCoverPhoto(url, id, cb) {
      $http.post(BASE_URL + '/createCoverPhoto', {
        url: url,
        id: id
      }).then(function (res) {
        cb(res.data);
      });
    }

    function uploadPhoto(url, cb) {
      if (url.indexOf('//local') === 0)
        url = 'http://www.seia.org:3000/img/profile.jpg';
      else
        url = 'http:' + url;
      if (url.indexOf(':4000') !== -1)
        url = url.replace(':4000', ':3000');
      FB.api('/me/photos', 'post', {
        no_story: 1,
        url: url
      }, function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function ui(publish, cb) {
      publish.appId = appId;
      FB.ui(publish, function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

	function revokelogin() {
		FB.api('/me/permissions', 'delete', function(response) {
    	console.log(response); // true
		});
	}

    return {
      getLoginStatus:     getLoginStatus,
      login:              login,
      getUser:            getUser,
      getProfileUrl:      getProfileUrl,
      getCoverUrl:        getCoverUrl,
      createProfilePhoto: createProfilePhoto,
      createCoverPhoto:   createCoverPhoto,
      uploadPhoto:        uploadPhoto,
      ui:                 ui,
      revokelogin:        revokelogin
    };
  }
);

<|endoftext|>


<commit_before>'use strict';
/*!
 * AngularJS app
 * Version: 1
 *
 * Copyright 2016 Janaagraha.
 *
 * Author: Jeeva D <jeevananthamcse@gmail.com>
 * Related to project of Swachh Bharath
 */
/**
 * declare 'swach-app' module with dependencies
 */
angular.module("pm-app", [
    'ngAnimate',
    'ui.router',
    'ui.bootstrap',
    'oc.lazyLoad',
    'cfp.loadingBar',
    'toaster',
    'ngMaterial',
]);
// Declare app level module which depends on filters, and services
var app = angular.module('pmApp', ['pm-app']);
///* Set request header */
//app.config(['$httpProvider', function ($httpProvider) {
//        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
//    }]);
app.config(['$interpolateProvider', function ($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
  }]);

app.factory('BearerAuthInterceptor', function ($window, $q) {
    return {
        request: function (config) {
            config.headers = config.headers || {};
            if ($window.localStorage.getItem('token')) {
                // may also use sessionStorage
                config.headers.Authorization = 'Bearer ' + $window.localStorage.getItem('token');
            }
            return config || $q.when(config);
        },
        response: function (response) {
            return response || $q.when(response);
        },
        responseError: function (rejection) {
            // do something on error

            if (rejection.status == 401)  {
                //$rootScope.signOut();
                console.log(statusText);
            }

            return $q.reject(rejection);
        }
    };
});

// Register the previously created AuthInterceptor.
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('BearerAuthInterceptor');

});
app.run(['$rootScope', '$state', '$stateParams', 'Data', '$window',
    function ($rootScope, $state, $stateParams, Data, $window) {

        // Set some reference to access them from any scope
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;

        // GLOBAL APP SCOPE
        // set below basic information
        $rootScope.app = {
            name: 'SBM', // name of your project
            author: 'Janaagraha', // author's name or company name
            description: 'Angular Bootstrap Admin Template', // brief description
            version: '2.0', // current version
            year: ((new Date()).getFullYear()), // automatic current year (for copyright information)
            isMobile: (function () {// true if the browser is a mobile device
                var check = false;
                if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
                    check = true;
                }
                ;
                return check;
            })(),
            layout: {
                isNavbarFixed: true, //true if you want to initialize the template with fixed header
                isSidebarFixed: true, // true if you want to initialize the template with fixed sidebar
                isSidebarClosed: false, // true if you want to initialize the template with closed sidebar
                isFooterFixed: false, // true if you want to initialize the template with fixed footer
                theme: 'theme-1', // indicate the theme chosen for your project
                logo: 'assets/images/logo.png', // relative path of the project logo
            }
        };

        $rootScope.user = {
            name: 'Peter',
            job: 'ng-Dev',
            picture: 'app/img/user/02.jpg'
        };

        $rootScope.$on("$stateChangeStart", function (event, next, current) {
            $rootScope.authenticated = false;
            return;
            Data.get('Authenticate/check_session').then(function (results) {
                if (results.id) {
                    $rootScope.authenticated = true;
                    $rootScope.uid = results.id;
                    $rootScope.name = results.full_name;
                    $rootScope.role_id = results.role_id;
                    //$location.path('dashboard');
                    //$state.go();
                } else {
                    //var nextUrl = next.$$route.originalPath;
                    //$state.go('login');
                    $window.location.href = '/login';
//                        if (nextUrl == '/signup' || nextUrl == '/login') {
//
//                        } else {
//                            //$location.path("/login");
//                            //$window.location.href = '/login';
//                            $state.go('login');
//                        }
                }
            });
        });

    }]);

<commit_msg>Removed ngMaterial module<commit_after>'use strict';
/*!
 * AngularJS app
 * Version: 1
 *
 * Copyright 2016 Janaagraha.
 *
 * Author: Jeeva D <jeevananthamcse@gmail.com>
 * Related to project of Swachh Bharath
 */
/**
 * declare 'swach-app' module with dependencies
 */
angular.module("pm-app", [
    'ngAnimate',
    'ui.router',
    'ui.bootstrap',
    'oc.lazyLoad',
    'cfp.loadingBar',
    'toaster',
    //'ngMaterial',
]);
// Declare app level module which depends on filters, and services
var app = angular.module('pmApp', ['pm-app']);
///* Set request header */
//app.config(['$httpProvider', function ($httpProvider) {
//        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
//    }]);
app.config(['$interpolateProvider', function ($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
  }]);

app.factory('BearerAuthInterceptor', function ($window, $q) {
    return {
        request: function (config) {
            config.headers = config.headers || {};
            if ($window.localStorage.getItem('token')) {
                // may also use sessionStorage
                config.headers.Authorization = 'Bearer ' + $window.localStorage.getItem('token');
            }
            return config || $q.when(config);
        },
        response: function (response) {
            return response || $q.when(response);
        },
        responseError: function (rejection) {
            // do something on error

            if (rejection.status == 401)  {
                //$rootScope.signOut();
                console.log(statusText);
            }

            return $q.reject(rejection);
        }
    };
});

// Register the previously created AuthInterceptor.
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('BearerAuthInterceptor');

});
app.run(['$rootScope', '$state', '$stateParams', 'Data', '$window',
    function ($rootScope, $state, $stateParams, Data, $window) {

        // Set some reference to access them from any scope
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;

        // GLOBAL APP SCOPE
        // set below basic information
        $rootScope.app = {
            name: 'SBM', // name of your project
            author: 'Janaagraha', // author's name or company name
            description: 'Angular Bootstrap Admin Template', // brief description
            version: '2.0', // current version
            year: ((new Date()).getFullYear()), // automatic current year (for copyright information)
            isMobile: (function () {// true if the browser is a mobile device
                var check = false;
                if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
                    check = true;
                }
                ;
                return check;
            })(),
            layout: {
                isNavbarFixed: true, //true if you want to initialize the template with fixed header
                isSidebarFixed: true, // true if you want to initialize the template with fixed sidebar
                isSidebarClosed: false, // true if you want to initialize the template with closed sidebar
                isFooterFixed: false, // true if you want to initialize the template with fixed footer
                theme: 'theme-1', // indicate the theme chosen for your project
                logo: 'assets/images/logo.png', // relative path of the project logo
            }
        };

        $rootScope.user = {
            name: 'Peter',
            job: 'ng-Dev',
            picture: 'app/img/user/02.jpg'
        };

        $rootScope.$on("$stateChangeStart", function (event, next, current) {
            $rootScope.authenticated = false;
            return;
            Data.get('Authenticate/check_session').then(function (results) {
                if (results.id) {
                    $rootScope.authenticated = true;
                    $rootScope.uid = results.id;
                    $rootScope.name = results.full_name;
                    $rootScope.role_id = results.role_id;
                    //$location.path('dashboard');
                    //$state.go();
                } else {
                    //var nextUrl = next.$$route.originalPath;
                    //$state.go('login');
                    $window.location.href = '/login';
//                        if (nextUrl == '/signup' || nextUrl == '/login') {
//
//                        } else {
//                            //$location.path("/login");
//                            //$window.location.href = '/login';
//                            $state.go('login');
//                        }
                }
            });
        });

    }]);

<|endoftext|>


<commit_before>
var r = require('rethinkdb');
var service = require('../Service');

r.connect({
    host: 'localhost',
    port: 28015,
    db: 'FJCU'
}, function (err, conneciton){

    if(err){
        console.log(err);
        process.exit();
    }

    global.connection = conneciton;
    r.table('people').changes().run(global.connection, function (err, cursor) {
        cursor.each(function (err, row) {

            if(err){
                console.log(err);
                process.exit();
            }

            console.log(row);

            service.emit('insertData', { data: row } );
        });
    });
});
<commit_msg>fix bug<commit_after>
var r = require('rethinkdb');
var service = require('../service');

r.connect({
    host: 'localhost',
    port: 28015,
    db: 'FJCU'
}, function (err, conneciton){

    if(err){
        console.log(err);
        process.exit();
    }

    global.connection = conneciton;
    r.table('people').changes().run(global.connection, function (err, cursor) {
        cursor.each(function (err, row) {

            if(err){
                console.log(err);
                process.exit();
            }

            console.log(row);

            service.emit('insertData', { data: row } );
        });
    });
});
<|endoftext|>


<commit_before>define(
  'ephox.alloy.toolbar.ToolbarSpecs',

  [
    'ephox.boulder.api.FieldPresence',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.ValueSchema',
    'ephox.compass.Arr',
    'ephox.highway.Merger',
    'ephox.peanut.Fun'
  ],

  function (FieldPresence, FieldSchema, ValueSchema, Arr, Merger, Fun) {
    var itemSchema = ValueSchema.choose(
      'type',
      {
        button: [
          FieldSchema.state('builder', function (raw) {
            return function (info) {
              return Merger.deepMerge(raw, {
                uiType: 'button',
                tabstopping: undefined,
                focusing: true
              });
            };
          })
        ]
      }
    );

    // TODO: Standardise all of these.
    var groupSchema = ValueSchema.objOf([
      FieldSchema.option('label'),
      FieldSchema.field(
        'components',
        'components',
        FieldPresence.strict(),
        ValueSchema.arrOf(itemSchema)
      )
    ]);

    var toolbarSchema = ValueSchema.objOf([
      FieldSchema.option('label'),
      FieldSchema.field(
        'groups',
        'groups',
        FieldPresence.strict(),
        ValueSchema.arrOf(
          groupSchema
        )
      )
    ]);

    var buildItem = function (compInfo) {
      return compInfo.builder()(compInfo);
    };

    var buildGroup = function (group) {
      return {
        uiType: 'custom',
        dom: {
          tag: 'div',
          styles: {
            display: 'flex'
          },
          // FIX:
          classes: [ 'ephox-chameleon-toolbar-group' ]
        },
        keying: {
          mode: 'flow',
          selector: '.toolbar-group-item'
        },
        tabstopping: true,
        // GOTCHAs. False won't do anything. Fix this so we don't have to pass "undefined"
        focusing: undefined,
        components: Arr.map(group.components(), buildItem)
      };
    };

    return {
      buildGroup: buildGroup,
      buildItem: buildItem,
      groupSchema: Fun.constant(groupSchema),
      toolbarSchema: Fun.constant(toolbarSchema)
    };
  }
);<commit_msg>VAN-44-wheel: adding custom type<commit_after>define(
  'ephox.alloy.toolbar.ToolbarSpecs',

  [
    'ephox.boulder.api.FieldPresence',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.ValueSchema',
    'ephox.compass.Arr',
    'ephox.highway.Merger',
    'ephox.peanut.Fun'
  ],

  function (FieldPresence, FieldSchema, ValueSchema, Arr, Merger, Fun) {
    var itemSchema = ValueSchema.choose(
      'type',
      {
        button: [
          FieldSchema.state('builder', function (raw) {
            return function (info) {
              return Merger.deepMerge(raw, {
                uiType: 'button',
                tabstopping: undefined,
                focusing: true
              });
            };
          })
        ],
        custom: [
          FieldSchema.state('builder', function (raw) {
            return function (_) {
              return Merger.deepMerge(raw, {
                uiType: 'custom'
              });
            };
          })
        ]
      }
    );

    // TODO: Standardise all of these.
    var groupSchema = ValueSchema.objOf([
      FieldSchema.option('label'),
      FieldSchema.field(
        'components',
        'components',
        FieldPresence.strict(),
        ValueSchema.arrOf(itemSchema)
      )
    ]);

    var toolbarSchema = ValueSchema.objOf([
      FieldSchema.option('label'),
      FieldSchema.field(
        'groups',
        'groups',
        FieldPresence.strict(),
        ValueSchema.arrOf(
          groupSchema
        )
      )
    ]);

    var buildItem = function (compInfo) {
      return compInfo.builder()(compInfo);
    };

    var buildGroup = function (group) {
      return {
        uiType: 'custom',
        dom: {
          tag: 'div',
          styles: {
            display: 'flex'
          },
          // FIX:
          classes: [ 'ephox-chameleon-toolbar-group' ]
        },
        keying: {
          mode: 'flow',
          selector: '.toolbar-group-item'
        },
        tabstopping: true,
        // GOTCHAs. False won't do anything. Fix this so we don't have to pass "undefined"
        focusing: undefined,
        components: Arr.map(group.components(), buildItem)
      };
    };

    return {
      buildGroup: buildGroup,
      buildItem: buildItem,
      groupSchema: Fun.constant(groupSchema),
      toolbarSchema: Fun.constant(toolbarSchema)
    };
  }
);<|endoftext|>


<commit_before>/**
 * CORS middleware
 * see: http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-nodejs
 */

module.exports = function cors() {
    return function(req, res, next) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
        res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
        res.header('Cache-Control', 'private, max-age=0');
        res.header('Expires', new Date().toUTCString());

        if ('OPTIONS' === req.method) {
            res.send(200);
        } else {
            next();
        }
    }
};
<commit_msg>Fixed linting error<commit_after>/**
 * CORS middleware
 * see: http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-nodejs
 */

module.exports = function cors() {
    return function(req, res, next) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
        res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
        res.header('Cache-Control', 'private, max-age=0');
        res.header('Expires', new Date().toUTCString());

        if ('OPTIONS' === req.method) {
            res.send(200);
        } else {
            next();
        }
    };
};
<|endoftext|>