<commit_before>/**
 * @fileoverview Driver script for speech processing.
 * @author aravart@cs.wisc.edu (Ara Vartanian)
 */
goog.provide('SpeechGames');

goog.require('Blockly.Workspace');
goog.require('SpeechBlocks.Controller');
goog.require('SpeechBlocks.Interpreter');
goog.require('Turtle.Answers');

/**
 * A global reference to the current workspace's controller.
 * @public {SpeechBlocks.Controller}
 */
SpeechGames.controller = null;

/**
 * A global reference to the workspace itself.
 * @public {Blockly.Workspace}
 */
SpeechGames.workspace = null;

/**
 * Extracts a parameter from the URL.
 * If the parameter is absent default_value is returned.
 * @param {string} name The name of the parameter.
 * @param {string} defaultValue Value to return if paramater not found.
 * @return {string} The parameter value or the default value if not found.
 */
SpeechGames.getStringParamFromUrl = function(name, defaultValue) {
  var val =
      window.location.search.match(new RegExp('[?&]' + name + '=([^&]+)'));
  return val ? decodeURIComponent(val[1].replace(/\+/g, '%20')) : defaultValue;
};

/**
 * Extracts a numeric parameter from the URL.
 * If the parameter is absent or less than min_value, min_value is
 * returned.  If it is greater than max_value, max_value is returned.
 * @param {string} name The name of the parameter.
 * @param {number} minValue The minimum legal value.
 * @param {number} maxValue The maximum legal value.
 * @return {number} A number in the range [min_value, max_value].
 */
SpeechGames.getNumberParamFromUrl = function(name, minValue, maxValue) {
  var val = Number(SpeechGames.getStringParamFromUrl(name, 'NaN'));
  return isNaN(val) ? minValue : goog.math.clamp(minValue, val, maxValue);
};

/**
 * Maximum number of levels.  Common to all apps.
 * @public @const
 */
SpeechGames.MAX_LEVEL = 12;

/**
 * User's current level (e.g. 5).
 * @public
 */
SpeechGames.LEVEL =
    SpeechGames.getNumberParamFromUrl('level', 1, SpeechGames.MAX_LEVEL);

/**
 * Bind a function to a button's click event.
 * On touch-enabled browsers, ontouchend is treated as equivalent to onclick.
 * @param {!Element|string} el Button element or ID thereof.
 * @param {!Function} func Event handler to bind.
 */
SpeechGames.bindClick = function(el, func) {
  if (typeof el == 'string') {
    el = document.getElementById(el);
  }
  el.addEventListener('click', func, true);
  el.addEventListener('touchend', func, true);
};

// Initialize microphone and speech handling.
$(document).ready(function() {
  SpeechGames.speech = new SpeechGames.Speech();
  SpeechGames.controller = SpeechBlocks.Controller.injectIntoDiv('blocklyDiv', {
    media: 'lib/google-blockly/media/',
    trashcan: false,
    scrollbars: false,
    toolbox: document.getElementById('toolbox')
  });
  SpeechGames.interpreter = new SpeechBlocks.Interpreter(SpeechGames.controller);
  SpeechGames.workspace = SpeechGames.controller.workspace_;

  if(!getParameterByName('debug')) {
    $('#debug').hide();
  }

  if(!getParameterByName('demo')) {
    SpeechGames.speech.awake = true;
  } else {
    SpeechGames.speech.demoMode = true;
    SpeechGames.speech.awake = false;
    SpeechGames.speech.setMicInterval();
    console.log("demo mode");
  }
  if (getParameterByName('level')) {
    SpeechGames.speech.awake = true;
  }
   $('#q')
    .change(SpeechGames.speech.scheduleParse.bind(SpeechGames.speech))
    .mousedown(SpeechGames.speech.scheduleParse.bind(SpeechGames.speech))
    .mouseup(SpeechGames.speech.scheduleParse.bind(SpeechGames.speech))
    .click(SpeechGames.speech.scheduleParse.bind(SpeechGames.speech))
    .keydown(SpeechGames.speech.scheduleParse.bind(SpeechGames.speech))
    .keyup(SpeechGames.speech.scheduleParse.bind(SpeechGames.speech))
    .keypress(SpeechGames.speech.scheduleParse.bind(SpeechGames.speech));

  $('#microphone')
      .click(SpeechGames.speech.toggleDictation.bind(SpeechGames.speech));
  if (SpeechGames.speech.demoMode && !SpeechGames.speech.awake) {
     $("#user-message").hide().text("Say 'Hey Jerry' to wake me up.").fadeIn(500);
  } else {
    $("#user-message").hide().text("Awaiting your command!").fadeIn(500);
  }

  // $('#runButton').on('click', run);
  // $('#showButton').on('click', showCode);

  $('#debugButton').on('click', function() {
    $('#debug').toggle();
  });
  $('#buttonRow').hide();
  $('#levelDescription').text(Turtle.descriptions[SpeechGames.LEVEL]);
});

SpeechGames.Speech = function() {
    this.oldQ = null;
    this.parseTimer = null;
    this.previousRecognitionTime = null;
    this.output = null;
    this.timeout = null;
    this.animating = false;
    this.demoMode = false;
    this.awake = false;
    this.listening = false;
    this.recognition = null;
    this.mic_animate = 'https://www.google.com/intl/en/chrome/assets/common/images/content/mic-animate.gif';
    this.mic = 'https://www.google.com/intl/en/chrome/assets/common/images/content/mic.gif';
    this.parseTimer = null;
};

SpeechGames.Speech.prototype.setMicInterval = function() {
  if (!window.location.origin.includes("file")) {
    if (this.interval) {
      clearInterval(this.interval);
    }
    this.interval = setInterval(function() {
      if (!this.listening) {
        this.listening = true;
        this.startDictation();
      }
    }.bind(this), 100);
  } else {
    console.log("Cannot use speech from local files!");
  }
};

SpeechGames.Speech.prototype.speechCorrections = function(speech) {
  speech = speech.toLowerCase();
  speech = speech.replace(/\bqueens\b/, 'please');
  speech = speech.replace(/\bfreeze out\b/, 'please add');
  speech = speech.replace(/\bhave\b/, 'add');
  speech = speech.replace(/\bhad\b/, 'add');
  speech = speech.replace(/\batom\b/, 'add a');
  speech = speech.replace(/\bad a\b/, 'add a');
  speech = speech.replace(/\badam\b/, 'add a');
  speech = speech.replace(/\badam's\b/, 'add a');
  speech = speech.replace(/\bcut\b/, 'put');
  speech = speech.replace(/\bport\b/, 'put');
  speech = speech.replace(/\bfoot\b/, 'put');
  speech = speech.replace(/\bfort\b/, 'put');
  speech = speech.replace(/\bwalk\b/, 'block');
  speech = speech.replace(/\bblack\b/, 'block');
  speech = speech.replace(/\block\b/, 'block');
  speech = speech.replace(/\badd remove\b/, 'add a move');
  speech = speech.replace(/\badam block\b/, 'add a move block');
  speech = speech.replace(/\bnew block\b/, 'move block');
  speech = speech.replace(/\broof\b/, 'move');
  speech = speech.replace(/\broom\b/, 'move')
  speech = speech.replace(/\bflu\b/, 'move');;
  speech = speech.replace(/\bnerve\b/, 'move');
  speech = speech.replace(/\bfuse block\b/, 'move block');
  speech = speech.replace(/\bbroccoli\b/, 'block 3');
  speech = speech.replace(/\bnumber to\b/, 'number 2');
  speech = speech.replace(/\bone\b/, '1');
  speech = speech.replace(/\btwo\b/, '2');
  speech = speech.replace(/\bthree\b/, '3');
  speech = speech.replace(/\b425\b/, '4 to 5');
  speech = speech.replace(/\bblock to\b/, 'block 2');
  speech = speech.replace(/\bblock what\b/, 'block 1');
  speech = speech.replace(/\bblock won\b/, 'block 1');
  speech = speech.replace(/\bunblock\b/, 'in block');
  speech = speech.replace(/\bterm\b/, 'turn');
  speech = speech.replace(/\b - \b/, ' to ');
  speech = speech.replace(/\b272\b/, 'to 72');
  return speech;
};

SpeechGames.Speech.prototype.startDictation = function() {
  if (window.hasOwnProperty('webkitSpeechRecognition')) {
    if (this.recognition) {
      this.recognition.stop();
    }
    this.recognition = new webkitSpeechRecognition();
    this.recognition.continuous = false;
    this.recognition.interimResults = false;
    this.recognition.lang = 'en-US';

    this.recognition.onstart = function() {
      console.log("started");
      this.listening = true;
      if (!this.animating) {
        this.animating = true;
        document.getElementById('microphone').src = this.mic_animate;
      }
    }.bind(this);

    this.recognition.onresult = function(e) {
      var unfiltered = e.results[0][0].transcript;
      var corrections = this.speechCorrections(unfiltered);
      $("#q").val(corrections);
      this.recognition.stop();
      this.parseSpeech();
    }.bind(this);

    this.recognition.onerror = function(e) {
      console.log('error');
      this.listening = false;
     }.bind(this);

    this.recognition.onend = function(e)  {
      console.log('end');
      this.listening = false;
    }.bind(this);

    this.recognition.start();
  }
};

SpeechGames.Speech.prototype.toggleDictation = function() {
  if (this.listening) {
    this.listening = !this.listening;
    this.recognition.stop();
    this.recognition = null;
    this.animating = false;
    document.getElementById('microphone').src = this.mic;
    clearInterval(this.interval);
    this.interval = null;
  } else {
    document.getElementById('microphone').src = this.mic_animate;
    this.setMicInterval();
  }
};

SpeechGames.Speech.prototype.checkHeyJerry = function() {
  if (this.awake || this.speech === "hey jerry" || (this.speech.includes("h") || this.speech.includes("j") || this.speech.includes("a"))) {
    this.awake = true;
    return true;
  } else {
    return false;
  }
};

SpeechGames.Speech.prototype.buildErrorMessage = function(e) {
  return e.location !== undefined ? 'Line ' + e.location.start.line + ', column ' + e.location.start.column + ': ' + e.message : e.message;
};

SpeechGames.Speech.prototype.parseSpeech = function() {
  this.previousRecognitionTime = Date.now();
  this.oldQ = $('#q').val();
  $('#parse-message').attr('class', 'message progress').text('Parsing the input...');
  $('#output').addClass('disabled').text('Output not available.');
  var result = false;
  this.speech = "";
  try {
    this.speech = $('#q').val().toLowerCase();
    console.log(this.speech);
    if (!this.awake && this.demoMode) {
      this.checkHeyJerry();
      if (this.awake) {
        $('#user-message').hide().text("Awaiting your command!").fadeIn(200);
        $("#q").val("");
        return;
      } else {
        $("#user-message").hide().text("Say 'Hey Jerry' to wake me up.").fadeIn(500);
        $("#q").val("");
        return;
      }
    }
    this.output = parser.parse(this.speech);
    console.log(this.output);
    $('#parse-message')
          .attr('class', 'message info')
          .text('Input parsed successfully.');
    $('#output').removeClass('disabled').text(jsDump.parse(this.output));
    this.response = this.interpretSpeech();
    clearTimeout(this.timeout);
    this.result = true;
    $("#user-message").hide().text(this.response).fadeIn(200);
    $("#q").val("");
  } catch (e) {
    console.log(e);
    if(e instanceof SpeechBlocks.UserError) {
      $('#user-message').text(e.message);
    } else {
      $('#parse-message').attr('class', 'message error').text(this.buildErrorMessage(e));
      if(this.speech !== '') {
        $('#user-message').hide().text('Sorry, I didn\'t understand \"' + this.speech + '\"').fadeIn(200);
        $("#q").val("");
        clearTimeout(this.timeout);
        this.timeout = setTimeout(function(){
          $('#user-message').hide().text("Awaiting your command!").fadeIn(200);
        }.bind(this), 5000);
      }
    }
  }
  return result;
};

SpeechGames.Speech.prototype.interpretSpeech = function() {
  if (this.output !== null) {
    return SpeechGames.interpreter.interpret(this.output);
  }
};

SpeechGames.Speech.prototype.scheduleParse = function() {
  if ($('#q').val() === this.oldQ) {
    return;
  }

  if (this.parseTimer !== null) {
    clearTimeout(this.parseTimer);
    this.parseTimer = null;
  }

  this.parseTimer = setTimeout(function() {
    this.parseSpeech();
    this.parseTimer = null;
  }.bind(this), 1000);
};

// utility functions
function createCode() {
  Blockly.JavaScript.addReservedWords('code');
  return Blockly.JavaScript.workspaceToCode(SpeechGames.workspace);
}

function showCode() {
  var modalEl = document.createElement('generatedCode');
  modalEl.style.width = '400px';
  modalEl.style.height = '300px';
  modalEl.style.margin = '100px auto';
  modalEl.style.backgroundColor = '#ff';
  modalEl.textContent = createCode();
  mui.overlay('on', modalEl);
}

function getParameterByName(name, url) {
  if (!url) {
    url = window.location.href;
  }
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
      results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
<commit_msg>Closure commenting, rearrangement, renaming<commit_after>/**
 * @fileoverview Driver script for speech processing.
 * @author aravart@cs.wisc.edu (Ara Vartanian), dliang@wisc.edu (David Liang)
 */
goog.provide('SpeechGames');
goog.provide('SpeechGames.Speech');

goog.require('Blockly.Workspace');
goog.require('SpeechBlocks.Controller');
goog.require('SpeechBlocks.Interpreter');
goog.require('Turtle.Answers');

/**
 * A global reference to the current workspace's controller.
 * @public {SpeechBlocks.Controller}
 */
SpeechGames.controller = null;

/**
 * A global reference to the workspace itself.
 * @public {Blockly.Workspace}
 */
SpeechGames.workspace = null;

/**
 * A global reference to the interpreter.
 * @public {Blockly.Interpreter}
 */
SpeechGames.interpreter = null;

/**
 * Maximum number of levels.  Common to all apps.
 * @public @const
 */
SpeechGames.MAX_LEVEL = 12;

/**
 * User's current level (e.g. 5).
 * @public
 */
SpeechGames.LEVEL = null;

/**
 * Bind a function to a button's click event.
 * On touch-enabled browsers, ontouchend is treated as equivalent to onclick.
 * @param {!Element|string} el Button element or ID thereof.
 * @param {!Function} func Event handler to bind.
 * @public
 */
SpeechGames.bindClick = function(el, func) {
  if (typeof el == 'string') {
    el = document.getElementById(el);
  }
  el.addEventListener('click', func, true);
  el.addEventListener('touchend', func, true);
};

/**
 * Instantiates a speech object, used for controlling speech input to interpreter.
 * @public
 * @constructor
 */
SpeechGames.Speech = function() {
    this.oldQ = null;
    this.parseTimer = null;
    this.previousRecognitionTime = null;
    this.output = null;
    this.timeout = null;
    this.animating = false;
    this.demoMode = false;
    this.awake = false;
    this.listening = false;
    this.recognition = null;
    this.mic_animate = 'https://www.google.com/intl/en/chrome/assets/common/images/content/mic-animate.gif';
    this.mic = 'https://www.google.com/intl/en/chrome/assets/common/images/content/mic.gif';
    this.parseTimer = null;
};

/**
 * Sets the interval that ensures the mic is lietning (when applicable).
 * @private
 */
SpeechGames.Speech.prototype.setMicInterval_ = function() {
  if (!window.location.origin.includes("file")) {
    if (this.interval) {
      clearInterval(this.interval);
    }
    this.interval = setInterval(function() {
      if (!this.listening) {
        this.listening = true;
        this.startDictation_();
      }
    }.bind(this), 100);
  } else {
    console.log("Cannot use speech from local files!");
  }
};

/**
 * Hard replacements for certain phrases.
 * @param {string} speech Utterance to be corrected.
 * @return {string} The corrected utterance.
 * @private
 */
SpeechGames.Speech.prototype.speechCorrections_ = function(speech) {
  //TODO: Perhaps replace this with a better system, possibly by finding nearest neighbor?
  speech = speech.toLowerCase();
  speech = speech.replace(/\bqueens\b/, 'please');
  speech = speech.replace(/\bfreeze out\b/, 'please add');
  speech = speech.replace(/\bhave\b/, 'add');
  speech = speech.replace(/\bhad\b/, 'add');
  speech = speech.replace(/\batom\b/, 'add a');
  speech = speech.replace(/\bad a\b/, 'add a');
  speech = speech.replace(/\badam\b/, 'add a');
  speech = speech.replace(/\badam's\b/, 'add a');
  speech = speech.replace(/\bcut\b/, 'put');
  speech = speech.replace(/\bport\b/, 'put');
  speech = speech.replace(/\bfoot\b/, 'put');
  speech = speech.replace(/\bfort\b/, 'put');
  speech = speech.replace(/\bwalk\b/, 'block');
  speech = speech.replace(/\bblack\b/, 'block');
  speech = speech.replace(/\block\b/, 'block');
  speech = speech.replace(/\badd remove\b/, 'add a move');
  speech = speech.replace(/\badam block\b/, 'add a move block');
  speech = speech.replace(/\bnew block\b/, 'move block');
  speech = speech.replace(/\broof\b/, 'move');
  speech = speech.replace(/\broom\b/, 'move')
  speech = speech.replace(/\bflu\b/, 'move');;
  speech = speech.replace(/\bnerve\b/, 'move');
  speech = speech.replace(/\bfuse block\b/, 'move block');
  speech = speech.replace(/\bbroccoli\b/, 'block 3');
  speech = speech.replace(/\bnumber to\b/, 'number 2');
  speech = speech.replace(/\bone\b/, '1');
  speech = speech.replace(/\btwo\b/, '2');
  speech = speech.replace(/\bthree\b/, '3');
  speech = speech.replace(/\b425\b/, '4 to 5');
  speech = speech.replace(/\bblock to\b/, 'block 2');
  speech = speech.replace(/\bblock what\b/, 'block 1');
  speech = speech.replace(/\bblock won\b/, 'block 1');
  speech = speech.replace(/\bunblock\b/, 'in block');
  speech = speech.replace(/\bterm\b/, 'turn');
  speech = speech.replace(/\b - \b/, ' to ');
  speech = speech.replace(/\b272\b/, 'to 72');
  return speech;
};

/**
 * Restarts the listening for a new utterance.
 * @private
 */
SpeechGames.Speech.prototype.startDictation_ = function() {
  if (window.hasOwnProperty('webkitSpeechRecognition')) {
    if (this.recognition) {
      this.recognition.stop();
    }
    this.recognition = new webkitSpeechRecognition();
    this.recognition.continuous = false;
    this.recognition.interimResults = false;
    this.recognition.lang = 'en-US';

    this.recognition.onstart = function() {
      console.log("started");
      this.listening = true;
      if (!this.animating) {
        this.animating = true;
        document.getElementById('microphone').src = this.mic_animate;
      }
    }.bind(this);

    this.recognition.onresult = function(e) {
      var unfiltered = e.results[0][0].transcript;
      var corrections = this.speechCorrections_(unfiltered);
      $("#q").val(corrections);
      this.recognition.stop();
      this.parseSpeech_();
    }.bind(this);

    this.recognition.onerror = function(e) {
      console.log('error');
      this.listening = false;
     }.bind(this);

    this.recognition.onend = function(e)  {
      console.log('end');
      this.listening = false;
    }.bind(this);

    this.recognition.start();
  }
};

/**
 * Toggles the listening from the microphone.
 * @private
 */
SpeechGames.Speech.prototype.toggleDictation_ = function() {
  if (this.listening) {
    this.listening = !this.listening;
    this.recognition.stop();
    this.recognition = null;
    this.animating = false;
    document.getElementById('microphone').src = this.mic;
    clearInterval(this.interval);
    this.interval = null;
  } else {
    document.getElementById('microphone').src = this.mic_animate;
    this.setMicInterval_();
  }
};

/**
 * Checks to see if 'Hey Jerry' has been said yet.
 * @return {boolean} True if Hey Jerry has been said yet, else false.
 * @private
 */
SpeechGames.Speech.prototype.checkHeyJerry_ = function() {
  if (this.awake || this.speech === "hey jerry" || (this.speech.includes("h") || this.speech.includes("j") || this.speech.includes("a"))) {
    this.awake = true;
    return true;
  } else {
    return false;
  }
};

/**
 * Parses the input and sends the result to SpeechGames.interpreter. Then outputs the response
 * to the user interface.
 * @private
 */
SpeechGames.Speech.prototype.parseSpeech_ = function() {
  this.previousRecognitionTime = Date.now();
  this.oldQ = $('#q').val();
  $('#parse-message').attr('class', 'message progress').text('Parsing the input...');
  $('#output').addClass('disabled').text('Output not available.');
  var result = false;
  this.speech = "";
  try {
    this.speech = $('#q').val().toLowerCase();
    console.log(this.speech);
    if (!this.awake && this.demoMode) {
      this.checkHeyJerry_();
      if (this.awake) {
        $('#user-message').hide().text("Awaiting your command!").fadeIn(200);
        $("#q").val("");
        return;
      } else {
        $("#user-message").hide().text("Say 'Hey Jerry' to wake me up.").fadeIn(500);
        $("#q").val("");
        return;
      }
    }
    this.output = parser.parse(this.speech);
    console.log(this.output);
    $('#parse-message')
          .attr('class', 'message info')
          .text('Input parsed successfully.');
    $('#output').removeClass('disabled').text(jsDump.parse(this.output));
    this.response = this.interpretSpeech_();
    clearTimeout(this.timeout);
    this.result = true;
    $("#user-message").hide().text(this.response).fadeIn(200);
    $("#q").val("");
  } catch (e) {
    console.log(e);
    if(e instanceof SpeechBlocks.UserError) {
      $('#user-message').text(e.message);
    } else {
      $('#parse-message').attr('class', 'message error').text(this.buildErrorMessage_(e));
      if(this.speech !== '') {
        $('#user-message').hide().text('Sorry, I didn\'t understand \"' + this.speech + '\"').fadeIn(200);
        $("#q").val("");
        clearTimeout(this.timeout);
        this.timeout = setTimeout(function(){
          $('#user-message').hide().text("Awaiting your command!").fadeIn(200);
        }.bind(this), 5000);
      }
    }
  }
  return result;
};

/**
 * Calls the SpeechGames.interpreter's interpret function.
 * @return {string} Response for user (i.e. 'Added a move block.').
 * @private
 */
SpeechGames.Speech.prototype.interpretSpeech_ = function() {
  if (this.output !== null) {
    return SpeechGames.interpreter.interpret(this.output);
  }
};

/**
 * Schedule's the parsing to occur after a second of inactivity.
 * @private
 */
SpeechGames.Speech.prototype.scheduleParse_ = function() {
  if ($('#q').val() !== this.oldQ) {
    if (this.parseTimer !== null) {
      clearTimeout(this.parseTimer);
      this.parseTimer = null;
    }
    this.parseTimer = setTimeout(function() {
      this.parseSpeech_();
      this.parseTimer = null;
    }.bind(this), 1000);
  }
};

/**
 * Builds an error message.
 * @param {exception} e Exception from which to build the error message.
 * @return {exception} The error message.
 */
SpeechGames.Speech.prototype.buildErrorMessage_ = function(e) {
  return e.location !== undefined ? 'Line ' + e.location.start.line + ', column ' + e.location.start.column + ': ' + e.message : e.message;
};

/**
 * Extracts a parameter from the URL.
 * If the parameter is absent default_value is returned.
 * @param {!string} name The name of the parameter.
 * @param {!string} defaultValue Value to return if paramater not found.
 * @return {string} The parameter value or the default value if not found.
 */
SpeechGames.getStringParamFromURL_ = function(name, defaultValue) {
  var val =
      window.location.search.match(new RegExp('[?&]' + name + '=([^&]+)'));
  return val ? decodeURIComponent(val[1].replace(/\+/g, '%20')) : defaultValue;
};

/**
 * Extracts a numeric parameter from the URL.
 * If the parameter is absent or less than min_value, min_value is
 * returned.  If it is greater than max_value, max_value is returned.
 * @param {!string} name The name of the parameter.
 * @param {!number} minValue The minimum legal value.
 * @param {!number} maxValue The maximum legal value.
 * @return {number} A number in the range [min_value, max_value].
 */
SpeechGames.getNumberParamFromURL_ = function(name, minValue, maxValue) {
  var val = Number(SpeechGames.getStringParamFromURL_(name, 'NaN'));
  return isNaN(val) ? minValue : goog.math.clamp(minValue, val, maxValue);
};

/**
 * Generates code from the blockly workspace.
 * @private
 */
SpeechGames.createCode_ = function() {
  Blockly.JavaScript.addReservedWords('code');
  return Blockly.JavaScript.workspaceToCode(SpeechGames.workspace);
};

/**
 * Shows the generated code.
 * @private
 */
SpeechGames.showCode_ = function() {
  var modalEl = document.createElement('generatedCode');
  modalEl.style.width = '400px';
  modalEl.style.height = '300px';
  modalEl.style.margin = '100px auto';
  modalEl.style.backgroundColor = '#ff';
  modalEl.textContent = createCode_();
  mui.overlay('on', modalEl);
};

/**
 * Gets a parameter from the url.
 * @param {!string} name Name of the param (i.e. debug)
 * @param {string} url Optional url, otherwise window url is used.
 */
SpeechGames.getParameterByName_ = function(name, url) {
  if (!url) {
    url = window.location.href;
  }
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
      results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
};

/**
 * Initializes all of the SpeechGames objects and begins listening.
 */
$(document).ready(function() {
  SpeechGames.speech = new SpeechGames.Speech();
  SpeechGames.controller = SpeechBlocks.Controller.injectIntoDiv('blocklyDiv', {
    media: 'lib/google-blockly/media/',
    trashcan: false,
    scrollbars: false,
    toolbox: document.getElementById('toolbox')
  });
  SpeechGames.interpreter = new SpeechBlocks.Interpreter(SpeechGames.controller);
  SpeechGames.workspace = SpeechGames.controller.workspace_;

  if(!SpeechGames.getParameterByName_('debug')) {
    $('#debug').hide();
  }

  if(!SpeechGames.getParameterByName_('demo')) {
    SpeechGames.speech.awake = true;
  } else {
    SpeechGames.speech.demoMode = true;
    SpeechGames.speech.awake = false;
    SpeechGames.speech.setMicInterval_();
    console.log("demo mode");
  }
  if (SpeechGames.getParameterByName_('level')) {
    SpeechGames.speech.awake = true;
  }
   $('#q')
    .change(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
    .mousedown(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
    .mouseup(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
    .click(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
    .keydown(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
    .keyup(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech))
    .keypress(SpeechGames.speech.scheduleParse_.bind(SpeechGames.speech));

  $('#microphone')
      .click(SpeechGames.speech.toggleDictation_.bind(SpeechGames.speech));
  if (SpeechGames.speech.demoMode && !SpeechGames.speech.awake) {
     $("#user-message").hide().text("Say 'Hey Jerry' to wake me up.").fadeIn(500);
  } else {
    $("#user-message").hide().text("Awaiting your command!").fadeIn(500);
  }

  // $('#runButton').on('click', run);
  // $('#showButton').on('click', showCode_);

  $('#debugButton').on('click', function() {
    $('#debug').toggle();
  });
  $('#buttonRow').hide();
  $('#levelDescription').text(Turtle.descriptions[SpeechGames.LEVEL]);

  SpeechGames.LEVEL = SpeechGames.getNumberParamFromURL_('level', 1, SpeechGames.MAX_LEVEL);
});
<|endoftext|>


<commit_before>var typeIndex = 0;
var typer = 0;

var typeDone = false;
var screenshotDone = false;
var screenshotIsVisible = false;

$(function(){
	checkBrowser();
});

function checkBrowser(){
	if (Modernizr.canvas && Modernizr.video && !jQuery.browser.mobile){
		doHTML5VideoInteractive()
	}else{
		doYoutubeVideo();
	}
}

function doHTML5VideoInteractive(){
	$("input#inpSearch").val("");

	setTimeout(function(){
		$("#googleSearch").show();
	},2000);

	// async screenshot ophalen
	$.getJSON(
		'/getgooglescreenshot',
		{name: name},
		function(data){
			if(data.err){
				console.log(data.err);
			}else{
				$("#googlescreenshot").attr('src', data.screenshot);
				screenshotDone = true;
				showScreenshot();
			}
		});

	$('#myVideo').seeThru({start : 'autoplay' , end : 'stop'});

	$('#myVideo')[0].addEventListener('ended',videoEnds,false);

	pollTime();
}

function pollTime(){
	var time = $('#myVideo')[0].currentTime;

	if(time > 4){
		//opacity ipv hide, anders schuift video op
		$('.klikhier').animate({
   			opacity: 0
   		});
	}

	if(time > 36){
		startTyping();

		_gaq.push(['_trackEvent', 'html5video', 'time36']);
	}else{
		//check again:
		setTimeout(pollTime,1000);
	}
}

function videoEnds(){
	_gaq.push(['_trackEvent', 'html5video', 'videoends']);

	window.location = "https://www.google.be/search?q=" + escape(name);
}

function startTyping(){
	// start typing
	typer = setInterval(typeTick,300);
}

function typeTick(){
	$("#inpSearch").val($("#inpSearch").val()+name.charAt(typeIndex));
	typeIndex++;
	if(typeIndex >name.length){
		clearInterval(typer);
		typeDone = true;
		showScreenshot();
	}
}

function showScreenshot(){
	// paar checks, want we weten niet wat er eerst gaat gedaan zijn: het typen of de screenhot laden
	if(typeDone && screenshotDone && !screenshotIsVisible){
		screenshotIsVisible = true;

		//beetje wachten voor hij de resultaten toont
		setTimeout(function(){
			$("#googlescreenshot").fadeIn();
			$("#googleSearch").fadeOut();

			scroll();
		}, 700);

	}
}

function scroll(){
	$('#googlescreenshot').animate({
    	top: '-1000px'
    },6000);
}

function doYoutubeVideo(){
	window.location = "youtube/?name=" + escape(name);
}

<commit_msg>nog meer tracking<commit_after>var typeIndex = 0;
var typer = 0;

var typeDone = false;
var screenshotDone = false;
var screenshotIsVisible = false;

var messageHidden = false;

$(function(){
	checkBrowser();
});

function checkBrowser(){
	if (Modernizr.canvas && Modernizr.video && !jQuery.browser.mobile){
		doHTML5VideoInteractive()
	}else{
		doYoutubeVideo();
	}
}

function doHTML5VideoInteractive(){
	$("input#inpSearch").val("");

	setTimeout(function(){
		$("#googleSearch").show();
	},2000);

	// async screenshot ophalen
	$.getJSON(
		'/getgooglescreenshot',
		{name: name},
		function(data){
			if(data.err){
				console.log(data.err);
			}else{
				$("#googlescreenshot").attr('src', data.screenshot);
				screenshotDone = true;
				showScreenshot();
			}
		});

	$('#myVideo').seeThru({start : 'autoplay' , end : 'stop'});

	$('#myVideo')[0].addEventListener('ended',videoEnds,false);

	pollTime();
}

function pollTime(){
	var time = $('#myVideo')[0].currentTime;

	if(time > 4 && !messageHidden){
		messageHidden = true;
		//opacity ipv hide, anders schuift video op
		$('.klikhier').animate({
   			opacity: 0
   		});

   		_gaq.push(['_trackEvent', 'html5video', 'time4']);
	}

	if(time > 36){
		startTyping();

		_gaq.push(['_trackEvent', 'html5video', 'time36']);
	}else{
		//check again:
		setTimeout(pollTime,1000);
	}
}

function videoEnds(){
	_gaq.push(['_trackEvent', 'html5video', 'videoends']);

	window.location = "https://www.google.be/search?q=" + escape(name);
}

function startTyping(){
	// start typing
	typer = setInterval(typeTick,300);
}

function typeTick(){
	$("#inpSearch").val($("#inpSearch").val()+name.charAt(typeIndex));
	typeIndex++;
	if(typeIndex >name.length){
		clearInterval(typer);
		typeDone = true;
		showScreenshot();
	}
}

function showScreenshot(){
	// paar checks, want we weten niet wat er eerst gaat gedaan zijn: het typen of de screenhot laden
	if(typeDone && screenshotDone && !screenshotIsVisible){
		screenshotIsVisible = true;

		//beetje wachten voor hij de resultaten toont
		setTimeout(function(){
			$("#googlescreenshot").fadeIn();
			$("#googleSearch").fadeOut();

			scroll();
		}, 700);

	}
}

function scroll(){
	$('#googlescreenshot').animate({
    	top: '-1000px'
    },6000);
}

function doYoutubeVideo(){
	window.location = "youtube/?name=" + escape(name);
}

<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name groongaAdminApp.controller:TableSearchController
 * @description
 * # TableSearchController
 * Controller of the groongaAdminApp
 */
angular.module('groongaAdminApp')
  .controller('TableSearchController', function ($scope, $routeParams, $location, $http) {
    $scope.table = $routeParams.table;
    $scope.style = 'table';
    $scope.rawData = [];
    $scope.columns = [];
    $scope.records = [];
    $scope.indexedColumns = [];
    $scope.outputColumns = [];
    $scope.commandLine = '';
    $scope.message = '';
    $scope.elapsedTimeInMilliseconds = 0;
    $scope.nTotalRecords = 0;
    $scope.parameters = angular.copy($location.search());

    $scope.search = function() {
      var matchColumns = $scope.indexedColumns
          .filter(function(indexedColumn) {
            return indexedColumn.inUse;
          })
          .map(function(indexedColumn) {
            return indexedColumn.name;
          })
          .join(',');
      var outputColumns = $scope.outputColumns
          .filter(function(outputColumn) {
            return outputColumn.inUse;
          })
          .map(function(outputColumn) {
            return outputColumn.name;
          })
          .join(',');
      var parameters = angular.extend({},
                                      $scope.parameters,
                                      {
                                        'match_columns':  matchColumns,
                                        'output_columns': outputColumns
                                      });
      $location.search(parameters);
    };

    $scope.clear = function() {
      $location.search({});
    };

    var client = new GroongaClient($http);
    client.execute('table_list')
      .success(function(response) {
        response.tables().forEach(function(table) {
          client.execute('column_list', {table: table.name})
            .success(function(response) {
              response.columns().forEach(function(column) {
                if (!column.isIndex) {
                  return;
                }
                if (column.range !== $scope.table) {
                  return;
                }
                var matchColumns = $scope.parameters.match_columns;
                column.sources.forEach(function(source) {
                  var localName = source.split('.')[1];
                  var inUse = true;
                  if (matchColumns) {
                      inUse = matchColumns.indexOf(localName) !== -1;
                  }
                  $scope.indexedColumns.push({name: localName, inUse: inUse});
                });
              });
            });
        });
      });

    client.execute('column_list', {table: $scope.table})
      .success(function(response) {
        var outputColumns = $scope.parameters.output_columns;
        console.log(response.columns());
        response.columns().forEach(function(column) {
          if (column.isIndex) {
            return;
          }
          var inUse = true;
          if (outputColumns) {
            inUse = outputColumns.indexOf(column.name) !== -1;
          }
          $scope.outputColumns.push({name: column.name, inUse: inUse});
        });
      });

    var parameters = {
      table: $scope.table
    };
    angular.forEach($scope.parameters, function(value, key) {
      if (key in parameters) {
        return;
      }
      parameters[key] = value;
    });
    var request = client.execute('select', parameters);
    request.success(function(response) {
      $scope.rawData = response.rawData();
      $scope.commandLine = request.commandLine();
      $scope.elapsedTimeInMilliseconds = response.elapsedTime() * 1000;
      if (!response.isSuccess()) {
        $scope.message =
          'Failed to call "select" command: ' + response.errorMessage();
        $scope.nTotalRecords = 0;
        return;
      }
      $scope.nTotalRecords = response.nTotalRecords();
      $scope.columns = response.columns();
      $scope.records = response.records().map(function(record) {
        return record.map(function(value, index) {
          return {
            value: value,
            column: $scope.columns[index]
          };
        });
      });
    });
  });
<commit_msg>Create function for each doe block<commit_after>'use strict';

/**
 * @ngdoc function
 * @name groongaAdminApp.controller:TableSearchController
 * @description
 * # TableSearchController
 * Controller of the groongaAdminApp
 */
angular.module('groongaAdminApp')
  .controller('TableSearchController', function ($scope, $routeParams, $location, $http) {
    var client = new GroongaClient($http);

    function initialize() {
      $scope.table = $routeParams.table;
      $scope.style = 'table';
      $scope.rawData = [];
      $scope.columns = [];
      $scope.records = [];
      $scope.indexedColumns = [];
      $scope.outputColumns = [];
      $scope.commandLine = '';
      $scope.message = '';
      $scope.elapsedTimeInMilliseconds = 0;
      $scope.nTotalRecords = 0;
      $scope.parameters = angular.copy($location.search());

      $scope.search = search;
      $scope.clear  = clear;
    }

    function search() {
      var matchColumns = $scope.indexedColumns
          .filter(function(indexedColumn) {
            return indexedColumn.inUse;
          })
          .map(function(indexedColumn) {
            return indexedColumn.name;
          })
          .join(',');
      var outputColumns = $scope.outputColumns
          .filter(function(outputColumn) {
            return outputColumn.inUse;
          })
          .map(function(outputColumn) {
            return outputColumn.name;
          })
          .join(',');
      var parameters = angular.extend({},
                                      $scope.parameters,
                                      {
                                        'match_columns':  matchColumns,
                                        'output_columns': outputColumns
                                      });
      $location.search(parameters);
    }

    function clear() {
      $location.search({});
    }

    function fillOptions() {
      client.execute('table_list')
        .success(function(response) {
          response.tables().forEach(function(table) {
            client.execute('column_list', {table: table.name})
            .success(function(response) {
              response.columns().forEach(function(column) {
                if (!column.isIndex) {
                  return;
                }
                if (column.range !== $scope.table) {
                  return;
                }
                var matchColumns = $scope.parameters.match_columns;
                column.sources.forEach(function(source) {
                  var localName = source.split('.')[1];
                  var inUse = true;
                  if (matchColumns) {
                      inUse = matchColumns.indexOf(localName) !== -1;
                  }
                  $scope.indexedColumns.push({name: localName, inUse: inUse});
                });
              });
            });
          });
        });

      client.execute('column_list', {table: $scope.table})
        .success(function(response) {
          var outputColumns = $scope.parameters.output_columns;
          console.log(response.columns());
          response.columns().forEach(function(column) {
            if (column.isIndex) {
              return;
            }
            var inUse = true;
            if (outputColumns) {
              inUse = outputColumns.indexOf(column.name) !== -1;
            }
            $scope.outputColumns.push({name: column.name, inUse: inUse});
          });
        });
    }

    function select() {
      var parameters = {
        table: $scope.table
      };
      angular.forEach($scope.parameters, function(value, key) {
        if (key in parameters) {
          return;
        }
        parameters[key] = value;
      });
      var request = client.execute('select', parameters);
      request.success(function(response) {
        $scope.rawData = response.rawData();
        $scope.commandLine = request.commandLine();
        $scope.elapsedTimeInMilliseconds = response.elapsedTime() * 1000;
        if (!response.isSuccess()) {
          $scope.message =
            'Failed to call "select" command: ' + response.errorMessage();
          $scope.nTotalRecords = 0;
          return;
        }
        $scope.nTotalRecords = response.nTotalRecords();
        $scope.columns = response.columns();
        $scope.records = response.records().map(function(record) {
          return record.map(function(value, index) {
            return {
              value: value,
              column: $scope.columns[index]
            };
          });
        });
      });
    }

    initialize();
    fillOptions();
    select();
  });
<|endoftext|>


<commit_before>var serverTimeout = 10000;

function $(x) {
    return document.getElementById(x);
}

function createXHR() {
    var xhr;
    if (window.ActiveXObject) {
        try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
        catch(e) { xhr = null; }
    } else xhr = new XMLHttpRequest();
    return xhr;
}

var changeInputLayout = function() {
    var textarea = document.createElement("textarea");
    var input = document.createElement("input");
    input.name = textarea.name = "content";
    input.id = textarea.id = "contentbox";
    input.type = "text";
    input.setAttribute("autocomplete", "off");
    var origin = document.form.content;
    if (origin.tagName == "TEXTAREA") {
        origin.parentNode.replaceChild(input, origin);
        $("textarea_br").className = 'hidden';
    } else {
        origin.parentNode.replaceChild(textarea, origin);
        $("textarea_br").className = '';
    }
}

document.form.onsubmit = function(e) {
    var content = document.form.content.value;
    var server = document.form.action;
    if (!content) {
        changeInputLayout();
        return false;
    }
    var cbRunning = function() {
        document.form.content.focus();
        document.form.content.disabled = true;
        document.form.btn.disabled = true;
        document.form.btn.value = "writing...";
    }
    var cbDone = function() {
        document.form.content.disabled = false;
        document.form.btn.disabled = false;
        document.form.btn.value = "write!";
        document.form.content.focus();
        updater.refreshOnce();
    }
    cbRunning();
    var xhr = createXHR();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            cbDone();
            if (xhr.responseText) {
                var res = eval("(" + xhr.responseText + ")");
                if (!res.err) document.form.content.value = "";
            }
        }
    };
    var params = "content=" + content;
    xhr.open("POST", server);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.timeout = serverTimeout;
    xhr.ontimeout = cbDone;
    xhr.send(params);
    return false;
};

var updater = {
    server: null,
    latest: null,
    interval: 5000,

    setup: function(server, latest) {
        updater.server = server;
        updater.latest = latest;
        updater.refresh();
    },

    refresh: function() {
        updater.refreshOnce(function() {
            setTimeout(updater.refresh, updater.interval);
        });
    },

    refreshOnce: function(cb) {
        var xhr = createXHR();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (cb) cb();
                if (xhr.responseText) {
                    var res = eval("(" + xhr.responseText + ")");
                    if (res.count && res.request == updater.latest) {
                        var table = $("mesglist");
                        table.innerHTML = res.html + table.innerHTML;
                        updater.latest = res.latest;
                    }
                }
            }
        }
        var localtime = Number(Date.now());
        xhr.timeout = serverTimeout;
        if (cb) xhr.ontimeout = cb;
        xhr.open("GET", updater.server + "?latest=" + updater.latest + "&localtime=" + localtime);
        xhr.send();
    }
};
<commit_msg>fix bugs for IE again, ontimeout not fully supported<commit_after>var serverTimeout = 10000;

function $(x) {
    return document.getElementById(x);
}

function createXHR() {
    var xhr;
    if (!XMLHttpRequest) {
        try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
        catch(e) { xhr = null; }
    } else xhr = new XMLHttpRequest();
    return xhr;
}

var changeInputLayout = function() {
    var textarea = document.createElement("textarea");
    var input = document.createElement("input");
    input.name = textarea.name = "content";
    input.id = textarea.id = "contentbox";
    input.type = "text";
    input.setAttribute("autocomplete", "off");
    var origin = document.form.content;
    if (origin.tagName == "TEXTAREA") {
        origin.parentNode.replaceChild(input, origin);
        $("textarea_br").className = 'hidden';
    } else {
        origin.parentNode.replaceChild(textarea, origin);
        $("textarea_br").className = '';
    }
}

document.form.onsubmit = function(e) {
    var content = document.form.content.value;
    var server = document.form.action;
    if (!content) {
        changeInputLayout();
        return false;
    }
    var cbRunning = function() {
        document.form.content.focus();
        document.form.content.disabled = true;
        document.form.btn.disabled = true;
        document.form.btn.value = "writing...";
    }
    var cbDone = function() {
        document.form.content.disabled = false;
        document.form.btn.disabled = false;
        document.form.btn.value = "write!";
        document.form.content.focus();
        updater.refreshOnce();
    }
    cbRunning();
    var xhr = createXHR();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            cbDone();
            if (xhr.responseText) {
                var res = eval("(" + xhr.responseText + ")");
                if (!res.err) document.form.content.value = "";
            }
        }
    };
    var params = "content=" + content;
    xhr.open("POST", server);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    try {
        xhr.timeout = serverTimeout;
        xhr.ontimeout = cbDone;
    } catch(e) {}
    xhr.send(params);
    return false;
};

var updater = {
    server: null,
    latest: null,
    interval: 5000,

    setup: function(server, latest) {
        updater.server = server;
        updater.latest = latest;
        updater.refresh();
    },

    refresh: function() {
        updater.refreshOnce(function() {
            setTimeout(updater.refresh, updater.interval);
        });
    },

    refreshOnce: function(cb) {
        var xhr = createXHR();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (cb) cb();
                if (xhr.responseText) {
                    var res = eval("(" + xhr.responseText + ")");
                    if (res.count && res.request == updater.latest) {
                        var table = $("mesglist");
                        table.innerHTML = res.html + table.innerHTML;
                        updater.latest = res.latest;
                    }
                }
            }
        }
        var localtime = Number(Date.now());
        try {
            xhr.timeout = serverTimeout;
            if (cb) xhr.ontimeout = cb;
        } catch(e) {}
        xhr.open("GET", updater.server + "?latest=" + updater.latest + "&localtime=" + localtime);
        xhr.send();
    }
};
<|endoftext|>


<commit_before>Package.describe({
  name: 'pmulch:game',
  version: '0.0.1',
  summary: 'A framework for building bring-your-own-device (BYOD) games using Meteor',
  git: 'https://github.com/pmulch/MeteorGameEngine.git',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  // min version
  api.versionsFrom('1.4.1.1');

  // dependencies
  // common
  api.use([
    'ecmascript',
    'underscore',
    'tracker',
    'mongo',
    'random'
  ]);

  // client
  api.use([
    'session',
    'u2622:persistent-session@0.4.4'
  ], ['client']);

  // source files
  // common
  api.addFiles([
    'lib/common/utils.js',
    'lib/common/data.js'
  ]);

  // server
  api.addFiles([
    'lib/server/publish.js',
    'lib/server/game-server.js'
  ], ['server']);

  // client
  api.addFiles([
    'lib/client/game-controller.js',
    'lib/client/game-session.js'
  ], ['client']);

  // exports
  api.export(['Games', 'Game']);
  api.export(['GameSession', 'GameController'], 'client');

  api.imply(['random']);
  api.imply(['u2622:persistent-session'], 'client');
});

Package.onTest(function(api) {
  api.use([
    'ecmascript',
    'tinytest',
    'underscore',
    'pmulch:game'
  ]);

  api.addFiles('tests/client.js', 'client');
  api.addFiles('tests/server.js', 'server');
});
<commit_msg>(part of previous commit) removing reference to utils.js from package.js<commit_after>Package.describe({
  name: 'pmulch:game',
  version: '0.0.1',
  summary: 'A framework for building bring-your-own-device (BYOD) games using Meteor',
  git: 'https://github.com/pmulch/MeteorGameEngine.git',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  // min version
  api.versionsFrom('1.4.1.1');

  // dependencies
  // common
  api.use([
    'ecmascript',
    'underscore',
    'tracker',
    'mongo',
    'random'
  ]);

  // client
  api.use([
    'session',
    'u2622:persistent-session@0.4.4'
  ], ['client']);

  // source files
  // common
  api.addFiles([
    'lib/common/data.js'
  ]);

  // server
  api.addFiles([
    'lib/server/publish.js',
    'lib/server/game-server.js'
  ], ['server']);

  // client
  api.addFiles([
    'lib/client/game-controller.js',
    'lib/client/game-session.js'
  ], ['client']);

  // exports
  api.export(['Games', 'Game']);
  api.export(['GameSession', 'GameController'], 'client');

  api.imply(['random']);
  api.imply(['u2622:persistent-session'], 'client');
});

Package.onTest(function(api) {
  api.use([
    'ecmascript',
    'tinytest',
    'underscore',
    'pmulch:game'
  ]);

  api.addFiles('tests/client.js', 'client');
  api.addFiles('tests/server.js', 'server');
});
<|endoftext|>


<commit_before>/*
 * Called as the user scrolls/zooms around to aniplate hrefs of the
 * view tab and various other links
 */
function updatelinks(lon,lat,zoom,layers,minlon,minlat,maxlon,maxlat, obj_type, obj_id) {
  var decimals = Math.pow(10, Math.floor(zoom/3));
  var node;

  lat = Math.round(lat * decimals) / decimals;
  lon = Math.round(lon * decimals) / decimals;

  node = document.getElementById("permalinkanchor");
  if (node) {
    var args = getArgs(node.href);
    args["lat"] = lat;
    args["lon"] = lon;
    args["zoom"] = zoom;
    if (layers) {
      args["layers"] = layers;
    }
    if (obj_type && obj_id) {
      args[obj_type] = obj_id;
    }
    node.href = setArgs(node.href, args);
  }

  node = document.getElementById("viewanchor");
  if (node) {
    var args = getArgs(node.href);
    args["lat"] = lat;
    args["lon"] = lon;
    args["zoom"] = zoom;
    if (layers) {
      args["layers"] = layers;
    }
    node.href = setArgs(node.href, args);
  }

  node = document.getElementById("exportanchor");
  if (node) {
    var args = getArgs(node.href);
    args["lat"] = lat;
    args["lon"] = lon;
    args["zoom"] = zoom;
    if (layers) {
      args["layers"] = layers;
    }
    node.href = setArgs(node.href, args);
  }

  node = document.getElementById("editanchor");
  if (node) {
    if (zoom >= 13) {
      var args = new Object();
      args.lat = lat;
      args.lon = lon;
      args.zoom = zoom;
      node.href = setArgs("/edit", args);
      node.style.fontStyle = 'normal';
    } else {
      node.href = 'javascript:alert("zoom in to edit map");';
      node.style.fontStyle = 'italic';
    }
  }

  node = document.getElementById("historyanchor");
  if (node) {
    if (zoom >= 11) {
      var args = new Object();
      //set bbox param from 'extents' object
      if (typeof minlon == "number" &&
	  typeof minlat == "number" &&
	  typeof maxlon == "number" &&
	  typeof maxlat == "number") {

        minlon = Math.round(minlon * decimals) / decimals;
        minlat = Math.round(minlat * decimals) / decimals;
        maxlon = Math.round(maxlon * decimals) / decimals;
        maxlat = Math.round(maxlat * decimals) / decimals;
        args.bbox = minlon + "," + minlat + "," + maxlon + "," + maxlat;
      }

      node.href = setArgs("/history", args);
      node.style.fontStyle = 'normal';
    } else {
      node.href = 'javascript:alert("zoom in to see editing history");';
      node.style.fontStyle = 'italic';
    }
  }

  node = document.getElementById("shortlinkanchor");
  if (node) {
    var args = getArgs(node.href);
    var code = makeShortCode(lat, lon, zoom);
    // little hack. may the gods of hardcoding please forgive me, or
    // show me the Right way to do it.
    if (layers && (layers != "B000FTF")) {
      args["layers"] = layers;
      node.href = setArgs("http://osm.org/go/" + code, args);
    } else {
      node.href = "http://osm.org/go/" + code;
    }
  }
}

function getArgs(url) {
  var args = new Object();
  var querystart = url.indexOf("?");

  if (querystart >= 0) {
     var querystring = url.substring(querystart + 1);
     var queryitems = querystring.split("&");

     for (var i = 0; i < queryitems.length; i++) {
        if (match = queryitems[i].match(/^(.*)=(.*)$/)) {
           args[unescape(match[1])] = unescape(match[2]);
        } else {
           args[unescape(queryitems[i])] = null
        }
     }
  }

  return args;
}

/*
 * Called to set the arguments on a URL from the given hash.
 */
function setArgs(url, args) {
   var queryitems = new Array();

   for (arg in args)
   {
      if (args[arg] == null) {
         queryitems.push(escape(arg));
      } else {
         queryitems.push(escape(arg) + "=" + escape(args[arg]));
      }
   }

   return url.replace(/\?.*$/, "") + "?" + queryitems.join("&");
}

/*
 * Called to get the arguments from a URL as a hash.
 */
function getStyle(el, property) {
  var style;

  if (el.currentStyle) {
    style = el.currentStyle[property];
  } else if( window.getComputedStyle ) {
    style = document.defaultView.getComputedStyle(el,null).getPropertyValue(property);
  } else {
    style = el.style[property];
  }

  return style;
}

/*
 * Called to interpolate JavaScript variables in strings using a
 * similar syntax to rails I18n string interpolation - the only
 * difference is that [[foo]] is the placeholder syntax instead
 * of {{foo}} which allows the same string to be processed by both
 * rails and then later by javascript.
 */
function i18n(string, keys) {
  for (var key in keys) {
    var re_key = '\\[\\[' + key + '\\]\\]';
    var re = new RegExp(re_key, "g");

    string = string.replace(re, keys[key]);
  }

  return string;
}

function makeShortCode(lat, lon, zoom) {
    char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
    var x = Math.round((lon + 180.0) * ((1 << 30) / 90.0));
    var y = Math.round((lat +  90.0) * ((1 << 30) / 45.0));
    // hack around the fact that JS apparently only allows 53-bit integers?!?
    // note that, although this reduces the accuracy of the process, it's fine for
    // z18 so we don't need to care for now.
    var c1 = 0, c2 = 0;
    for (var i = 31; i > 16; --i) {
	c1 = (c1 << 1) | ((x >> i) & 1);
	c1 = (c1 << 1) | ((y >> i) & 1);
    }
    for (var i = 16; i > 1; --i) {
	c2 = (c2 << 1) | ((x >> i) & 1);
	c2 = (c2 << 1) | ((y >> i) & 1);
    }
    var str = "";
    for (var i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
	digit = (c1 >> (24 - 6 * i)) & 0x3f;
	str += char_array.charAt(digit);
    }
    for (var i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
	digit = (c2 >> (24 - 6 * (i - 5))) & 0x3f;
	str += char_array.charAt(digit);
    }
    for (var i = 0; i < ((zoom + 8) % 3); ++i) {
	str += "=";
    }
    return str;
}
<commit_msg>Only hardcode http://osm.org/ in shortlinks when we're at openstreetmap.org (according to window.location.hostname).<commit_after>/*
 * Called as the user scrolls/zooms around to aniplate hrefs of the
 * view tab and various other links
 */
function updatelinks(lon,lat,zoom,layers,minlon,minlat,maxlon,maxlat, obj_type, obj_id) {
  var decimals = Math.pow(10, Math.floor(zoom/3));
  var node;

  lat = Math.round(lat * decimals) / decimals;
  lon = Math.round(lon * decimals) / decimals;

  node = document.getElementById("permalinkanchor");
  if (node) {
    var args = getArgs(node.href);
    args["lat"] = lat;
    args["lon"] = lon;
    args["zoom"] = zoom;
    if (layers) {
      args["layers"] = layers;
    }
    if (obj_type && obj_id) {
      args[obj_type] = obj_id;
    }
    node.href = setArgs(node.href, args);
  }

  node = document.getElementById("viewanchor");
  if (node) {
    var args = getArgs(node.href);
    args["lat"] = lat;
    args["lon"] = lon;
    args["zoom"] = zoom;
    if (layers) {
      args["layers"] = layers;
    }
    node.href = setArgs(node.href, args);
  }

  node = document.getElementById("exportanchor");
  if (node) {
    var args = getArgs(node.href);
    args["lat"] = lat;
    args["lon"] = lon;
    args["zoom"] = zoom;
    if (layers) {
      args["layers"] = layers;
    }
    node.href = setArgs(node.href, args);
  }

  node = document.getElementById("editanchor");
  if (node) {
    if (zoom >= 13) {
      var args = new Object();
      args.lat = lat;
      args.lon = lon;
      args.zoom = zoom;
      node.href = setArgs("/edit", args);
      node.style.fontStyle = 'normal';
    } else {
      node.href = 'javascript:alert("zoom in to edit map");';
      node.style.fontStyle = 'italic';
    }
  }

  node = document.getElementById("historyanchor");
  if (node) {
    if (zoom >= 11) {
      var args = new Object();
      //set bbox param from 'extents' object
      if (typeof minlon == "number" &&
	  typeof minlat == "number" &&
	  typeof maxlon == "number" &&
	  typeof maxlat == "number") {

        minlon = Math.round(minlon * decimals) / decimals;
        minlat = Math.round(minlat * decimals) / decimals;
        maxlon = Math.round(maxlon * decimals) / decimals;
        maxlat = Math.round(maxlat * decimals) / decimals;
        args.bbox = minlon + "," + minlat + "," + maxlon + "," + maxlat;
      }

      node.href = setArgs("/history", args);
      node.style.fontStyle = 'normal';
    } else {
      node.href = 'javascript:alert("zoom in to see editing history");';
      node.style.fontStyle = 'italic';
    }
  }

  node = document.getElementById("shortlinkanchor");
  if (node) {
    var args = getArgs(node.href);
    var code = makeShortCode(lat, lon, zoom);
    var prefix = shortlinkPrefix();

    // little hack. may the gods of hardcoding please forgive me, or
    // show me the Right way to do it.
    if (layers && (layers != "B000FTF")) {
      args["layers"] = layers;
      node.href = setArgs(prefix + "/go/" + code, args);
    } else {
      node.href = prefix + "/go/" + code;
    }
  }
}

/*
 * This is a hack to hardcode opestreetmap.org -> osm.org in the
 * shortlink
 */
function shortlinkPrefix() {
    var hostname = window.location.hostname;
    var normalized_hostname = hostname.replace(/^:www\./i,'');
    var prefix = '';

    if (normalized_hostname.match(/^openstreetmap\.org$/i)) {
        prefix = "http://osm.org";
    }

    return prefix;
}

function getArgs(url) {
  var args = new Object();
  var querystart = url.indexOf("?");

  if (querystart >= 0) {
     var querystring = url.substring(querystart + 1);
     var queryitems = querystring.split("&");

     for (var i = 0; i < queryitems.length; i++) {
        if (match = queryitems[i].match(/^(.*)=(.*)$/)) {
           args[unescape(match[1])] = unescape(match[2]);
        } else {
           args[unescape(queryitems[i])] = null
        }
     }
  }

  return args;
}

/*
 * Called to set the arguments on a URL from the given hash.
 */
function setArgs(url, args) {
   var queryitems = new Array();

   for (arg in args)
   {
      if (args[arg] == null) {
         queryitems.push(escape(arg));
      } else {
         queryitems.push(escape(arg) + "=" + escape(args[arg]));
      }
   }

   return url.replace(/\?.*$/, "") + "?" + queryitems.join("&");
}

/*
 * Called to get the arguments from a URL as a hash.
 */
function getStyle(el, property) {
  var style;

  if (el.currentStyle) {
    style = el.currentStyle[property];
  } else if( window.getComputedStyle ) {
    style = document.defaultView.getComputedStyle(el,null).getPropertyValue(property);
  } else {
    style = el.style[property];
  }

  return style;
}

/*
 * Called to interpolate JavaScript variables in strings using a
 * similar syntax to rails I18n string interpolation - the only
 * difference is that [[foo]] is the placeholder syntax instead
 * of {{foo}} which allows the same string to be processed by both
 * rails and then later by javascript.
 */
function i18n(string, keys) {
  for (var key in keys) {
    var re_key = '\\[\\[' + key + '\\]\\]';
    var re = new RegExp(re_key, "g");

    string = string.replace(re, keys[key]);
  }

  return string;
}

function makeShortCode(lat, lon, zoom) {
    char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
    var x = Math.round((lon + 180.0) * ((1 << 30) / 90.0));
    var y = Math.round((lat +  90.0) * ((1 << 30) / 45.0));
    // hack around the fact that JS apparently only allows 53-bit integers?!?
    // note that, although this reduces the accuracy of the process, it's fine for
    // z18 so we don't need to care for now.
    var c1 = 0, c2 = 0;
    for (var i = 31; i > 16; --i) {
	c1 = (c1 << 1) | ((x >> i) & 1);
	c1 = (c1 << 1) | ((y >> i) & 1);
    }
    for (var i = 16; i > 1; --i) {
	c2 = (c2 << 1) | ((x >> i) & 1);
	c2 = (c2 << 1) | ((y >> i) & 1);
    }
    var str = "";
    for (var i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
	digit = (c1 >> (24 - 6 * i)) & 0x3f;
	str += char_array.charAt(digit);
    }
    for (var i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
	digit = (c2 >> (24 - 6 * (i - 5))) & 0x3f;
	str += char_array.charAt(digit);
    }
    for (var i = 0; i < ((zoom + 8) % 3); ++i) {
	str += "=";
    }
    return str;
}
<|endoftext|>


<commit_before>import {combineReducers} from 'redux';

import greetingReducer from './greetingReducer';

export default combineReducers({
    greeting: greetingReducer
});<commit_msg>simplify the export<commit_after>import {combineReducers} from 'redux';

import greeting from './greetingReducer';

export default combineReducers({
    greeting
});<|endoftext|>


<commit_before>'use strict';

$('head').append('<link rel="stylesheet" href="js/jqrangeslider/dest/css/iThing-min.css" type="text/css" />');
$('#svgDiv').append('

');
$('#svgDiv').append('
<button type="button" class="btn btn-default btn-primary" onClick="play()">Play</button>

<button type="button" class="btn btn-default btn-primary" onClick="reset()">Reset</button>
');

var stateTitle = [{
    'name': 'Alabama',
    'abbreviation': 'AL'
}, {
    'name': 'Alaska',
    'abbreviation': 'AK'
}, {
    'name': 'American Samoa',
    'abbreviation': 'AS'
}, {
    'name': 'Arizona',
    'abbreviation': 'AZ'
}, {
    'name': 'Arkansas',
    'abbreviation': 'AR'
}, {
    'name': 'California',
    'abbreviation': 'CA'
}, {
    'name': 'Colorado',
    'abbreviation': 'CO'
}, {
    'name': 'Connecticut',
    'abbreviation': 'CT'
}, {
    'name': 'Delaware',
    'abbreviation': 'DE'
}, {
    'name': 'District Of Columbia',
    'abbreviation': 'DC'
}, {
    'name': 'Federated States Of Micronesia',
    'abbreviation': 'FM'
}, {
    'name': 'Florida',
    'abbreviation': 'FL'
}, {
    'name': 'Georgia',
    'abbreviation': 'GA'
}, {
    'name': 'Guam',
    'abbreviation': 'GU'
}, {
    'name': 'Hawaii',
    'abbreviation': 'HI'
}, {
    'name': 'Idaho',
    'abbreviation': 'ID'
}, {
    'name': 'Illinois',
    'abbreviation': 'IL'
}, {
    'name': 'Indiana',
    'abbreviation': 'IN'
}, {
    'name': 'Iowa',
    'abbreviation': 'IA'
}, {
    'name': 'Kansas',
    'abbreviation': 'KS'
}, {
    'name': 'Kentucky',
    'abbreviation': 'KY'
}, {
    'name': 'Louisiana',
    'abbreviation': 'LA'
}, {
    'name': 'Maine',
    'abbreviation': 'ME'
}, {
    'name': 'Marshall Islands',
    'abbreviation': 'MH'
}, {
    'name': 'Maryland',
    'abbreviation': 'MD'
}, {
    'name': 'Massachusetts',
    'abbreviation': 'MA'
}, {
    'name': 'Michigan',
    'abbreviation': 'MI'
}, {
    'name': 'Minnesota',
    'abbreviation': 'MN'
}, {
    'name': 'Mississippi',
    'abbreviation': 'MS'
}, {
    'name': 'Missouri',
    'abbreviation': 'MO'
}, {
    'name': 'Montana',
    'abbreviation': 'MT'
}, {
    'name': 'Nebraska',
    'abbreviation': 'NE'
}, {
    'name': 'Nevada',
    'abbreviation': 'NV'
}, {
    'name': 'New Hampshire',
    'abbreviation': 'NH'
}, {
    'name': 'New Jersey',
    'abbreviation': 'NJ'
}, {
    'name': 'New Mexico',
    'abbreviation': 'NM'
}, {
    'name': 'New York',
    'abbreviation': 'NY'
}, {
    'name': 'North Carolina',
    'abbreviation': 'NC'
}, {
    'name': 'North Dakota',
    'abbreviation': 'ND'
}, {
    'name': 'Northern Mariana Islands',
    'abbreviation': 'MP'
}, {
    'name': 'Ohio',
    'abbreviation': 'OH'
}, {
    'name': 'Oklahoma',
    'abbreviation': 'OK'
}, {
    'name': 'Oregon',
    'abbreviation': 'OR'
}, {
    'name': 'Palau',
    'abbreviation': 'PW'
}, {
    'name': 'Pennsylvania',
    'abbreviation': 'PA'
}, {
    'name': 'Puerto Rico',
    'abbreviation': 'PR'
}, {
    'name': 'Rhode Island',
    'abbreviation': 'RI'
}, {
    'name': 'South Carolina',
    'abbreviation': 'SC'
}, {
    'name': 'South Dakota',
    'abbreviation': 'SD'
}, {
    'name': 'Tennessee',
    'abbreviation': 'TN'
}, {
    'name': 'Texas',
    'abbreviation': 'TX'
}, {
    'name': 'Utah',
    'abbreviation': 'UT'
}, {
    'name': 'Vermont',
    'abbreviation': 'VT'
}, {
    'name': 'Virgin Islands',
    'abbreviation': 'VI'
}, {
    'name': 'Virginia',
    'abbreviation': 'VA'
}, {
    'name': 'Washington',
    'abbreviation': 'WA'
}, {
    'name': 'West Virginia',
    'abbreviation': 'WV'
}, {
    'name': 'Wisconsin',
    'abbreviation': 'WI'
}, {
    'name': 'Wyoming',
    'abbreviation': 'WY'
}];
/*var consolidateToState = function(data) {
    var result = d3.map();
    data.forEach(function(element) {
        stateTitle.forEach(function(state) {
            if (element[0].indexOf(state.name + ', USA') > -1 || element[0].indexOf(', ' + state.abbreviation) > -1) {
                if (result.has(state.abbreviation)) {
                    var cnt = result.get(state.abbreviation);
                    cnt = cnt + element[2];
                    result.set(state.abbreviation, cnt);
                }
                else {
                    result.set(state.abbreviation, element[2]);
                }
            }
        });
    });
    return result;
};*/

var consolidateToDate = function(data) {
    var result = d3.map();
    data.forEach(function(element) {
        var stateAbrivation = '';
        stateTitle.forEach(function(state) {
            if (element[0].indexOf(state.name + ', USA') > -1 || element[0].indexOf(', ' + state.abbreviation) > -1) {
                stateAbrivation = state.abbreviation;
            }
        });
        if (stateAbrivation !== '') {
            if (result.has(new Date(element[1]))) {
                var mapDate = result.get(new Date(element[1]));
                if (mapDate.has(stateAbrivation)) {
                    var cnt = mapDate.get(stateAbrivation);
                    cnt = cnt + element[2];
                    mapDate.set(stateAbrivation, cnt);
                }
                else {
                    mapDate.set(stateAbrivation, element[2]);
                }
                result.set(new Date(element[1]), mapDate);
            }
            else {
                var mapDate2 = d3.map();
                mapDate2.set(stateAbrivation, element[2]);
                result.set(new Date(element[1]), mapDate2);
            }
        }
    });
    return result;
};

var svgDiv = document.querySelector('#svgDiv');
var resultData = angular.element(svgDiv).scope().query.result;
var result = consolidateToDate(resultData);

var minDate = d3.min(result.entries(), function(d) {
    var date = new Date(d.key);
    return date;
});
var maxDate = d3.max(result.entries(), function(d) {
    var date = new Date(d.key);
    return date;
});

var width = 969,
    height = 593;

var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];

var draw = function(firstDate, lastDate, data) {
    var resultData = d3.map();
    stateTitle.forEach(function(element) {
        resultData.set(element.abbreviation, 0);
    });
    data.entries().forEach(function(element) {
        var date2 = new Date(element.key);
        firstDate.setDate(firstDate.getDate() - 1);

        if (firstDate < date2 && date2 < lastDate) {
            element.value.entries().forEach(function(element) {
                if (resultData.has(element.key)) {
                    var cnt = resultData.get(element.key);
                    cnt = cnt + element.value;
                    resultData.set(element.key, cnt);
                }
                else {
                    resultData.set(element.key, element.value);
                }
            });
        }
    });

    var max = d3.max(resultData.entries(), function(d) {
        return d.value;
    });
    var min = d3.min(resultData.entries(), function(d) {
        return d.value;
    });
    console.log(max + ',' + min);

    var color = d3.scale.linear()
        .domain([min, max])
        .range(['#deebf7', '#00003f']);

    d3.select('#AK').remove();
    d3.select('#path57').remove();
    d3.select('#HI').remove();

    resultData.entries().forEach(function(element) {
        d3.select('#' + element.key)
            .transition().duration(800)
            .style('fill', function() {
                if (element.value === 0) {
                    return '#d3d3d3';
                }
                return color(element.value);
            });
    });
};

var intervalDay = 7;
$('#slider').dateRangeSlider({
    bounds: {
        min: new Date(minDate),
        max: new Date(maxDate)
    },
    defaultValues: {
        min: new Date(minDate),
        max: new Date(minDate.valueOf() + (1000 * 3600 * 24) * intervalDay)
    },
    enabled: false,
    scales: [{
        first: function(value) {
            return value;
        },
        end: function(value) {
            return value;
        },
        next: function(value) {
            var next = new Date(value);
            return new Date(next.setMonth(value.getMonth() + 1));
        },
        label: function(value) {
            return months[value.getMonth()];
        },
        format: function(tickContainer, tickStart, tickEnd) {
            tickContainer.addClass('myCustomClass');
        }
    }]
});

d3.xml('http://upload.wikimedia.org/wikipedia/commons/3/32/Blank_US_Map.svg', 'image/svg+xml', function(xml) {
    var svg = d3.select('#svgDiv').append('svg')
        .attr('width', width)
        .attr('height', height)
        .attr('class', 'center-block')
        .attr('id', 'usSvg')
        .attr('viewBox', '0 0 969 593')
        .attr('perserveAspectRatio', 'xMinYMid');

    var chart = $('#usSvg'),
        aspect = chart.width() / chart.height(),
        container = chart.parent().parent().parent();

    angular.element(window).on('resize', function() {
        var targetWidth = container.width();
        chart.attr('width', targetWidth);
        chart.attr('height', Math.round(targetWidth / aspect));
    }).trigger('resize');

    var usSvg = document.querySelector('#usSvg');
    usSvg.appendChild(xml.documentElement);
    draw(new Date(minDate), new Date(minDate.valueOf() + (1000 * 3600 * 24) * intervalDay), result);
});

$('#slider').on('valuesChanged', function(e, data) {
    //$('#usSvg').remove();
    //console.log('Something moved. min: ' + data.values.min + ' max: ' + data.values.max);
    draw(new Date(data.values.min), new Date(data.values.max), result);
});

////////////////////////////////////////////////////////////////////////////
var play = function() {
    var dateValues = $('#slider').dateRangeSlider('values');
    setTimeout(function() {
        $('#slider').dateRangeSlider('values', dateValues.max, new Date(dateValues.max.valueOf() + (1000 * 3600 * 24) * intervalDay));
        if (dateValues.max.valueOf() + (1000 * 3600 * 24) * intervalDay < maxDate.valueOf()) {
            play();
        }
        else {
            $('#slider').dateRangeSlider('values', dateValues.max, maxDate);
        }
    }, 1000);
};<commit_msg>Graph4 improvement<commit_after>'use strict';

$('head').append('<link rel="stylesheet" href="js/jqrangeslider/dest/css/iThing-min.css" type="text/css" />');
$('#svgDiv').append('

');
$('#svgDiv').append('
<button type="button" class="btn btn-default btn-primary" onClick="play()">Play</button>

<button type="button" class="btn btn-default btn-primary" onClick="reset()">Reset</button>
');

var stateTitle = [{
    'name': 'Alabama',
    'abbreviation': 'AL'
}, {
    'name': 'Alaska',
    'abbreviation': 'AK'
}, {
    'name': 'American Samoa',
    'abbreviation': 'AS'
}, {
    'name': 'Arizona',
    'abbreviation': 'AZ'
}, {
    'name': 'Arkansas',
    'abbreviation': 'AR'
}, {
    'name': 'California',
    'abbreviation': 'CA'
}, {
    'name': 'Colorado',
    'abbreviation': 'CO'
}, {
    'name': 'Connecticut',
    'abbreviation': 'CT'
}, {
    'name': 'Delaware',
    'abbreviation': 'DE'
}, {
    'name': 'District Of Columbia',
    'abbreviation': 'DC'
}, {
    'name': 'Federated States Of Micronesia',
    'abbreviation': 'FM'
}, {
    'name': 'Florida',
    'abbreviation': 'FL'
}, {
    'name': 'Georgia',
    'abbreviation': 'GA'
}, {
    'name': 'Guam',
    'abbreviation': 'GU'
}, {
    'name': 'Hawaii',
    'abbreviation': 'HI'
}, {
    'name': 'Idaho',
    'abbreviation': 'ID'
}, {
    'name': 'Illinois',
    'abbreviation': 'IL'
}, {
    'name': 'Indiana',
    'abbreviation': 'IN'
}, {
    'name': 'Iowa',
    'abbreviation': 'IA'
}, {
    'name': 'Kansas',
    'abbreviation': 'KS'
}, {
    'name': 'Kentucky',
    'abbreviation': 'KY'
}, {
    'name': 'Louisiana',
    'abbreviation': 'LA'
}, {
    'name': 'Maine',
    'abbreviation': 'ME'
}, {
    'name': 'Marshall Islands',
    'abbreviation': 'MH'
}, {
    'name': 'Maryland',
    'abbreviation': 'MD'
}, {
    'name': 'Massachusetts',
    'abbreviation': 'MA'
}, {
    'name': 'Michigan',
    'abbreviation': 'MI'
}, {
    'name': 'Minnesota',
    'abbreviation': 'MN'
}, {
    'name': 'Mississippi',
    'abbreviation': 'MS'
}, {
    'name': 'Missouri',
    'abbreviation': 'MO'
}, {
    'name': 'Montana',
    'abbreviation': 'MT'
}, {
    'name': 'Nebraska',
    'abbreviation': 'NE'
}, {
    'name': 'Nevada',
    'abbreviation': 'NV'
}, {
    'name': 'New Hampshire',
    'abbreviation': 'NH'
}, {
    'name': 'New Jersey',
    'abbreviation': 'NJ'
}, {
    'name': 'New Mexico',
    'abbreviation': 'NM'
}, {
    'name': 'New York',
    'abbreviation': 'NY'
}, {
    'name': 'North Carolina',
    'abbreviation': 'NC'
}, {
    'name': 'North Dakota',
    'abbreviation': 'ND'
}, {
    'name': 'Northern Mariana Islands',
    'abbreviation': 'MP'
}, {
    'name': 'Ohio',
    'abbreviation': 'OH'
}, {
    'name': 'Oklahoma',
    'abbreviation': 'OK'
}, {
    'name': 'Oregon',
    'abbreviation': 'OR'
}, {
    'name': 'Palau',
    'abbreviation': 'PW'
}, {
    'name': 'Pennsylvania',
    'abbreviation': 'PA'
}, {
    'name': 'Puerto Rico',
    'abbreviation': 'PR'
}, {
    'name': 'Rhode Island',
    'abbreviation': 'RI'
}, {
    'name': 'South Carolina',
    'abbreviation': 'SC'
}, {
    'name': 'South Dakota',
    'abbreviation': 'SD'
}, {
    'name': 'Tennessee',
    'abbreviation': 'TN'
}, {
    'name': 'Texas',
    'abbreviation': 'TX'
}, {
    'name': 'Utah',
    'abbreviation': 'UT'
}, {
    'name': 'Vermont',
    'abbreviation': 'VT'
}, {
    'name': 'Virgin Islands',
    'abbreviation': 'VI'
}, {
    'name': 'Virginia',
    'abbreviation': 'VA'
}, {
    'name': 'Washington',
    'abbreviation': 'WA'
}, {
    'name': 'West Virginia',
    'abbreviation': 'WV'
}, {
    'name': 'Wisconsin',
    'abbreviation': 'WI'
}, {
    'name': 'Wyoming',
    'abbreviation': 'WY'
}];
/*var consolidateToState = function(data) {
    var result = d3.map();
    data.forEach(function(element) {
        stateTitle.forEach(function(state) {
            if (element[0].indexOf(state.name + ', USA') > -1 || element[0].indexOf(', ' + state.abbreviation) > -1) {
                if (result.has(state.abbreviation)) {
                    var cnt = result.get(state.abbreviation);
                    cnt = cnt + element[2];
                    result.set(state.abbreviation, cnt);
                }
                else {
                    result.set(state.abbreviation, element[2]);
                }
            }
        });
    });
    return result;
};*/

var consolidateToDate = function(data) {
    var result = d3.map();
    data.forEach(function(element) {
        var stateAbrivation = '';
        stateTitle.forEach(function(state) {
            if (element[0].indexOf(state.name + ', USA') > -1 || element[0].indexOf(', ' + state.abbreviation) > -1) {
                stateAbrivation = state.abbreviation;
            }
        });
        if (stateAbrivation !== '') {
            if (result.has(new Date(element[1]))) {
                var mapDate = result.get(new Date(element[1]));
                if (mapDate.has(stateAbrivation)) {
                    var cnt = mapDate.get(stateAbrivation);
                    cnt = cnt + element[2];
                    mapDate.set(stateAbrivation, cnt);
                }
                else {
                    mapDate.set(stateAbrivation, element[2]);
                }
                result.set(new Date(element[1]), mapDate);
            }
            else {
                var mapDate2 = d3.map();
                mapDate2.set(stateAbrivation, element[2]);
                result.set(new Date(element[1]), mapDate2);
            }
        }
    });
    return result;
};

var svgDiv = document.querySelector('#svgDiv');
var resultData = angular.element(svgDiv).scope().query.result;
var result = consolidateToDate(resultData);

var minDate = d3.min(result.entries(), function(d) {
    var date = new Date(d.key);
    return date;
});
var maxDate = d3.max(result.entries(), function(d) {
    var date = new Date(d.key);
    return date;
});

var width = 969,
    height = 593;

var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];

var draw = function(firstDate, lastDate, data) {
    var resultData = d3.map();
    stateTitle.forEach(function(element) {
        resultData.set(element.abbreviation, 0);
    });
    data.entries().forEach(function(element) {
        var date2 = new Date(element.key);
        firstDate.setDate(firstDate.getDate() - 1);

        if (firstDate < date2 && date2 < lastDate) {
            element.value.entries().forEach(function(element) {
                if (resultData.has(element.key)) {
                    var cnt = resultData.get(element.key);
                    cnt = cnt + element.value;
                    resultData.set(element.key, cnt);
                }
                else {
                    resultData.set(element.key, element.value);
                }
            });
        }
    });

    var max = d3.max(resultData.entries(), function(d) {
        return d.value;
    });
    var min = d3.min(resultData.entries(), function(d) {
        return d.value;
    });
    console.log(max + ',' + min);

    var color = d3.scale.linear()
        .domain([min, max])
        .range(['#deebf7', '#00003f']);

    d3.select('#AK').remove();
    d3.select('#path57').remove();
    d3.select('#HI').remove();

    resultData.entries().forEach(function(element) {
        d3.select('#' + element.key)
            .transition().duration(800)
            .style('fill', function() {
                if (element.value === 0) {
                    return '#d3d3d3';
                }
                return color(element.value);
            });
    });
};

var intervalDay = 7;
$('#slider').dateRangeSlider({
    bounds: {
        min: new Date(minDate),
        max: new Date(maxDate)
    },
    defaultValues: {
        min: new Date(minDate),
        max: new Date(minDate.valueOf() + (1000 * 3600 * 24) * intervalDay)
    },
    enabled: false,
    scales: [{
        first: function(value) {
            return value;
        },
        end: function(value) {
            return value;
        },
        next: function(value) {
            var next = new Date(value);
            return new Date(next.setMonth(value.getMonth() + 1));
        },
        label: function(value) {
            return months[value.getMonth()];
        },
        format: function(tickContainer, tickStart, tickEnd) {
            tickContainer.addClass('myCustomClass');
        }
    }]
});

d3.xml('http://upload.wikimedia.org/wikipedia/commons/3/32/Blank_US_Map.svg', 'image/svg+xml', function(xml) {
    var svg = d3.select('#svgDiv').append('svg')
        .attr('width', width)
        .attr('height', height)
        .attr('class', 'center-block')
        .attr('id', 'usSvg')
        .attr('viewBox', '0 0 969 593')
        .attr('perserveAspectRatio', 'xMinYMid');

    var chart = $('#usSvg'),
        aspect = chart.width() / chart.height(),
        container = chart.parent().parent().parent();

    angular.element(window).on('resize', function() {
        var targetWidth = container.width();
        chart.attr('width', targetWidth);
        chart.attr('height', Math.round(targetWidth / aspect));
    }).trigger('resize');

    var usSvg = document.querySelector('#usSvg');
    usSvg.appendChild(xml.documentElement);
    draw(new Date(minDate), new Date(minDate.valueOf() + (1000 * 3600 * 24) * intervalDay), result);
});

$('#slider').on('valuesChanged', function(e, data) {
    //$('#usSvg').remove();
    //console.log('Something moved. min: ' + data.values.min + ' max: ' + data.values.max);
    draw(new Date(data.values.min), new Date(data.values.max), result);
});

////////////////////////////////////////////////////////////////////////////
var play = function() {
    var dateValues = $('#slider').dateRangeSlider('values');
    setTimeout(function() {
        $('#slider').dateRangeSlider('values', dateValues.max, new Date(dateValues.max.valueOf() + (1000 * 3600 * 24) * intervalDay));
        if (dateValues.max.valueOf() + (1000 * 3600 * 24) * intervalDay < maxDate.valueOf()) {
            play();
        }
        else {
            $('#slider').dateRangeSlider('values', dateValues.max, maxDate);
        }
    }, 1000);
};
var reset = function(){
    $('#slider').dateRangeSlider('values', minDate, new Date(minDate.valueOf() + (1000 * 3600 * 24) * intervalDay));
};<|endoftext|>


<commit_before>var npm = require('npm'),
    path = require('path'),
    http = require('http'),
    targz = require('tar.gz'),
    fs = require('fs'),
    manifest = require('./manifest'),
    os = require('os'),
    rc = require('rc'),
    plugmanConfigDir = path.resolve(process.env.HOME, '.plugman'),
    plugmanCacheDir = path.resolve(plugmanConfigDir, 'cache');

function handleError(err, cb) {
    if(typeof cb == 'function') {
        return cb(err);
    }
    throw err;
}

/**
 * @method getPackageInfo
 * @param {String} args Package names
 * @param {Function} cb callback
 */
function getPackageInfo(args, cb) {
    var thing = args.length ? args.shift().split("@") : [],
                              name = thing.shift(),
                              version = thing.join("@");

    version = version ? version : 'latest';

    var settings = module.exports.settings;

    http.get(settings.registry + '/' + name + '/' + version, function(res) {
         if(res.statusCode != 200) {
                 var err = new Error('Error');
                 if (cb) cb(err);
                 else throw err;
         } else {
             var info = '';
             res.on('data', function(chunk) {
                info += chunk;
             });
             res.on('end', function() {
                 cb(null, JSON.parse(info));
             });
         }
    }).on('error', function(err) {
        cb(err);
    });
}

/**
 * @method fetchPackage
 * @param {String} info Package info
 * @param {Function} cb callback
 */
function fetchPackage(info, cb) {
    var settings = module.exports.settings;

    var cached = path.resolve(settings.cache, info.name, info.version, 'package');
    if(fs.existsSync(cached)) {
        cb(null, cached);
    } else {
        var target = os.tmpdir() + info.name;
        var filename = target + '.tgz';
        var filestream = fs.createWriteStream(filename);
        var request = http.get(info.dist.tarball, function(res) {
            if(res.statusCode != 200) {
                var err = new Error('failed to fetch the plugin archive');
                if (cb) cb(err);
                else throw err;
            } else {
                res.pipe(filestream);
                filestream.on('finish', function() {
                    var decompress = new targz().extract(filename, target, function(err) {
                        cb(err, path.resolve(target, 'package'));
                    });
                });
            }
        });
    }
}

module.exports = {
    settings: null,
    /**
     * @method config
     * @param {Array} args Command argument
     * @param {Function} cb Command callback
     */
    config: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            npm.load(settings, function(er) {
                if (er) return handleError(er);
                npm.commands.config(args, cb);
            });
        });
    },
    /**
     * @method adduser
     * @param {Array} args Command argument
     * @param {Function} cb Command callback
     */
    adduser: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            npm.load(settings, function(er) {
                if (er) return handleError(er);
                npm.commands.adduser(args, cb);
            });
        });
    },
    /**
     * @method publish
     * @param {Array} args Command argument
     * @param {Function} cb Command callback
     */
    publish: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            manifest.generatePackageJsonFromPluginXml(args[0]);
            npm.load(settings, function(er) {
                if (er) return handleError(er);
                npm.commands.publish(args, function(err, data) {
                    fs.unlink(path.resolve(args[0], 'package.json'));
                    cb(err, data);
                });
            });
        });
    },
    /**
     * @method search
     * @param {Array} args Array of keywords
     * @param {Function} cb Command callback
     */
    search: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            npm.load(settings, function(er) {
                if (er) return handleError(er, cb);
                npm.commands.search(args, true, cb);
            });
        });
    },
    /**
     * @method unpublish
     * @param {Array} args Command argument
     * @param {Function} cb Command callback
     */
    unpublish: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            npm.load(settings, function(er) {
                if (er) return handlError(er);
                npm.commands.unpublish(args, function(err, d) {
                    if(err) return handleError(err, cb);
                    npm.commands.cache(["clean"], cb);
                });
            });
        });
    },
    /**
     * @method fetch
     * @param {String} name Plugin name
     * @param {Function} cb Command callback
     */
    fetch: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            getPackageInfo(args, function(err, info) {
                if(err) return handleError(err, cb)
                fetchPackage(info, cb);
            });
        });
    }
}

/**
 * @method initSettings
 * @param {Function} cb callback
 */
function initSettings(cb) {
    var settings = module.exports.settings;
    if(typeof cb != 'function') throw new Error('Please provide a callback');
    // check if settings already set
    if(settings != null) return cb(null, settings);

    // setting up settings
    // obviously if settings dir does not exist settings is going to be empty
    if(!fs.existsSync(plugmanConfigDir)) {
        fs.mkdirSync(plugmanConfigDir);
        fs.mkdirSync(plugmanCacheDir);
    }

    settings =
    module.exports.settings =
    rc('plugman', {
         cache: plugmanCacheDir,
         force: true,
         registry: 'http://registry.cordova.io',
         logstream: fs.createWriteStream(path.resolve(plugmanConfigDir, 'plugman.log')),
         userconfig: path.resolve(plugmanConfigDir, 'config')
    });
    cb(null, settings);
}
<commit_msg>CB-4415 fixing possible bugs on windows<commit_after>var npm = require('npm'),
    path = require('path'),
    http = require('http'),
    targz = require('tar.gz'),
    fs = require('fs'),
    manifest = require('./manifest'),
    os = require('os'),
    rc = require('rc'),
    home = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
    plugmanConfigDir = path.resolve(home, '.plugman'),
    plugmanCacheDir = path.resolve(plugmanConfigDir, 'cache');

function handleError(err, cb) {
    if(typeof cb == 'function') {
        return cb(err);
    }
    throw err;
}

/**
 * @method getPackageInfo
 * @param {String} args Package names
 * @param {Function} cb callback
 */
function getPackageInfo(args, cb) {
    var thing = args.length ? args.shift().split("@") : [],
                              name = thing.shift(),
                              version = thing.join("@");

    version = version ? version : 'latest';

    var settings = module.exports.settings;

    http.get(settings.registry + '/' + name + '/' + version, function(res) {
         if(res.statusCode != 200) {
                 var err = new Error('Error');
                 if (cb) cb(err);
                 else throw err;
         } else {
             var info = '';
             res.on('data', function(chunk) {
                info += chunk;
             });
             res.on('end', function() {
                 cb(null, JSON.parse(info));
             });
         }
    }).on('error', function(err) {
        cb(err);
    });
}

/**
 * @method fetchPackage
 * @param {String} info Package info
 * @param {Function} cb callback
 */
function fetchPackage(info, cb) {
    var settings = module.exports.settings;

    var cached = path.resolve(settings.cache, info.name, info.version, 'package');
    if(fs.existsSync(cached)) {
        cb(null, cached);
    } else {
        var target = path.join(os.tmpdir(), info.name);
        var filename = target + '.tgz';
        var filestream = fs.createWriteStream(filename);
        var request = http.get(info.dist.tarball, function(res) {
            if(res.statusCode != 200) {
                var err = new Error('failed to fetch the plugin archive');
                if (cb) cb(err);
                else throw err;
            } else {
                res.pipe(filestream);
                filestream.on('finish', function() {
                    var decompress = new targz().extract(filename, target, function(err) {
                        cb(err, path.resolve(target, 'package'));
                    });
                });
            }
        });
    }
}

module.exports = {
    settings: null,
    /**
     * @method config
     * @param {Array} args Command argument
     * @param {Function} cb Command callback
     */
    config: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            npm.load(settings, function(er) {
                if (er) return handleError(er);
                npm.commands.config(args, cb);
            });
        });
    },
    /**
     * @method adduser
     * @param {Array} args Command argument
     * @param {Function} cb Command callback
     */
    adduser: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            npm.load(settings, function(er) {
                if (er) return handleError(er);
                npm.commands.adduser(args, cb);
            });
        });
    },
    /**
     * @method publish
     * @param {Array} args Command argument
     * @param {Function} cb Command callback
     */
    publish: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            manifest.generatePackageJsonFromPluginXml(args[0]);
            npm.load(settings, function(er) {
                if (er) return handleError(er);
                npm.commands.publish(args, function(err, data) {
                    fs.unlink(path.resolve(args[0], 'package.json'));
                    cb(err, data);
                });
            });
        });
    },
    /**
     * @method search
     * @param {Array} args Array of keywords
     * @param {Function} cb Command callback
     */
    search: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            npm.load(settings, function(er) {
                if (er) return handleError(er, cb);
                npm.commands.search(args, true, cb);
            });
        });
    },
    /**
     * @method unpublish
     * @param {Array} args Command argument
     * @param {Function} cb Command callback
     */
    unpublish: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            npm.load(settings, function(er) {
                if (er) return handlError(er);
                npm.commands.unpublish(args, function(err, d) {
                    if(err) return handleError(err, cb);
                    npm.commands.cache(["clean"], cb);
                });
            });
        });
    },
    /**
     * @method fetch
     * @param {String} name Plugin name
     * @param {Function} cb Command callback
     */
    fetch: function(args, cb) {
        initSettings(function(err, settings) {
            if(err) return handleError(err, cb);
            getPackageInfo(args, function(err, info) {
                if(err) return handleError(err, cb)
                fetchPackage(info, cb);
            });
        });
    }
}

/**
 * @method initSettings
 * @param {Function} cb callback
 */
function initSettings(cb) {
    var settings = module.exports.settings;
    if(typeof cb != 'function') throw new Error('Please provide a callback');
    // check if settings already set
    if(settings != null) return cb(null, settings);

    // setting up settings
    // obviously if settings dir does not exist settings is going to be empty
    if(!fs.existsSync(plugmanConfigDir)) {
        fs.mkdirSync(plugmanConfigDir);
        fs.mkdirSync(plugmanCacheDir);
    }

    settings =
    module.exports.settings =
    rc('plugman', {
         cache: plugmanCacheDir,
         force: true,
         registry: 'http://registry.cordova.io',
         logstream: fs.createWriteStream(path.resolve(plugmanConfigDir, 'plugman.log')),
         userconfig: path.resolve(plugmanConfigDir, 'config')
    });
    cb(null, settings);
}
<|endoftext|>