<commit_before>chrome.extension.sendMessage({}, function(response) {

  var settings = {
    togglePlayAndPauseKeyCode: 80,  // default: P
    jumpToBeginningKeyCode:    72,  // defualt: H
    jumpToEndKeyCode:          69,  // default: E
    rewindTimeKeyCode:         65,  // default: A
    advanceTimeKeyCode:        83,  // default: S
    speedDownKeyCode:          68,  // default: D
    speedUpKeyCode:            85,  // default: U
    resetSpeedKeyCode:         82,  // default: R
    partialLoopKeyCode:        76,  // default: L
    skipTimeAmount:             5,  // default: 5
  };

  chrome.storage.sync.get(settings, function(storage) {
    settings.togglePlayAndPauseKeyCode = Number(storage.togglePlayAndPauseKeyCode);
    settings.jumpToBeginningKeyCode    = Number(storage.jumpToBeginningKeyCode);
    settings.jumpToEndKeyCode          = Number(storage.jumpToEndKeyCode);
    settings.rewindTimeKeyCode         = Number(storage.rewindTimeKeyCode);
    settings.advanceTimeKeyCode        = Number(storage.advanceTimeKeyCode);
    settings.speedDownKeyCode          = Number(storage.speedDownKeyCode);
    settings.speedUpKeyCode            = Number(storage.speedUpKeyCode);
    settings.resetSpeedKeyCode         = Number(storage.resetSpeedKeyCode);
    settings.partialLoopKeyCode        = Number(storage.partialLoopKeyCode);
    settings.skipTimeAmount            = Number(storage.skipTimeAmount);
  });

  // グローバル変数
  var player = document.getElementsByTagName('video')[0];
  var loopStatus = 0;
  var loopStart;
  var loopEnd;
  var flag = 0;
  var loopTimeoutID;
  var removeStatusBoxTimeoutID;

  // キーが押されたかどうかを判定
  document.addEventListener('keydown', function(event) {

    // 入力フォームにフォーカスがあるときはショートカットを無効化
    if ((document.activeElement.nodeName === 'INPUT'
    || document.activeElement.nodeName === 'TEXTAREA'
    || document.activeElement.getAttribute('type') === 'text')
    || document.activeElement.isContentEditable === true) {
      return false;
    } else {
      activeBlur();
    }

    // cmd, shift, ctrl, alt をエスケープ
    if (event.metaKey || event.shiftKey || event.ctrlKey || event.altKey) {
      return false;
    }

    // ショートカットキーから関数を呼び出す
    switch (event.keyCode) {
      // オプションで変更可能なキーコード
      case settings.togglePlayAndPauseKeyCode: togglePlayAndPause(); break; // default: P
      case settings.jumpToBeginningKeyCode:    jumpToBeginning();    break; // default: H
      case settings.jumpToEndKeyCode:          jumpToEnd();          break; // default: E
      case settings.rewindTimeKeyCode:         rewindTime();         break; // default: A
      case settings.advanceTimeKeyCode:        advanceTime();        break; // default: S
      case settings.speedDownKeyCode:          speedDown();          break; // default: D
      case settings.speedUpKeyCode:            speedUp();            break; // default: U
      case settings.resetSpeedKeyCode:         resetSpeed();         break; // default: R

      // 固定のキーコード
      case 32: event.preventDefault(); togglePlayAndPause(); break; // space
      case 37:                         rewindTime();         break; // left-arrow
      case 39:                         advanceTime();        break; // right-arrow
      case 27: activeBlur();           resetLoopStatus();    break; // esc
    }

    // 数字のキーを押すとその数字に対応する割合まで動画を移動する
    // キーボードの 3 を押すと動画全体の 30% の位置に移動する
    // 固定のキーコード
    if (event.keyCode >= 48 && event.keyCode <= 57) {
      jumpToTimerRatio(event.keyCode);
    }

    // 部分ループ再生のステータスを記録
    // オプションで変更可能なキーコード
    // default: L
    if (event.keyCode == settings.partialLoopKeyCode) {
      if (loopStatus === undefined) {
        loopStatus = 0;
      }
      loopStatus++;
      partialLoop();
    }

  });

  // 再生スピードの変更を監視する
  player.onratechange = function() {
    observeSpeed(player.playbackRate);
  };

  // 再生/停止
  function togglePlayAndPause() {
    if (player.paused === true)
      player.play();
    else
      player.pause();
    scrollToPlayer();
  };

  // 数秒巻き戻し
  function rewindTime() {
    player.currentTime -= settings.skipTimeAmount;
    scrollToPlayer();
  };

  // 数秒早送り
  function advanceTime() {
    player.currentTime += settings.skipTimeAmount;
    scrollToPlayer();
  };

  // 再生スピードダウン
  function speedDown() {
    player.playbackRate = floorFormat((player.playbackRate - 0.09), 1);
    statusBox('playbackRate', adjustSpeedStatus(player.playbackRate));
    scrollToPlayer();
  }

  // 再生スピードアップ
  function speedUp() {
    player.playbackRate = floorFormat((player.playbackRate + 0.11), 1);
    statusBox('playbackRate', adjustSpeedStatus(player.playbackRate));
    scrollToPlayer();
  }

  // 再生スピードリセット
  function resetSpeed() {
    player.playbackRate = 1.0;
    statusBox('playbackRate', adjustSpeedStatus(player.playbackRate));
    scrollToPlayer();
  }

  // 動画の最初の位置に移動する
  function jumpToBeginning() {
    player.currentTime = player.seekable.start(0);
    scrollToPlayer();
  };

  // 動画の最後の位置に移動する
  function jumpToEnd() {
    player.currentTime = player.seekable.end(0);
    scrollToPlayer();
  };

  // 数字に対応する割合まで動画を移動する
  function jumpToTimerRatio(timerRatio) {
    timerRatio = (timerRatio - 48) / 10;
    player.currentTime = player.seekable.end(0) * timerRatio;
    scrollToPlayer();
  };

  // 部分ループ再生
  function partialLoop() {
    if (loopStatus === 1) {
      loopStart = player.currentTime;
      statusBox('set', 'Set');
    }
    else if (loopStatus === 2) {
      if (flag !== 1) {
        loopEnd = player.currentTime;
        flag = 1;
        statusBox('loop', 'Loop!');
      }
      loopTimeoutID = setTimeout(function() {
        if (player.currentTime >= loopEnd || player.currentTime < loopStart) {
          player.currentTime = loopStart;
        }
        if (loopStatus === 3) {
          clearTimeout(loopTimeoutID);
          loopStatus = 0;
          flag = 0;
          statusBox('restore', 'Restore');
          return false;
        }
        partialLoop();
      }, 100);
    }
  };

  // アクティブフォーカスを外す
  function activeBlur() {
    document.activeElement.blur();
  };

  // ループステータスをリセットする
  function resetLoopStatus() {
    if (loopStatus !== 0) {
      clearTimeout(loopTimeoutID);
      loopStatus = 0;
      flag = 0;
      statusBox('reset', 'Restore');
    }
  };

  // 小数点第(n+1)位を切り捨てて小数点第n位まで求める
  function floorFormat(number, n) {
    var _pow = Math.pow(10, n);
    return Math.floor(number * _pow) / _pow;
  };

  // 動画プレイヤーのある位置までスクロールする
  function scrollToPlayer() {
    var rect = player.getBoundingClientRect();
    var positionY = rect.top;
    var dElm = document.documentElement;
    var dBody = document.body;
    var scrollY = dElm.scrollTop || dBody.scrollTop;
    var y = positionY + scrollY - 100;
    window.scrollTo(0, y);
  };

  // 部分ループ再生のステータスを表示する
  function statusBox(status, statusStr) {
    if (status === 'set') {
      var videoStatus = '' + statusStr + '';
    }
    else {
      var videoStatus = '' + statusStr + '';
    }

    $('.video-status').remove();
    if (status === 'loop') {
      $('.video-status-keep-showing').remove();
    }
    if (status === 'reset') {
      $('.video-status-keep-showing').remove();
      clearTimeout(removeStatusBoxTimeoutID);
    }

    $(videoStatus).insertBefore('video');

    if ($('span').hasClass('video-status') && $('span').hasClass('video-status-keep-showing')) {
      $('.video-status-keep-showing').css('display', 'none');
      clearTimeout(removeStatusBoxTimeoutID);
      removeStatusBoxTimeoutID = setTimeout(function() {
        $('.video-status').remove();
        $('.video-status-keep-showing').css('display', 'inline-block');
      }, 1000);
    }
    else {
      $('.video-status').fadeOut(1000, function() {
        $(this).remove();
      });
    }
  };

  // 再生スピードの上限と下限を設定する
  function observeSpeed(speedChecker) {
    if (speedChecker < 0.5) {
      player.playbackRate = 0.5;
    }
    else if (speedChecker > 4.0) {
      player.playbackRate = 4.0;
    }
  };

  // 表示される再生スピードを調整する
  function adjustSpeedStatus(speedStatus) {
    if (speedStatus < 0.5) {
      speedStatus = 0.5;
    }
    else if (speedStatus > 4.0) {
      speedStatus = 4.0;
    }
    return speedStatus.toFixed(1);
  };

});
<commit_msg>:bangbang: Ignore original key event, and get video element correctly<commit_after>chrome.extension.sendMessage({}, function(response) {
  var settings = {
    togglePlayAndPauseKeyCode: 80,  // default: P
    jumpToBeginningKeyCode:    72,  // defualt: H
    jumpToEndKeyCode:          69,  // default: E
    rewindTimeKeyCode:         65,  // default: A
    advanceTimeKeyCode:        83,  // default: S
    speedDownKeyCode:          68,  // default: D
    speedUpKeyCode:            85,  // default: U
    resetSpeedKeyCode:         82,  // default: R
    partialLoopKeyCode:        76,  // default: L
    skipTimeAmount:             5,  // default: 5
  };

  chrome.storage.sync.get(settings, function(storage) {
    settings.togglePlayAndPauseKeyCode = Number(storage.togglePlayAndPauseKeyCode);
    settings.jumpToBeginningKeyCode    = Number(storage.jumpToBeginningKeyCode);
    settings.jumpToEndKeyCode          = Number(storage.jumpToEndKeyCode);
    settings.rewindTimeKeyCode         = Number(storage.rewindTimeKeyCode);
    settings.advanceTimeKeyCode        = Number(storage.advanceTimeKeyCode);
    settings.speedDownKeyCode          = Number(storage.speedDownKeyCode);
    settings.speedUpKeyCode            = Number(storage.speedUpKeyCode);
    settings.resetSpeedKeyCode         = Number(storage.resetSpeedKeyCode);
    settings.partialLoopKeyCode        = Number(storage.partialLoopKeyCode);
    settings.skipTimeAmount            = Number(storage.skipTimeAmount);
  });

  // グローバル変数
  var player;
  var loopStatus = 0;
  var loopStart;
  var loopEnd;
  var flag = 0;
  var loopTimeoutID;
  var removeStatusBoxTimeoutID;
  var getVideoTimeoutID;

  // video要素を取得する
  function getVideoElement() {
    if (document.getElementsByTagName('video')[0] !== undefined) {
      player = document.getElementsByTagName('video')[0];
      clearTimeout(getVideoTimeoutID);
      observeSpeed();
      return false;
    }
    getVideoTimeoutID = setTimeout(function() {
      getVideoElement();
    }, 10);
  };
  getVideoElement();

  // キーが押されたかどうかを判定
  window.addEventListener('keydown', function(event) {

    Object.keys(settings).forEach(function(key) {
      if (event.keyCode == settings[key]) {
        event.stopPropagation();
      }
    });

    // 入力フォームにフォーカスがあるときはショートカットを無効化
    if ((document.activeElement.nodeName === 'INPUT'
    || document.activeElement.nodeName === 'TEXTAREA'
    || document.activeElement.getAttribute('type') === 'text')
    || document.activeElement.isContentEditable === true) {
      return false;
    } else {
      activeBlur();
    }

    // cmd, ctrl, alt をエスケープ
    if (event.metaKey || event.ctrlKey || event.altKey) {
      return false;
    }

    // ショートカットキーから関数を呼び出す
    switch (event.keyCode) {
      // オプションで変更可能なキーコード
      case settings.togglePlayAndPauseKeyCode: togglePlayAndPause(); break; // default: P
      case settings.jumpToBeginningKeyCode:    jumpToBeginning();    break; // default: H
      case settings.jumpToEndKeyCode:          jumpToEnd();          break; // default: E
      case settings.rewindTimeKeyCode:         rewindTime();         break; // default: A
      case settings.advanceTimeKeyCode:        advanceTime();        break; // default: S
      case settings.speedDownKeyCode:          speedDown();          break; // default: D
      case settings.speedUpKeyCode:            speedUp();            break; // default: U
      case settings.resetSpeedKeyCode:         resetSpeed();         break; // default: R

      // 固定のキーコード
      case 32: event.preventDefault(); togglePlayAndPause(); break; // space
      case 37:                         rewindTime();         break; // left-arrow
      case 39:                         advanceTime();        break; // right-arrow
      case 27: activeBlur();           resetLoopStatus();    break; // esc
    }

    // 数字のキーを押すとその数字に対応する割合まで動画を移動する
    // キーボードの 3 を押すと動画全体の 30% の位置に移動する
    // 固定のキーコード
    if (event.keyCode >= 48 && event.keyCode <= 57) {
      jumpToTimerRatio(event.keyCode);
    }

    // 部分ループ再生のステータスを記録
    // オプションで変更可能なキーコード
    // default: L
    if (event.keyCode == settings.partialLoopKeyCode) {
      if (loopStatus === undefined) {
        loopStatus = 0;
      }
      loopStatus++;
      partialLoop();
    }

  }, true);

  // 再生スピードの変更を監視する
  function observeSpeed() {
    player.onratechange = function() {
      setSpeedRange(player.playbackRate);
    };
  };

  // 再生/停止
  function togglePlayAndPause() {
    if (player.paused === true)
      player.play();
    else
      player.pause();
    scrollToPlayer();
  };

  // 数秒巻き戻し
  function rewindTime() {
    player.currentTime -= settings.skipTimeAmount;
    scrollToPlayer();
  };

  // 数秒早送り
  function advanceTime() {
    player.currentTime += settings.skipTimeAmount;
    scrollToPlayer();
  };

  // 再生スピードダウン
  function speedDown() {
    player.playbackRate = floorFormat((player.playbackRate - 0.09), 1);
    statusBox('playbackRate', adjustSpeedStatus(player.playbackRate));
    scrollToPlayer();
  }

  // 再生スピードアップ
  function speedUp() {
    player.playbackRate = floorFormat((player.playbackRate + 0.11), 1);
    statusBox('playbackRate', adjustSpeedStatus(player.playbackRate));
    scrollToPlayer();
  }

  // 再生スピードリセット
  function resetSpeed() {
    player.playbackRate = 1.0;
    statusBox('playbackRate', adjustSpeedStatus(player.playbackRate));
    scrollToPlayer();
  }

  // 動画の最初の位置に移動する
  function jumpToBeginning() {
    player.currentTime = player.seekable.start(0);
    scrollToPlayer();
  };

  // 動画の最後の位置に移動する
  function jumpToEnd() {
    player.currentTime = player.seekable.end(0);
    scrollToPlayer();
  };

  // 数字に対応する割合まで動画を移動する
  function jumpToTimerRatio(timerRatio) {
    timerRatio = (timerRatio - 48) / 10;
    player.currentTime = player.seekable.end(0) * timerRatio;
    scrollToPlayer();
  };

  // 部分ループ再生
  function partialLoop() {
    if (loopStatus === 1) {
      loopStart = player.currentTime;
      statusBox('set', 'Set');
    }
    else if (loopStatus === 2) {
      if (flag !== 1) {
        loopEnd = player.currentTime;
        flag = 1;
        statusBox('loop', 'Loop!');
      }
      loopTimeoutID = setTimeout(function() {
        if (player.currentTime >= loopEnd || player.currentTime < loopStart) {
          player.currentTime = loopStart;
        }
        if (loopStatus === 3) {
          clearTimeout(loopTimeoutID);
          loopStatus = 0;
          flag = 0;
          statusBox('restore', 'Restore');
          return false;
        }
        partialLoop();
      }, 100);
    }
  };

  // アクティブフォーカスを外す
  function activeBlur() {
    document.activeElement.blur();
  };

  // ループステータスをリセットする
  function resetLoopStatus() {
    if (loopStatus !== 0) {
      clearTimeout(loopTimeoutID);
      loopStatus = 0;
      flag = 0;
      statusBox('reset', 'Restore');
    }
  };

  // 小数点第(n+1)位を切り捨てて小数点第n位まで求める
  function floorFormat(number, n) {
    var _pow = Math.pow(10, n);
    return Math.floor(number * _pow) / _pow;
  };

  // 動画プレイヤーのある位置までスクロールする
  function scrollToPlayer() {
    var rect = player.getBoundingClientRect();
    var positionY = rect.top;
    var dElm = document.documentElement;
    var dBody = document.body;
    var scrollY = dElm.scrollTop || dBody.scrollTop;
    var y = positionY + scrollY - 100;
    window.scrollTo(0, y);
  };

  // 部分ループ再生のステータスを表示する
  function statusBox(status, statusStr) {
    if (status === 'set') {
      var videoStatus = '' + statusStr + '';
    }
    else {
      var videoStatus = '' + statusStr + '';
    }

    $('.video-status').remove();
    if (status === 'loop') {
      $('.video-status-keep-showing').remove();
    }
    if (status === 'reset') {
      $('.video-status-keep-showing').remove();
      clearTimeout(removeStatusBoxTimeoutID);
    }

    $(videoStatus).insertBefore('video');

    if ($('span').hasClass('video-status') && $('span').hasClass('video-status-keep-showing')) {
      $('.video-status-keep-showing').css('display', 'none');
      clearTimeout(removeStatusBoxTimeoutID);
      removeStatusBoxTimeoutID = setTimeout(function() {
        $('.video-status').remove();
        $('.video-status-keep-showing').css('display', 'inline-block');
      }, 1000);
    }
    else {
      $('.video-status').fadeOut(1000, function() {
        $(this).remove();
      });
    }
  };

  // 再生スピードの上限と下限を設定する
  function setSpeedRange(speedChecker) {
    if (speedChecker < 0.5) {
      player.playbackRate = 0.5;
    }
    else if (speedChecker > 4.0) {
      player.playbackRate = 4.0;
    }
  };

  // 表示される再生スピードを調整する
  function adjustSpeedStatus(speedStatus) {
    if (speedStatus < 0.5) {
      speedStatus = 0.5;
    }
    else if (speedStatus > 4.0) {
      speedStatus = 4.0;
    }
    return speedStatus.toFixed(1);
  };
});
<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('101100111001101...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hinweis: Wenn Andreas online ist, sieht er dieses Gespräch und kann beitreten.')
                .then(() => 'vorname');
        }
    },

    vorname: {
        prompt: (bot) => bot.say('Wie heissen Sie mit Vornamen?'),
        receive: (bot, message) => {
            var vorname = message.text;
            return bot.setProp('vorname', vorname)
                .then(() => bot.say(`${vorname}, prima.`))
                .then(() => 'nachname');
        }
    },

    nachname: {
        prompt: (bot) => bot.say('Und mit Nachnamen?'),
        receive: (bot, message) => {
            var nachname = message.text;
            return bot.setProp('nachname', nachname)
                .then(() => bot.say(`${nachname}, danke.`))
                .then(() => bot.say('Schreiben Sie hier eine Nachricht an Andreas. Oder unterhalten Sie sich mit mir, indem Sie --bot schreiben!'))
                .then(() => 'register');
        }
    },

    register: {
        receive: (bot, message) => {

            var wollen = message.text;
            var befehl = wollen;
            befehl = befehl.trim();
            befehl = befehl.toUpperCase();

         // System
            if (befehl == "--BOT")          { bot.say('Wollen Sie etwas über seine --Person erfahren, hören, was es --Neues bei ihm gibt oder auf anderem Wege --Kontakt  aufnehmen?'); }
            if (befehl == "--BOT")          { bot.say('Ich bin sozusagen Andreas\' Assistent. Er hat mir vieles beigebracht, das Sie durch Schreiben der mit -- beginnenden Wörter abrufen können:'); }
            if (befehl == "--ABBRECHEN")    { bot.say('Text: Abbruch.'); }

         // Über mich
            if (befehl == "--PERSON")       { bot.say('Text: Person; Links: --Lebenslauf, --Foto.'); }
            if (befehl == "--LEBENSLAUF")   { bot.say('Text: Lebenslauf. %[Lebenslauf öffnen](http://sefzig.net/link/Lebenslauf/)'); }
            if (befehl == "--FOTO")         { bot.say('Text mit http://sefzig.net/text/seiten/SefzignetStartseite/dateien/SefzignetStartseiteFotoLogos.png Bild.'); }
            if (befehl == "--NEUES")        { bot.say('Text: Neues.'); }

         // Kontakt
            if (befehl == "--KONTAKT")      { bot.say('Text: Kontakt mit Webseite; Links: --Twitter, --Slackteam, --Xing. %[Kontakt-Seite öffnen](http://sefzig.net/link/Kontakt/)'); }
            if (befehl == "--SLACKTEAM")    { bot.say('Text: Offenes Slack-Team. %[Offenes Slack-Team](http://sefzig.net/link/Slack/)'); }
            if (befehl == "--XING")         { bot.say('Andreas ist Mitglied bei Xing: %[Xing-Profil ansehen](http://sefzig.net/link/Xing/)'); }
            if (befehl == "--TWITTER")      { bot.say('Andreas ist auf Twitter: %[Twitter-Profil öffnen](http://sefzig.net/link/Twitter/)'); }

         // Vorlage
            if (befehl == "--VORLAGE")      { bot.say('Text: Vorlage.'); }

            return bot.setProp('wollen', wollen)
                .then(() => 'register');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<commit_msg>Script<commit_after>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('101100111001101...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Ich bin Andreas Sefzigs Bot.')
                .then(() => bot.say('Hinweis: Wenn Andreas online ist, sieht er dieses Gespräch und kann beitreten.'))
                .then(() => 'vorname');
        }
    },

    vorname: {
        prompt: (bot) => bot.say('Wie heissen Sie mit Vornamen?'),
        receive: (bot, message) => {
            var vorname = message.text;
            return bot.setProp('vorname', vorname)
                .then(() => bot.say(`${vorname}, prima.`))
                .then(() => 'nachname');
        }
    },

    nachname: {
        prompt: (bot) => bot.say('Und mit Nachnamen?'),
        receive: (bot, message) => {
            var nachname = message.text;
            return bot.setProp('nachname', nachname)
                .then(() => bot.say(`${nachname}, danke.`))
                .then(() => bot.say('Schreiben Sie hier eine Nachricht an Andreas. Oder unterhalten Sie sich mit mir, indem Sie --bot schreiben!'))
                .then(() => 'register');
        }
    },

    register: {
        receive: (bot, message) => {

            var wollen = message.text;
            var befehl = wollen;
            befehl = befehl.trim();
            befehl = befehl.toUpperCase();

         // System
            if (befehl == "--BOT")          { bot.say('Wollen Sie etwas über seine --Person erfahren, hören, was es --Neues bei ihm gibt oder auf anderem Wege --Kontakt  aufnehmen?'); }
            if (befehl == "--BOT")          { bot.say('Ich bin sozusagen Andreas\' Assistent. Er hat mir vieles beigebracht, das Sie durch Schreiben der mit -- beginnenden Wörter abrufen können:'); }
            if (befehl == "--ABBRECHEN")    { bot.say('Text: Abbruch.'); }

         // Über mich
            if (befehl == "--PERSON")       { bot.say('Text: Person; Links: --Lebenslauf, --Foto.'); }
            if (befehl == "--LEBENSLAUF")   { bot.say('Text: Lebenslauf. %[Lebenslauf öffnen](http://sefzig.net/link/Lebenslauf/)'); }
            if (befehl == "--FOTO")         { bot.say('Text mit http://sefzig.net/text/seiten/SefzignetStartseite/dateien/SefzignetStartseiteFotoLogos.png Bild.'); }
            if (befehl == "--NEUES")        { bot.say('Text: Neues.'); }

         // Kontakt
            if (befehl == "--KONTAKT")      { bot.say('Text: Kontakt mit Webseite; Links: --Twitter, --Slackteam, --Xing. %[Kontakt-Seite öffnen](http://sefzig.net/link/Kontakt/)'); }
            if (befehl == "--SLACKTEAM")    { bot.say('Text: Offenes Slack-Team. %[Offenes Slack-Team](http://sefzig.net/link/Slack/)'); }
            if (befehl == "--XING")         { bot.say('Andreas ist Mitglied bei Xing: %[Xing-Profil ansehen](http://sefzig.net/link/Xing/)'); }
            if (befehl == "--TWITTER")      { bot.say('Andreas ist auf Twitter: %[Twitter-Profil öffnen](http://sefzig.net/link/Twitter/)'); }

         // Vorlage
            if (befehl == "--VORLAGE")      { bot.say('Text: Vorlage.'); }

            return bot.setProp('wollen', wollen)
                .then(() => 'register');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
    groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
    groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
    groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
    groet = "Welkom";
}

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('${groet}'),
        receive: () => 'start'
    },

    start: {
            receive: (bot) => {
                return bot.say(`Welkom bij Independer`)
                     .then(() => `askName`);
            }
        },

        askName: {
                prompt: (bot) => bot.say(`Hoe heet je?`),
                receive: (bot,message) => {
                    const name = message.text;
                    return bot.setProp(`name`, name)
                        .then(() => bot.say(`Ok ${name}, hoe kan ik je helpen? \n
                         %[Heb je schade](postback:schade) %[Zoek je een verzekering](reply:zoek)
                          `));
                },
            },

            error: {
        prompt: (bot) => bot.say(`Sorry - kun je dat nog eens zeggen?  Er ging iets mis...`),
        receive: () => `start`
    },

            next: {
          receive: (bot, button) => {
            const choice = button.event;
              return bot.getProp('choice', choice)
                  .then(() => bot.say(`Je koos ${choice}`))
                  .then(() => 'done');
          }
      },

done: {
    receive: () => 'done'
},

finish: {
    receive: () => 'finish'
},

    speak: {
        receive: (bot, message) => {

            let upperText = message.text.trim().toUpperCase();

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                if (!_.has(scriptRules, upperText)) {
                    return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                }

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log(line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });

                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<commit_msg>k<commit_after>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
    groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
    groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
    groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
    groet = "Welkom";
}

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
            receive: (bot) => {
                return bot.say(`${groet} - welkom bij Independer`)
                     .then(() => `askName`);
            }
        },

        askName: {
                prompt: (bot) => bot.say(`Hoe heet je?`),
                receive: (bot,message) => {
                    const name = message.text;
                    return bot.setProp(`name`, name)
                        .then(() => bot.say(`Ok ${name}, hoe kan ik je helpen? \n
                         %[Heb je schade](postback:schade) %[Zoek je een verzekering](reply:zoek)
                          `)
                        .then(() => `speak`);
                        );
                },
            },

            error: {
        prompt: (bot) => bot.say(`Sorry - kun je dat nog eens zeggen?  Er ging iets mis...`),
        receive: () => `start`
    },

            next: {
          receive: (bot, button) => {
            const choice = button.event;
              return bot.getProp('choice', choice)
                  .then(() => bot.say(`Je koos ${choice}`))
                  .then(() => 'done');
          }
      },

done: {
    receive: () => 'done'
},

finish: {
    receive: () => 'finish'
},

    speak: {
        receive: (bot, message) => {

            let upperText = message.text.trim().toUpperCase();

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                if (!_.has(scriptRules, upperText)) {
                    return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                }

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log(line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });

                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<|endoftext|>


<commit_before>// Time to next rendez-vous
var nextrdv = new Date("Sept 11, 2020 18:00:00").getTime();
var x = setInterval(function () {
    var now = new Date().getTime();
    var tonextrdv = nextrdv - now;
    var days = Math.floor(tonextrdv / (1000 * 60 * 60 * 24));
    if (days < 10) {
        days = '0' + days
    }
    var hours = Math.floor((tonextrdv % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    if (hours < 10) {
        hours = '0' + hours
    }
    var minutes = Math.floor((tonextrdv % (1000 * 60 * 60)) / (1000 * 60));
    if (minutes < 10) {
        minutes = '0' + minutes
    }
    var seconds = Math.floor((tonextrdv % (1000 * 60)) / 1000);
    if (seconds < 10) {
        seconds = '0' + seconds
    }
    document.getElementById("nextrdv").innerHTML = days + " jours - " + hours + " : " +
        minutes + " : " + seconds;
    if (tonextrdv < 0) {
        clearInterval(x);
        document.getElementById("nextrdv").innerHTML = "I Love You";
    }

}, 1000);

// Time together
var bday = new Date("07/10/20").getTime();
var z = setInterval(function () {
    var bnow = new Date().getTime();
    var tillbday = bnow - bday;
    var bdays = Math.floor(tillbday / (1000 * 60 * 60 * 24));
    if (bdays < 10) {
        bdays = '0' + bdays
    }
    document.getElementById("together").innerHTML = bdays + " jours"
}, 1000);<commit_msg>Update date<commit_after>// Time to next rendez-vous
var nextrdv = new Date("Oct 19, 2020 18:00:00").getTime();
var x = setInterval(function () {
    var now = new Date().getTime();
    var tonextrdv = nextrdv - now;
    var days = Math.floor(tonextrdv / (1000 * 60 * 60 * 24));
    if (days < 10) {
        days = '0' + days
    }
    var hours = Math.floor((tonextrdv % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    if (hours < 10) {
        hours = '0' + hours
    }
    var minutes = Math.floor((tonextrdv % (1000 * 60 * 60)) / (1000 * 60));
    if (minutes < 10) {
        minutes = '0' + minutes
    }
    var seconds = Math.floor((tonextrdv % (1000 * 60)) / 1000);
    if (seconds < 10) {
        seconds = '0' + seconds
    }
    document.getElementById("nextrdv").innerHTML = days + " jours - " + hours + " : " +
        minutes + " : " + seconds;
    if (tonextrdv < 0) {
        clearInterval(x);
        document.getElementById("nextrdv").innerHTML = "I Love You";
    }

}, 1000);

// Time together
var bday = new Date("07/10/20").getTime();
var z = setInterval(function () {
    var bnow = new Date().getTime();
    var tillbday = bnow - bday;
    var bdays = Math.floor(tillbday / (1000 * 60 * 60 * 24));
    if (bdays < 10) {
        bdays = '0' + bdays
    }
    document.getElementById("together").innerHTML = bdays + " jours"
}, 1000);<|endoftext|>


<commit_before>var get = function(id) {
    return document.getElementById(id);
}

var divider = "\n------------------------------------------------------";
console.log("Golden Sun Battle Sim" + divider);
console.log("Enter - Game.commands() - to view all usable functions" + divider);

var that;
var gameCommandsArray = ["adventurer.adventurerData()","adventurer.addToInventory()","adventurer.viewInventory()", "adventurer.addSpell(spell)",
                "adventurer.viewSpells()", "adventurer.setWeapon(woodenMeleeWeapon || woodenRangeWeapon)",
                "adventurer.lotOfPots() -- Adds 50 HP Potions", "adventurer.playerOneHealthItem.use()",
                "adventurer.playerTwoHealthItem.use()", "adventurer.battle()", "adventurer.attack()"];

var Game = {
    gameItems : ["HP Pot", "MP Pot", "Brass Guard", "Wooden Sword", "Wooden Staff"],
    commands : function(){
        var i = 0;
        while(i < gameCommandsArray.length){ console.log(gameCommandsArray[i] + divider); i++ }
    },
    enemy : undefined,
    enemyList : ["Skeleton Warrior", "Vale Rat"],
    gameEnemies : {
        skeleton : {
            name : "Skeleton Warrior",
            health : 40,
            attack : "Skeletal Slash",
            damage : 9,
            itemList: ["Wooden Sword", "HP Pot", "Brass Guard", "Nothing"]
        },
        rat : {
            name : "Vale Rat",
            health : 20,
            attack : "Scratch",
            damage : 7,
            itemList: ["MP Pot", "Wooden Staff", "Nothing"]
        },
    },
    enemyHealth : undefined,
    inBattle : false,

    playerTurn : true
};

var Adventurer = function(name, health, mana) {
    this.name = name;
    this.health = health;
    this.maxHealth = health;
    this.maxOverheal = this.maxHealth * 2;
    this.mana = mana;
    this.inventory = [];
    this.spells = [];
    this.weapon;
    this.level = 1;
    this.attackPower = 1;
    this.spellInUse = false;
    this.currentSpell = "";
    /*var experience = 5;
    var neededExperience = experience * 2;

    this.addExperience = function(experienceGiven){
        experience += experienceGiven;
        console.log(experience);
        console.log(neededExperience);

        if(experience >= neededExperience){
            this.level += 1;
            var previousLevel = this.level - 1;
            console.log(this.name + " has " + "LEVELED UP!" + "(" + previousLevel + "->" + this.level + ")");
            neededExperience = experience * 2;
        }
    }*/

}

var woodenMeleeWeapon = {
    damage : 8,
    name : "Wooden Sword",
    uses : 40,
    info : "Your weathered but trusty wooden sword"
};

var woodenRangeWeapon = {
    damage : 4,
    rangedDamage : 13,
    mana : 5,
    name : "Wooden Staff",
    uses: 40,
    info : "A wooden staff with a rock-hard tip"
};

Adventurer.prototype.addToInventory = function(item) {
    for(i = 0; i < Game.gameItems.length; i++){
        if(item == Game.gameItems[i]){ this.inventory.push(item); }
    }
}

Adventurer.prototype.addSpell = function(spell) {
    this.spells.push(spell);
}

Adventurer.prototype.setWeapon = function(weapon) {
    if(weapon == woodenMeleeWeapon){
        this.weapon = woodenMeleeWeapon;
        this.inventory.push(weapon.name);
    }
    else if(weapon == woodenRangeWeapon){
        this.weapon = woodenRangeWeapon;
        this.inventory.push(weapon.name);
    }
}

var HealthItem = function(adventurer) {
    this.healthItemName = "";
    this.healAmount = 0;

    this.use = function() {
        that = adventurer;
        console.log(that.name);
        for (var x = 0; x < that.inventory.length; x++) {
            if (that.inventory[x] == "HP Pot") {
                this.healthItemName = "HP Pot";
                this.healAmount = 30;
                that.health += this.healAmount;
                console.log(that.name + " Has Used " + this.healthItemName + " to heal for " + this.healAmount + "HP" + divider);
                if (that.health > that.maxHealth && that.health < that.maxOverheal) {
                    var overheal = that.health - that.maxHealth;
                    console.log("Overhealed by " + overheal + "!");
                } else if (that.health > that.maxOverheal) {
                    console.log(that.name + " cannot " + "be " + "overhealed " + "anymore!");
                    that.health = that.maxOverheal;
                }
                that.inventory.splice(x, 1);
                return;
            }
        }
        console.log("No Health Items in Inventory" + divider);
    }
}

Adventurer.prototype.adventurerData = function() {
    console.log(this.name);
    console.log("Health: " + this.health);
    console.log("Mana: " + this.mana + divider);
}

Adventurer.prototype.viewSpells = function() {
    for (var i = 0; i < this.spells.length; i++) {
        console.log(this.spells[i] + divider);
    }
}

Adventurer.prototype.useSpell = function(spell) {
    if(this.spellInUse == true) { console.log(this.name + " is already charging " + this.currentSpell); }
    else{
    for (var i = 0; i < this.spells.length; i++) {
        if (this.spells[i] == spell) {
            if(Game.enemy == undefined){
                this.spellInUse = false;
                console.log("What are you aiming that " + spell + " at?" + divider);
                return;
            }
            else{
            this.currentSpell = spell;
            this.spellInUse = true;
            console.log(this.name + " is charging " + this.currentSpell + "...");
            playerTurn = false;
            return;
        }
        }
    }
    console.log("You don't know how to do that..." + divider);
}
}

Adventurer.prototype.viewInventory = function() {
    for (var x = 0; x < this.inventory.length; x++) {
        console.log(this.inventory[x] + divider);
    }
    if (this.inventory.length == 0) {
        console.log(this.name + "'s" + " bag is empty");
    }
}

Adventurer.prototype.lotOfPots = function() {
    for (var i = 0; i < 50; i++) {
        this.addToInventory("HP Pot");
    }
}

Adventurer.prototype.battle = function(){
    if(Game.enemy != undefined){
        console.log("You're already in a battle!");
    }
    else{
    Game.inBattle = true;
    Game.enemy = Game.enemyList[Math.floor(Math.random()*Game.enemyList.length)];
    if(Game.enemy == "Skeleton Warrior"){ Game.enemy = Game.gameEnemies.skeleton; }
    else{ Game.enemy = Game.gameEnemies.rat; }
    Game.enemyHealth = Game.enemy.health;
    console.log(this.name + "'s" + " party has encountered " + Game.enemy.name + "(HP:" + Game.enemy.health + ")");
}
}

Adventurer.prototype.attack = function(){
    var damage;
    if(Game.enemyHealth > 0){
    while(Game.playerTurn){
        /*Spell progress
        if(this.spellInUse == true){
            for(var x = 0; x < spellList.length; x++){
                if(this.currentSpell == spellList[x].name && spellList[x].hostile == true){
                    damage = spellList[x].effect;
                    console.log("testing: " + damage);
                }
            }
        }
        else{*/
        damage = this.weapon.damage + (this.attackPower * 0.5);
    //}
        Game.enemyHealth -= damage;
        console.log(this.name +  " hit " + Game.enemy.name + " for " + damage + "!");
        if(Game.enemyHealth < 0) { Game.enemyHealth = 0; console.log(Game.enemy.name + " HP: " + Game.enemyHealth + divider); }
        else { console.log(Game.enemy.name + " HP: " + Game.enemyHealth + divider); }
        Game.playerTurn = false;
    }
    if(Game.enemyHealth <= 0){
            Game.enemyHealth = 0;
            console.log(this.name + "'s" + " party has defeated " + Game.enemy.name + "!" + divider);
            for(var i = 0; i < 1; i++){
                var loot = Game.enemy.itemList[Math.floor(Math.random()*Game.enemy.itemList.length)];
                if(loot == "Nothing") { console.log( Game.enemy.name + " did not drop anything"); }
                else { this.addToInventory(loot) };
                console.log(this.name + " looted " + loot + " from " + Game.enemy.name);
            }
            Game.enemy = undefined;
        }
    if(!Game.playerTurn && Game.enemyHealth > 0){
        var critCheck = Math.floor(Math.random()*10);
        if(critCheck == 9) {
            this.health -= Game.enemy.damage * 1.5;
            var critDamage = Game.enemy.damage * 1.5;
            console.log(">> CRITICAL HIT BONUS <<");
            console.log("**" + Game.enemy.name + " hits " + this.name + " for " + critDamage + "!**");
        }
        else {
            this.health -= Game.enemy.damage;
            console.log("**" + Game.enemy.name + " hits " + this.name + " for " + Game.enemy.damage + "!**");
        }

    }
    }
    Game.playerTurn = true;
}

var isaac = new Adventurer("Isaac", 100, 50);
var mia = new Adventurer("Mia", 80, 90);

isaac.setWeapon(woodenMeleeWeapon);
mia.setWeapon(woodenRangeWeapon);

Adventurer.prototype.playerOneHealthItem = new HealthItem(isaac);
Adventurer.prototype.playerTwoHealthItem = new HealthItem(mia);

isaac.addSpell("Earthquake");
isaac.addSpell("Push");

mia.addSpell("Soothing Waters");
mia.addSpell("Sleet");
<commit_msg>Added adventurer health after enemy attack<commit_after>var get = function(id) {
    return document.getElementById(id);
}

var divider = "\n------------------------------------------------------";
console.log("Golden Sun Battle Sim" + divider);
console.log("Enter - Game.commands() - to view all usable functions" + divider);

var that;
var gameCommandsArray = ["adventurer.adventurerData()","adventurer.addToInventory()","adventurer.viewInventory()", "adventurer.addSpell(spell)",
                "adventurer.viewSpells()", "adventurer.setWeapon(woodenMeleeWeapon || woodenRangeWeapon)",
                "adventurer.lotOfPots() -- Adds 50 HP Potions", "adventurer.playerOneHealthItem.use()",
                "adventurer.playerTwoHealthItem.use()", "adventurer.battle()", "adventurer.attack()"];

var Game = {
    gameItems : ["HP Pot", "MP Pot", "Brass Guard", "Wooden Sword", "Wooden Staff"],
    commands : function(){
        var i = 0;
        while(i < gameCommandsArray.length){ console.log(gameCommandsArray[i] + divider); i++ }
    },
    enemy : undefined,
    enemyList : ["Skeleton Warrior", "Vale Rat"],
    gameEnemies : {
        skeleton : {
            name : "Skeleton Warrior",
            health : 40,
            attack : "Skeletal Slash",
            damage : 9,
            itemList: ["Wooden Sword", "HP Pot", "Brass Guard", "Nothing"]
        },
        rat : {
            name : "Vale Rat",
            health : 20,
            attack : "Scratch",
            damage : 7,
            itemList: ["MP Pot", "Wooden Staff", "Nothing"]
        },
    },
    enemyHealth : undefined,
    inBattle : false,

    playerTurn : true
};

var Adventurer = function(name, health, mana) {
    this.name = name;
    this.health = health;
    this.maxHealth = health;
    this.maxOverheal = this.maxHealth * 2;
    this.mana = mana;
    this.inventory = [];
    this.spells = [];
    this.weapon;
    this.level = 1;
    this.attackPower = 1;
    this.spellInUse = false;
    this.currentSpell = "";
    /*var experience = 5;
    var neededExperience = experience * 2;

    this.addExperience = function(experienceGiven){
        experience += experienceGiven;
        console.log(experience);
        console.log(neededExperience);

        if(experience >= neededExperience){
            this.level += 1;
            var previousLevel = this.level - 1;
            console.log(this.name + " has " + "LEVELED UP!" + "(" + previousLevel + "->" + this.level + ")");
            neededExperience = experience * 2;
        }
    }*/

}

var woodenMeleeWeapon = {
    damage : 8,
    name : "Wooden Sword",
    uses : 40,
    info : "Your weathered but trusty wooden sword"
};

var woodenRangeWeapon = {
    damage : 4,
    rangedDamage : 13,
    mana : 5,
    name : "Wooden Staff",
    uses: 40,
    info : "A wooden staff with a rock-hard tip"
};

Adventurer.prototype.addToInventory = function(item) {
    for(i = 0; i < Game.gameItems.length; i++){
        if(item == Game.gameItems[i]){ this.inventory.push(item); }
    }
}

Adventurer.prototype.addSpell = function(spell) {
    this.spells.push(spell);
}

Adventurer.prototype.setWeapon = function(weapon) {
    if(weapon == woodenMeleeWeapon){
        this.weapon = woodenMeleeWeapon;
        this.inventory.push(weapon.name);
    }
    else if(weapon == woodenRangeWeapon){
        this.weapon = woodenRangeWeapon;
        this.inventory.push(weapon.name);
    }
}

var HealthItem = function(adventurer) {
    this.healthItemName = "";
    this.healAmount = 0;

    this.use = function() {
        that = adventurer;
        console.log(that.name);
        for (var x = 0; x < that.inventory.length; x++) {
            if (that.inventory[x] == "HP Pot") {
                this.healthItemName = "HP Pot";
                this.healAmount = 30;
                that.health += this.healAmount;
                console.log(that.name + " Has Used " + this.healthItemName + " to heal for " + this.healAmount + "HP" + divider);
                if (that.health > that.maxHealth && that.health < that.maxOverheal) {
                    var overheal = that.health - that.maxHealth;
                    console.log("Overhealed by " + overheal + "!");
                } else if (that.health > that.maxOverheal) {
                    console.log(that.name + " cannot " + "be " + "overhealed " + "anymore!");
                    that.health = that.maxOverheal;
                }
                that.inventory.splice(x, 1);
                return;
            }
        }
        console.log("No Health Items in Inventory" + divider);
    }
}

Adventurer.prototype.adventurerData = function() {
    console.log(this.name);
    console.log("Health: " + this.health);
    console.log("Mana: " + this.mana + divider);
}

Adventurer.prototype.viewSpells = function() {
    for (var i = 0; i < this.spells.length; i++) {
        console.log(this.spells[i] + divider);
    }
}

Adventurer.prototype.useSpell = function(spell) {
    if(this.spellInUse == true) { console.log(this.name + " is already charging " + this.currentSpell); }
    else{
    for (var i = 0; i < this.spells.length; i++) {
        if (this.spells[i] == spell) {
            if(Game.enemy == undefined){
                this.spellInUse = false;
                console.log("What are you aiming that " + spell + " at?" + divider);
                return;
            }
            else{
            this.currentSpell = spell;
            this.spellInUse = true;
            console.log(this.name + " is charging " + this.currentSpell + "...");
            playerTurn = false;
            return;
        }
        }
    }
    console.log("You don't know how to do that..." + divider);
}
}

Adventurer.prototype.viewInventory = function() {
    for (var x = 0; x < this.inventory.length; x++) {
        console.log(this.inventory[x] + divider);
    }
    if (this.inventory.length == 0) {
        console.log(this.name + "'s" + " bag is empty");
    }
}

Adventurer.prototype.lotOfPots = function() {
    for (var i = 0; i < 50; i++) {
        this.addToInventory("HP Pot");
    }
}

Adventurer.prototype.battle = function(){
    if(Game.enemy != undefined){
        console.log("You're already in a battle!");
    }
    else{
    Game.inBattle = true;
    Game.enemy = Game.enemyList[Math.floor(Math.random()*Game.enemyList.length)];
    if(Game.enemy == "Skeleton Warrior"){ Game.enemy = Game.gameEnemies.skeleton; }
    else{ Game.enemy = Game.gameEnemies.rat; }
    Game.enemyHealth = Game.enemy.health;
    console.log(this.name + "'s" + " party has encountered " + Game.enemy.name + "(HP:" + Game.enemy.health + ")");
}
}

Adventurer.prototype.attack = function(){
    var damage;
    if(Game.enemyHealth > 0){
    while(Game.playerTurn){
        /*Spell progress
        if(this.spellInUse == true){
            for(var x = 0; x < spellList.length; x++){
                if(this.currentSpell == spellList[x].name && spellList[x].hostile == true){
                    damage = spellList[x].effect;
                    console.log("testing: " + damage);
                }
            }
        }
        else{*/
        damage = this.weapon.damage + (this.attackPower * 0.5);
    //}
        Game.enemyHealth -= damage;
        console.log(this.name +  " hit " + Game.enemy.name + " for " + damage + "!");
        if(Game.enemyHealth < 0) { Game.enemyHealth = 0; console.log(Game.enemy.name + " HP: " + Game.enemyHealth + divider); }
        else { console.log(Game.enemy.name + " HP: " + Game.enemyHealth + divider); }
        Game.playerTurn = false;
    }
    if(Game.enemyHealth <= 0){
            Game.enemyHealth = 0;
            console.log(this.name + "'s" + " party has defeated " + Game.enemy.name + "!" + divider);
            for(var i = 0; i < 1; i++){
                var loot = Game.enemy.itemList[Math.floor(Math.random()*Game.enemy.itemList.length)];
                if(loot == "Nothing") { console.log( Game.enemy.name + " did not drop anything"); }
                else { this.addToInventory(loot) };
                console.log(this.name + " looted " + loot + " from " + Game.enemy.name);
            }
            Game.enemy = undefined;
        }
    if(!Game.playerTurn && Game.enemyHealth > 0){
        var critCheck = Math.floor(Math.random()*10);
        if(critCheck == 9) {
            this.health -= Game.enemy.damage * 1.5;
            var critDamage = Game.enemy.damage * 1.5;
            console.log(">> CRITICAL HIT BONUS <<");
            console.log("**" + Game.enemy.name + " hits " + this.name + " for " + critDamage + "!**");
            console.log(this.name + " HP: " + this.health);
        }
        else {
            this.health -= Game.enemy.damage;
            console.log("**" + Game.enemy.name + " hits " + this.name + " for " + Game.enemy.damage + "!**");
            console.log(this.name + " HP: " + this.health);
        }

    }
    }
    Game.playerTurn = true;
}

var isaac = new Adventurer("Isaac", 100, 50);
var mia = new Adventurer("Mia", 80, 90);

isaac.setWeapon(woodenMeleeWeapon);
mia.setWeapon(woodenRangeWeapon);

Adventurer.prototype.playerOneHealthItem = new HealthItem(isaac);
Adventurer.prototype.playerTwoHealthItem = new HealthItem(mia);

isaac.addSpell("Earthquake");
isaac.addSpell("Push");

mia.addSpell("Soothing Waters");
mia.addSpell("Sleet");
<|endoftext|>


<commit_before>

$(function(){

    var formatAMPM = function(date) {
	var hours = date.getHours();
	var minutes = date.getMinutes();
	var ampm = hours >= 12 ? 'pm' : 'am';
	hours = hours % 12;
	hours = hours ? hours : 12;
	minutes = minutes < 10 ? '0'+minutes : minutes;
	var strTime = hours + ':' + minutes + ' ' + ampm;
	return strTime;
    }

    var updateDT = function(){
	var now = new Date();
	var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
	var months = ["January", "February", "March", "April", "May", "June",
		      "July", "August", "September", "October", "November", "December"
		     ];
	var timeString = formatAMPM(now);
	var dateString = weekdays[now.getDay()] + ', ' +
	    months[now.getMonth()] + ' ' + now.getDate()
	$('#cpl-time').html(timeString);
	$('#cpl-date').html(dateString);
	setTimeout(updateDT, 500);
    };

    var updateWeather = function(){
	$.simpleWeather({
	    woeid: '12758737', // woeid for cambridge ma
	    unit: 'f',
	    success: function(weather) {
		html = ' | ' + weather.temp + '°' + weather.units.temp;
		$("#cpl-weather").html(html);
		$("#cpl-weather-image").html('');
	    },
	    error: function(error) {
		console.log("Error getting weather data");
		console.log(error);
		$("#cpl-weather").html('
'+'
');
	    }
	});
    }

    var insertFloor = function(location, rooms, floor) {
	$.each(rooms, function(i, room) {
            location = location.replace(room,room+ ' (' + floor + ')');
	});
	return location;
    };

    var mungeLocation = function(loc) {
	loc = insertFloor(loc, ['Community Room', 'Lecture Hall'],
			  'L2');
	loc = insertFloor(loc, ['Beech Room', 'Rossi Room'], 'Ground Floor');
	loc = insertFloor(loc, ['Rindge Room', 'Learning Lab', 'Teen Room'], '1st Floor');
	loc = insertFloor(loc, ['Curious George Room', 'Rey Room'], '3rd Floor');
	loc = insertFloor(loc, ['Cambridge Room'], '2nd Floor');
	return loc;
    };

    var mungeDate = function(dateString) {
	var date = new Date(Date.parse(dateString));
	var today = new Date();
	//console.log("Does : " + date.toDateString() + ' ===  ' +  today.toDateString());
	if (date.toDateString() === today.toDateString()) {
	    dateString = 'Today';
	} else {
	    dateString = dateString.replace(/, \d{4}$/,'');
	}
	return dateString;
    };

    var getBranchName = function(title){
	var url = window.location.href;
	var branches = [
	    ['boudreau', 'Boudreau'],
	    ['collins', 'Collins'],
	    ['csq', 'Central Square'],
	    ['oneill', "O'Neill"],
	    ['oconnell', "O'Connell"],
	    ['valente', 'Valente' ],
	    ['Online', 'Online' ]
	];
	var branchName = "Online";
	branches.forEach(function(branch){
	    console.log("Branchs is " , branch);
	    if (url.indexOf(branch[0]) > -1){
		branchName = branch[1];
	    }
	});
	console.log("Returning branchName : " + branchName);
	return branchName;
    };

    var mungeTitle = function(title){
	var branchName = getBranchName();
	if (branchName){
	    title = title.replace("("+branchName+")","");
	}
	title = title.replace(/\(virtual\)/i,"");
	title = title;
	return title;
    };

    // reload page every 10 minutes.
    setTimeout("location.reload(true);",60000*10);
    setTimeout(updateDT, 500);
    var columnCount = 2;
    if ($('#cpl-events-column-2').length>0){
	columnCount = 3;
    }

    var e = undefined;
    var events = [];
    // grab data from (hidden) springshare html table
    $('.s-lc-ea-tb tr').each(function (i, row) {
	var $row = $(row);
	var $tds = $row.find('td');
	var key = $tds.eq(0).text().replace(':','').toLowerCase();
	var value = $tds.eq(1).text();
	if ( key === 'title' ){
	    value = mungeTitle(value);
	    e = {};
	    e.id = 'cpl-event-' + events.length;
	    events.push(e);
	}
	e[key]=value;
    });
    $.each(events, function (i, e) {
	// clean up events
	var loc = e.location;
	console.log(e);
	console.log("REINOS 0: loc: " + loc);
	if ( e.branches === 'Online'){
	    loc = 'Online';
	}
	console.log("REINOS 1: loc: " + loc);
	if ( loc ) {
	    e.location = mungeLocation(loc);
	}
	e.date = mungeDate(e.date);
    });
    console.log(events);
    // use data to generate more attractive html and display it.
    var column = 0;
    $.each(events, function (i, e) {
	var eventsPerColumn = events.length/columnCount;
	if ( i >= eventsPerColumn ) {
	    column = 1;
	    if ( i >= eventsPerColumn*2) {
		column = 2;
	    }
	}
	console.log("Event: " + i + " Column: " + column + " columnCount: " + columnCount + " eventsPerColumn: " + eventsPerColumn);

	$('
', {
	    id: e.id,
	    class: 'cpl-event'
	}).appendTo('#cpl-events-column-'+column);
	$('
',{
	    id: e.id + '-title',
	    class: 'cpl-event-title',
	    text: e.title,
	}).appendTo('#'+e.id);
	$('
',{
	    id: e.date + '-date',
	    text: e.date,
	    class: 'cpl-event-' + (e.date === 'Today' ? 'today' : 'date'),
	}).appendTo('#'+e.id);
	$('
',{
	    id: e.time + '-time',
	    text: e.time,
	}).appendTo('#'+e.id);
	if ( e.location ) {
	    $('
',{
		id: e.location + '-location',
		text: e.location,
	    }).appendTo('#'+e.id);
	}
    });
    var wh = $(window).height();
    var ww = $(window).width();
    var ph = wh-120;
    var pw = ph / 1.26;
    //$('#cpl-poster-div').css('height', ph);
    //$('#cpl-poster-div').css('width' , pw);
    //$('#cpl-events-div').css('height', ph);
    //alert("Window: " + wh + "," +  ww +  " poster:  " +  ph + "," + pw);

});
<commit_msg>fix Hive floor munging<commit_after>

$(function(){

    var formatAMPM = function(date) {
	var hours = date.getHours();
	var minutes = date.getMinutes();
	var ampm = hours >= 12 ? 'pm' : 'am';
	hours = hours % 12;
	hours = hours ? hours : 12;
	minutes = minutes < 10 ? '0'+minutes : minutes;
	var strTime = hours + ':' + minutes + ' ' + ampm;
	return strTime;
    }

    var updateDT = function(){
	var now = new Date();
	var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
	var months = ["January", "February", "March", "April", "May", "June",
		      "July", "August", "September", "October", "November", "December"
		     ];
	var timeString = formatAMPM(now);
	var dateString = weekdays[now.getDay()] + ', ' +
	    months[now.getMonth()] + ' ' + now.getDate()
	$('#cpl-time').html(timeString);
	$('#cpl-date').html(dateString);
	setTimeout(updateDT, 500);
    };

    var updateWeather = function(){
	$.simpleWeather({
	    woeid: '12758737', // woeid for cambridge ma
	    unit: 'f',
	    success: function(weather) {
		html = ' | ' + weather.temp + '°' + weather.units.temp;
		$("#cpl-weather").html(html);
		$("#cpl-weather-image").html('');
	    },
	    error: function(error) {
		console.log("Error getting weather data");
		console.log(error);
		$("#cpl-weather").html('
'+'
');
	    }
	});
    }

    var insertFloor = function(location, rooms, floor) {
	$.each(rooms, function(i, room) {
            location = location.replace(room,room+ ' (' + floor + ')');
	});
	return location;
    };

    var mungeLocation = function(loc) {
	loc = insertFloor(loc, ['Community Room', 'Lecture Hall'],
			  'L2');
	loc = insertFloor(loc, ['The Hive'], 'L1');
	loc = insertFloor(loc, ['Beech Room', 'Rossi Room'], 'Ground Floor');
	loc = insertFloor(loc, ['Rindge Room', 'Learning Lab', 'Teen Room'], '1st Floor');
	loc = insertFloor(loc, ['Curious George Room', 'Rey Room'], '3rd Floor');
	loc = insertFloor(loc, ['Cambridge Room'], '2nd Floor');
	return loc;
    };

    var mungeDate = function(dateString) {
	var date = new Date(Date.parse(dateString));
	var today = new Date();
	//console.log("Does : " + date.toDateString() + ' ===  ' +  today.toDateString());
	if (date.toDateString() === today.toDateString()) {
	    dateString = 'Today';
	} else {
	    dateString = dateString.replace(/, \d{4}$/,'');
	}
	return dateString;
    };

    var getBranchName = function(title){
	var url = window.location.href;
	var branches = [
	    ['boudreau', 'Boudreau'],
	    ['collins', 'Collins'],
	    ['csq', 'Central Square'],
	    ['oneill', "O'Neill"],
	    ['oconnell', "O'Connell"],
	    ['valente', 'Valente' ],
	    ['Online', 'Online' ]
	];
	var branchName = "Online";
	branches.forEach(function(branch){
	    console.log("Branchs is " , branch);
	    if (url.indexOf(branch[0]) > -1){
		branchName = branch[1];
	    }
	});
	console.log("Returning branchName : " + branchName);
	return branchName;
    };

    var mungeTitle = function(title){
	var branchName = getBranchName();
	if (branchName){
	    title = title.replace("("+branchName+")","");
	}
	title = title.replace(/\(virtual\)/i,"");
	title = title;
	return title;
    };

    // reload page every 10 minutes.
    setTimeout("location.reload(true);",60000*10);
    setTimeout(updateDT, 500);
    var columnCount = 2;
    if ($('#cpl-events-column-2').length>0){
	columnCount = 3;
    }

    var e = undefined;
    var events = [];
    // grab data from (hidden) springshare html table
    $('.s-lc-ea-tb tr').each(function (i, row) {
	var $row = $(row);
	var $tds = $row.find('td');
	var key = $tds.eq(0).text().replace(':','').toLowerCase();
	var value = $tds.eq(1).text();
	if ( key === 'title' ){
	    value = mungeTitle(value);
	    e = {};
	    e.id = 'cpl-event-' + events.length;
	    events.push(e);
	}
	e[key]=value;
    });
    $.each(events, function (i, e) {
	// clean up events
	var loc = e.location;
	console.log(e);
	console.log("REINOS 0: loc: " + loc);
	if ( e.branches === 'Online'){
	    loc = 'Online';
	}
	console.log("REINOS 1: loc: " + loc);
	if ( loc ) {
	    e.location = mungeLocation(loc);
	}
	e.date = mungeDate(e.date);
    });
    console.log(events);
    // use data to generate more attractive html and display it.
    var column = 0;
    $.each(events, function (i, e) {
	var eventsPerColumn = events.length/columnCount;
	if ( i >= eventsPerColumn ) {
	    column = 1;
	    if ( i >= eventsPerColumn*2) {
		column = 2;
	    }
	}
	console.log("Event: " + i + " Column: " + column + " columnCount: " + columnCount + " eventsPerColumn: " + eventsPerColumn);

	$('
', {
	    id: e.id,
	    class: 'cpl-event'
	}).appendTo('#cpl-events-column-'+column);
	$('
',{
	    id: e.id + '-title',
	    class: 'cpl-event-title',
	    text: e.title,
	}).appendTo('#'+e.id);
	$('
',{
	    id: e.date + '-date',
	    text: e.date,
	    class: 'cpl-event-' + (e.date === 'Today' ? 'today' : 'date'),
	}).appendTo('#'+e.id);
	$('
',{
	    id: e.time + '-time',
	    text: e.time,
	}).appendTo('#'+e.id);
	if ( e.location ) {
	    $('
',{
		id: e.location + '-location',
		text: e.location,
	    }).appendTo('#'+e.id);
	}
    });
    var wh = $(window).height();
    var ww = $(window).width();
    var ph = wh-120;
    var pw = ph / 1.26;
    //$('#cpl-poster-div').css('height', ph);
    //$('#cpl-poster-div').css('width' , pw);
    //$('#cpl-events-div').css('height', ph);
    //alert("Window: " + wh + "," +  ww +  " poster:  " +  ph + "," + pw);

});
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");
var nlp = require("./nlp");
var pushConv = require("./push");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ");
            console.log("===receive step 1",message);
            let upperText = message.text.trim().toUpperCase();

            var botUser = bot.userId;
            var authUsers = ['a30fa820d0a0f0216fa26070'];

            //Undone - currently only creates new user
            //needs to create conversation record and update it throughout the prcoess
            console.log("===before db",bot);
            newUser(bot)
              .then (console.log("===after db", bot.userId))

              //undone - test for userid and or message
              //look at stacking messages in DB and looking them up
              //end conversation and do not send a response to the user that kicked things off
              //
              if (authUsers.indexOf(bot.userId) !== -1) {
                //if (message.substr(0,5) == '/msg ') {
                  console.log("===before push",message);
                //pushConv(bot);
                //}
              }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "-SUPPORT":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    case "-ACE":
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            console.log("===receive step 2",upperText);

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var promises = [];
                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(message.text, bot.userId));

                Q.all(promises).then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        //console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
                        console.log("source: ", source);
                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
                //return next();

            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
                console.log("source: ", source);
                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                console.log("simplified: ", simplified);
                console.log("===receive step 3",upperText);

              if (source != 'agent')
                {
                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                        console.log("fulfillmentSpeech is: ", fulfillmentSpeech);
                        return bot.say(fulfillmentSpeech).then(() => 'speak');
                    }
                    else if (simplified)
                    {
                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }
                if (!_.has(scriptRules, upperText)) {
                    console.log("===no rule", upperText);
                    return bot.say(`I'm sorry that is not something I know.  Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                }

                console.log("===receive step 3",upperText);

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                bot.userId = botUser;

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("=== p line",line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<commit_msg>try msg.text<commit_after>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");
var nlp = require("./nlp");
var pushConv = require("./push");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ");
            console.log("===receive step 1",message);
            let upperText = message.text.trim().toUpperCase();

            var botUser = bot.userId;
            var authUsers = ['a30fa820d0a0f0216fa26070'];

            //Undone - currently only creates new user
            //needs to create conversation record and update it throughout the prcoess
            console.log("===before db",bot);
            newUser(bot)
              .then (console.log("===after db", bot.userId))

              //undone - test for userid and or message
              //look at stacking messages in DB and looking them up
              //end conversation and do not send a response to the user that kicked things off
              //
              if (authUsers.indexOf(bot.userId) !== -1) {
                if (message.text.substr(0,5) == '/msg ') {
                  console.log("===before push",message);
                //pushConv(bot);
                }
              }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "-SUPPORT":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    case "-ACE":
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            console.log("===receive step 2",upperText);

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var promises = [];
                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(message.text, bot.userId));

                Q.all(promises).then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        //console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
                        console.log("source: ", source);
                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
                //return next();

            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
                console.log("source: ", source);
                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                console.log("simplified: ", simplified);
                console.log("===receive step 3",upperText);

              if (source != 'agent')
                {
                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                        console.log("fulfillmentSpeech is: ", fulfillmentSpeech);
                        return bot.say(fulfillmentSpeech).then(() => 'speak');
                    }
                    else if (simplified)
                    {
                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }
                if (!_.has(scriptRules, upperText)) {
                    console.log("===no rule", upperText);
                    return bot.say(`I'm sorry that is not something I know.  Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                }

                console.log("===receive step 3",upperText);

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                bot.userId = botUser;

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("=== p line",line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<|endoftext|>


<commit_before>var ruler = {library: {_mappings: {}}}

ruler._get = function(name) {
    return ruler.library._mappings[ruler.name_add_prefix(name)]
}

ruler.name_add_prefix = function(alias) {
    return 'ruler.'.concat(alias)
}

ruler.parse = function parse(sequence, _result) {
    result = _result || []
    to_return = null

    if(sequence.length > 0) {
        if(_.isArray(_.head(sequence))) {
            to_return = parse(_.tail(sequence), result.concat([parse(_.head(sequence))]))
        } else if(_.has(ruler.library._mappings, ruler.name_add_prefix(_.head(sequence)))) {
            to_return = parse(_.tail(sequence), result.concat([ruler.library._mappings[ruler.name_add_prefix(_.head(sequence))]]))
        } else {
            to_return = parse(_.tail(sequence), result.concat(_.head(sequence)))
        }
    } else {
        if(_.isFunction(_.head(result))) {
            to_return = _.head(result).apply(this, _.tail(result))
        } else {
            to_return = result
        }
    }

    return to_return
}

ruler.library._mappings = {}
ruler.library.register = function(alias, func) {
    ruler.library._mappings[ruler.name_add_prefix(alias)] = func

    return func
}

ruler.library.register('basic.Field', function(key) {
    return function(context) {
        return context[key]
    }
})

ruler.library.register('boolean.And', function() {
    var args = arguments
    return function(context) {
        return _.reduce(args,
                        function(result, incoming) {
                            return result && incoming(context)
                        },
                        true)
    }
})

ruler.library.register('boolean.Or', function() {
    var args = arguments
    return function(context) {
        return _.reduce(args,
                        function(result, incoming) {
                            return result || incoming(context)
                        },
                        false)
    }
})

ruler.library.register('boolean.Not', function(arg) {
    return function(context) {
        return ! arg(context)
    }
})

ruler.library.register('boolean.Tautology', function() {
    return function() { return true }
})

ruler.library.register('condition.Equal', function(key, value) {
    return function(context) {
        return context[key] == value
    }
})

ruler.library.register('condition.In', function(key, values) {
    return function(context) {
        return _.contains(values, context[key])
    }
})

ruler.library.register('condition.Is_Null', function(key) {
    return function(context) {
        return _.isNull(context[key])
    }
})

ruler.library.register('condition.Is_True', function(key) {
    return function(context) {
        return context[key] === true
    }
})

ruler.library.register('string.Concat', function(link) {
    var values = _.tail(arguments)

    return function(context) {
        return _.map(values,
                    function(value) {
                        return _.isFunction(value) ? value(context) : value
                    }).join(link)
    }
})

ruler.library.register('string.Concat_Fiels', function(link) {
    var keys = _.tail(arguments)

    return ruler._get('string.Concat').apply(this, [link].concat(_.map(keys,
                                                         function(key) {
                                                             return ruler._get('basic.Field').call(key)
                                                         })))
})

ruler.library.register('string.Lower', function(value) {
    return function(context) {
        return _.isFunction(value) ? value(context).toLowerCase() : value.toLowerCase()
    }
})
<commit_msg>minor typo<commit_after>var ruler = {library: {_mappings: {}}}

ruler._get = function(name) {
    return ruler.library._mappings[ruler.name_add_prefix(name)]
}

ruler.name_add_prefix = function(alias) {
    return 'ruler.'.concat(alias)
}

ruler.parse = function parse(sequence, _result) {
    result = _result || []
    to_return = null

    if(sequence.length > 0) {
        if(_.isArray(_.head(sequence))) {
            to_return = parse(_.tail(sequence), result.concat([parse(_.head(sequence))]))
        } else if(_.has(ruler.library._mappings, ruler.name_add_prefix(_.head(sequence)))) {
            to_return = parse(_.tail(sequence), result.concat([ruler.library._mappings[ruler.name_add_prefix(_.head(sequence))]]))
        } else {
            to_return = parse(_.tail(sequence), result.concat(_.head(sequence)))
        }
    } else {
        if(_.isFunction(_.head(result))) {
            to_return = _.head(result).apply(this, _.tail(result))
        } else {
            to_return = result
        }
    }

    return to_return
}

ruler.library._mappings = {}
ruler.library.register = function(alias, func) {
    ruler.library._mappings[ruler.name_add_prefix(alias)] = func

    return func
}

ruler.library.register('basic.Field', function(key) {
    return function(context) {
        return context[key]
    }
})

ruler.library.register('boolean.And', function() {
    var args = arguments
    return function(context) {
        return _.reduce(args,
                        function(result, incoming) {
                            return result && incoming(context)
                        },
                        true)
    }
})

ruler.library.register('boolean.Or', function() {
    var args = arguments
    return function(context) {
        return _.reduce(args,
                        function(result, incoming) {
                            return result || incoming(context)
                        },
                        false)
    }
})

ruler.library.register('boolean.Not', function(arg) {
    return function(context) {
        return ! arg(context)
    }
})

ruler.library.register('boolean.Tautology', function() {
    return function() { return true }
})

ruler.library.register('condition.Equal', function(key, value) {
    return function(context) {
        return context[key] == value
    }
})

ruler.library.register('condition.In', function(key, values) {
    return function(context) {
        return _.contains(values, context[key])
    }
})

ruler.library.register('condition.Is_Null', function(key) {
    return function(context) {
        return _.isNull(context[key])
    }
})

ruler.library.register('condition.Is_True', function(key) {
    return function(context) {
        return context[key] === true
    }
})

ruler.library.register('string.Concat', function(link) {
    var values = _.tail(arguments)

    return function(context) {
        return _.map(values,
                    function(value) {
                        return _.isFunction(value) ? value(context) : value
                    }).join(link)
    }
})

ruler.library.register('string.Concat_Fields', function(link) {
    var keys = _.tail(arguments)

    return ruler._get('string.Concat').apply(this, [link].concat(_.map(keys,
                                                         function(key) {
                                                             return ruler._get('basic.Field').call(key)
                                                         })))
})

ruler.library.register('string.Lower', function(value) {
    return function(context) {
        return _.isFunction(value) ? value(context).toLowerCase() : value.toLowerCase()
    }
})
<|endoftext|>


<commit_before>$(document).ready(function() {
  $("#add-task").click(function() {
    $(".todo-list").append("
"+$("input").val()+" <button>Smazat</button>
")
    $("input").val("");
    // Vybereme tlacitko v naposledy pridane polozce
    $(".todo-list li:last-child button").click(function() {
      $(this).closest("li").remove()
    });
  });

  $(".hilight-task").click(function() {
    $(".todo-list li:last-child").toggleClass("hilight");
  })
});
<commit_msg>7. krok: animace položky při kliku<commit_after>$(document).ready(function() {
  $("#add-task").click(function() {
    $(".todo-list").append("
"+$("input").val()+" <button>Smazat</button>
")
    $("input").val("");
    // Vybereme tlacitko v naposledy pridane polozce
    $(".todo-list li:last-child button").click(function() {
      $(this).closest("li").remove()
    });
    // Animace polozky pri kliku
    $(".todo-list li:last-child").click(function() {
      $(this).animate({marginLeft: "10px"}).animate({marginLeft: "-10px"}).animate({marginLeft: 0})
    });
  });

  $(".hilight-task").click(function() {
    $(".todo-list li:last-child").toggleClass("hilight");
  })
});
<|endoftext|>


<commit_before>
var ReactWeather = React.createClass({
  getInitialState: function() {
    return {
      citiesArr: [],
      currentCity: ''
    };
  },

  componentDidMount: function() {
    this._getGeoOfUser();
    this._getCitysFromStorage();
    //this._updateWeatherState('London');
  },

  componentDidUpdate: function() {
    this._setCitysToStorage();
  },

  _getCitysFromStorage: function() {
    //localStorage.removeItem('citiesArr');
    if(typeof localStorage['citiesArr'] === 'undefined') {
      localStorage['citiesArr'] = '[]';
    }

    this.setState({
      citiesArr: JSON.parse(localStorage['citiesArr'])
    });
  },

  _setCitysToStorage: function() {
    localStorage['citiesArr'] = JSON.stringify(this.state.citiesArr);
  },

  _getGeoOfUser: function() {
    var self = this;

    if (!navigator.geolocation) {
      this.state.currentCity = 'Can\'t get geo!';
      return;
    }

    function success(position) {
      var pos = {
        lat: position.coords.latitude,
        lon: position.coords.longitude
      };
      console.log('Geo success: %o', pos);

      self._updateWeatherState(pos);
    };

    function error() {
      console.log('Geo FAIL!');
    };

    navigator.geolocation.getCurrentPosition(success, error);
  },

  _updateWeatherState: function(arg) {

    var self = this;
    var appID = '2de143494c0b295cca9337e1e96b00e0';
    var url = 'http://api.openweathermap.org/data/2.5/weather';

    var city = '';
    var query = {};
    if (typeof arg === 'object') {
      query.lat = arg.lat;
      query.lon = arg.lon;
      city = 'You Geolocation Weather!';
    } else {
      query.q = arg;
      city = arg;
    }
    query.appid = appID;

    console.log(query);

    $.get(url, query, function(data) {
      if ( self.isMounted() ) {
        self.setState({
          currentCity: city,
          temp: data.main.temp,
          icon: data.weather[0].icon,
          pressure: data.main.pressure,
          humidity: data.main.humidity
        });
      }
    });
  },

  _addCity: function(city) {
    if(city === '') {
      return
    }

    this.setState(function(state) {
      var temp = state.citiesArr;
      temp.push(city);
      state.citiesArr = temp;
    });
  },

  _getCitiesLine: function() {
    var self = this;
    return self.state.citiesArr.map(function(value, key) {
      var className = (value === self.state.currentCity) ? 'selectCity' : 'cityNames';
      return ( {value} )
    });
  },

  removeAllCitiesHandler: function(event) {
    this.setState({
      citiesArr: []
    });
  },

  addCityHanler: function(event) {
    var input = document.getElementById("addCity").value;
    console.log('addCityHanler: ' + input);
    this._addCity(input);
  },

  cityClickHandler: function(event) {
    var city = event.target.innerHTML;
    console.log('cityClickHandler: ' + city);
    this._updateWeatherState(city);
  },

  render: function () {
    var state = this.state;
    var citiesLine = this._getCitiesLine();
    var iconLink = 'http://openweathermap.org/img/w/'+state.icon+'.png';

    console.log(state);

    return (

{state.currentCity}

          Влажность: {state.humidity}

          Давление: {state.pressure}

          Температура: {state.temp}

          <input type='text' id='addCity' />

          <input type='submit' value='Добавить' onClick={this.addCityHanler} />
          <input type='submit' value='Удалить всё' onClick={this.removeAllCitiesHandler} />

{citiesLine}

    );
  }

});

ReactDOM.render(
  <ReactWeather />,
  document.getElementById('ReactWeather')
);
<commit_msg>corrected language mistake<commit_after>
var ReactWeather = React.createClass({
  getInitialState: function() {
    return {
      citiesArr: [],
      currentCity: ''
    };
  },

  componentDidMount: function() {
    this._getGeoOfUser();
    this._getCitysFromStorage();
  },

  componentDidUpdate: function() {
    this._setCitysToStorage();
  },

  _getCitysFromStorage: function() {
    //localStorage.removeItem('citiesArr');
    if(typeof localStorage['citiesArr'] === 'undefined') {
      localStorage['citiesArr'] = '[]';
    }

    this.setState({
      citiesArr: JSON.parse(localStorage['citiesArr'])
    });
  },

  _setCitysToStorage: function() {
    localStorage['citiesArr'] = JSON.stringify(this.state.citiesArr);
  },

  _getGeoOfUser: function() {
    var self = this;

    if (!navigator.geolocation) {
      this.state.currentCity = 'Can\'t get geo!';
      return;
    }

    function success(position) {
      var pos = {
        lat: position.coords.latitude,
        lon: position.coords.longitude
      };
      console.log('Geo success: %o', pos);

      self._updateWeatherState(pos);
    };

    function error() {
      console.log('Geo FAIL!');
    };

    navigator.geolocation.getCurrentPosition(success, error);
  },

  _updateWeatherState: function(arg) {

    var self = this;
    var appID = '2de143494c0b295cca9337e1e96b00e0';
    var url = 'http://api.openweathermap.org/data/2.5/weather';

    var city = '';
    var query = {};
    if (typeof arg === 'object') {
      query.lat = arg.lat;
      query.lon = arg.lon;
      city = 'Weather in the place where you are!';
    } else {
      query.q = arg;
      city = arg;
    }
    query.appid = appID;

    console.log(query);

    $.get(url, query, function(data) {
      if ( self.isMounted() ) {
        self.setState({
          currentCity: city,
          temp: data.main.temp,
          icon: data.weather[0].icon,
          pressure: data.main.pressure,
          humidity: data.main.humidity
        });
      }
    });
  },

  _addCity: function(city) {
    if(city === '') {
      return
    }

    this.setState(function(state) {
      var temp = state.citiesArr;
      temp.push(city);
      state.citiesArr = temp;
    });
  },

  _getCitiesLine: function() {
    var self = this;
    return self.state.citiesArr.map(function(value, key) {
      var className = (value === self.state.currentCity) ? 'selectCity' : 'cityNames';
      return ( {value} )
    });
  },

  removeAllCitiesHandler: function(event) {
    this.setState({
      citiesArr: []
    });
  },

  addCityHanler: function(event) {
    var input = document.getElementById("addCity").value;
    console.log('addCityHanler: ' + input);
    this._addCity(input);
  },

  cityClickHandler: function(event) {
    var city = event.target.innerHTML;
    console.log('cityClickHandler: ' + city);
    this._updateWeatherState(city);
  },

  render: function () {
    var state = this.state;
    var citiesLine = this._getCitiesLine();
    var iconLink = 'http://openweathermap.org/img/w/'+state.icon+'.png';

    console.log(state);

    return (

{state.currentCity}

          Влажность: {state.humidity}

          Давление: {state.pressure}

          Температура: {state.temp}

          <input type='text' id='addCity' />

          <input type='submit' value='Добавить' onClick={this.addCityHanler} />
          <input type='submit' value='Удалить всё' onClick={this.removeAllCitiesHandler} />

{citiesLine}

    );
  }

});

ReactDOM.render(
  <ReactWeather />,
  document.getElementById('ReactWeather')
);
<|endoftext|>


<commit_before>$(document).ready(function() {
	var coin = loadCoin("res/us/quarter.json");
});

$('img#coin').click(function() {
	if (Math.random() < 0.5) {
		$(this).attr('src', coin.headSrc);
	} else {
		$(this).attr('src', coin.tailSrc);
	}
});

function loadCoin(url) {
	return $.getJSON(url, function(response){
		JSON = response;
		alert(JSON.property);
	});
}
<commit_msg>Stack 2177548<commit_after>$(document).ready(function() {
	var coin = loadCoin("res/us/quarter.json");
});

$('img#coin').click(function() {
	if (Math.random() < 0.5) {
		$(this).attr('src', coin.headSrc);
	} else {
		$(this).attr('src', coin.tailSrc);
	}
});

function loadCoin(url) {
	var json = (function () {
		var json = null;
		$.ajax({
			'async': false,
			'global': false,
			'url': my_url,
			'dataType': "json",
			'success': function (data) {
				json = data;
			}
		});
		return json;
	})();
}
<|endoftext|>


<commit_before>(function() {
  var cnt = 0;
  var image;
  var imageUrl;
  var more;
  var strangeElements = [];

  function downloadURI(uri) {
    var link = document.createElement("a");
    link.href = uri;
    link.setAttribute('download', null);
    link.click();
  }

  function pollForMore(elem) {
    if (elem.nextElementSibling) {
      walkThroughVisibleImages(elem.nextElementSibling);
      return;
    }
    setTimeout(function() { pollForMore(elem); }, 100);
  }

  function processElem(elem) {
    if (elem.getElementsByClassName('play').length > 0) {
      return true;
    }
    image = elem.getElementsByClassName('image')[0];
    if (!image) {
      strangeElements.push(elem);
      return true;
    }
    imageUrl = image.getAttribute('data-image');
    if (!!newestAvailable && imageUrl.indexOf(newestAvailable) > -1) {
      return false;
    }
    downloadURI(imageUrl);
    cnt++;
    return true;
  }

  function walkThroughVisibleImages(elem) {
    if (!processElem(elem)) {
      return;
    }
    while (elem.nextElementSibling) {
      elem = elem.nextElementSibling;
      if (!processElem(elem)) {
        return;
      }
      if (cnt % 10 === 0 && elem.nextElementSibling) {
        setTimeout(function() {
          walkThroughVisibleImages(elem.nextElementSibling);
        }, 2000);
        return;
      }
    }
    more = document.getElementsByClassName('loadmore');
    if (more.length) {
      more[0].click();
      pollForMore(elem);
    }
  }

  var newestAvailable = prompt("What is the newest image filename?");
  var container = document.getElementsByClassName('stories')[0];
  var elem = container.firstElementChild;
  walkThroughVisibleImages(elem);
})();
<commit_msg>Modifying the delays<commit_after>(function() {
  var cnt = 0;
  var image;
  var imageUrl;
  var more;
  var strangeElements = [];

  function downloadURI(uri) {
    var link = document.createElement("a");
    link.href = uri;
    link.setAttribute('download', null);
    link.click();
  }

  function pollForMore(elem) {
    if (elem.nextElementSibling) {
      walkThroughVisibleImages(elem.nextElementSibling);
      return;
    }
    setTimeout(function() { pollForMore(elem); }, 100);
  }

  function processElem(elem) {
    if (elem.getElementsByClassName('play').length > 0) {
      return true;
    }
    image = elem.getElementsByClassName('image')[0];
    if (!image) {
      strangeElements.push(elem);
      return true;
    }
    imageUrl = image.getAttribute('data-image');
    if (!!newestAvailable && imageUrl.indexOf(newestAvailable) > -1) {
      return false;
    }
    downloadURI(imageUrl);
    cnt++;
    return true;
  }

  function walkThroughVisibleImages(elem) {
    if (!processElem(elem)) {
      return;
    }
    while (elem.nextElementSibling) {
      elem = elem.nextElementSibling;
      if (!processElem(elem)) {
        return;
      }
      if (cnt % 5 === 0 && elem.nextElementSibling) {
        setTimeout(function() {
          walkThroughVisibleImages(elem.nextElementSibling);
        }, 3000);
        return;
      }
    }
    more = document.getElementsByClassName('loadmore');
    if (more.length) {
      more[0].click();
      pollForMore(elem);
    }
  }

  var newestAvailable = prompt("What is the newest image filename?");
  var container = document.getElementsByClassName('stories')[0];
  var elem = container.firstElementChild;
  walkThroughVisibleImages(elem);
})();
<|endoftext|>


<commit_before>$(function(){
  var
  $start = $('#start'),
  $btns = $('.btns .btn'),
  colors = ['#16A085','#2ECC71','#2980B9','#9B59B6','#2C3E50','#F39C12','#D35400','#E74C3C','#973449','#FF385D','#C0392B','#7F8C8D','#D35400','#973449','#9DC500'],
  selected = null,
  rnd = function(min, max){
    return  Math.floor(Math.random()*(max-min+1)+min);
  },
  randColor = function(){
    return colors[rnd(0, colors.length-1)];
  },
  setColors = function(){
    $btns.each(function(){
      $(this).css({
        'background-color' : randColor()
      });
    });
  },
  exploid = function(){
    $btns.each(function(){
      $(this).animate({
        left : rnd(0, 90) + '%',
        top : rnd(0, 90) + '%'
      }, 400);
    });
  },
  choose1 = function(){

  },
  start = function(){
    exploid();
    $btns.click(choose1);
  },
  reset = function(){
    window.location.reload(); // cheap as posible !
  },
  init = function(){
    $start.click(start);
    setColors();
  };

  init();

});<commit_msg>Better begin animate<commit_after>$(function(){
  var
  $start = $('#start'),
  $btns = $('.btns .btn'),
  colors = ['#16A085','#2ECC71','#2980B9','#9B59B6','#2C3E50','#F39C12','#D35400','#E74C3C','#973449','#FF385D','#C0392B','#7F8C8D','#D35400','#973449','#9DC500'],
  selected = null,
  rnd = function(min, max){
    return  Math.floor(Math.random()*(max-min+1)+min);
  },
  randColor = function(){
    return colors[rnd(0, colors.length-1)];
  },
  setColors = function(){
    $btns.each(function(){
      $(this).css({
        'background-color' : randColor()
      });
    });
  },
  exploid = function(){
    var i,delay = 1;
    for(i=$btns.length-1; i>=0; i--){
      setTimeout(function(i){
        $btns.eq(i).animate({
          left : rnd(0, 90) + '%',
          top : rnd(0, 90) + '%'
        }, 400);
      },delay,i);
      delay+=100;
    }
  },
  choose1 = function(){

  },
  start = function(){
    exploid();
    $btns.click(choose1);
    $start.hide();
  },
  reset = function(){
    window.location.reload(); // cheap as posible !
  },
  init = function(){
    $start.click(start);
    setColors();
  };

  init();

});<|endoftext|>