<commit_before>'use strict';

testRunner.directive('concertoTest', ['$http', '$interval', '$timeout', '$sce', '$compile', '$templateCache', 'dateFilter', 'FileUploader', '$window',
  function ($http, $interval, $timeout, $sce, $compile, $templateCache, dateFilter, FileUploader, $window) {
    function link(scope, element, attrs) {

      $window.addEventListener('unload', function (e) {
        clearTimer();

        $.ajax({
          type: "POST",
          url: settings.directory + "test/session/" + lastResponse.hash + "/kill",
          async: false,
          data: {}
        });
      });

      var DISPLAY_UNKNOWN = -1;
      var DISPLAY_LOADER_SHOWING = 0;
      var DISPLAY_LOADER_SHOWN = 1;
      var DISPLAY_LOADER_HIDING = 2;
      var DISPLAY_LOADER_HIDDEN = 3;
      var DISPLAY_VIEW_SHOWING = 4;
      var DISPLAY_VIEW_SHOWN = 5;
      var DISPLAY_VIEW_HIDING = 6;
      var DISPLAY_VIEW_HIDDEN = 7;
      var RESPONSE_VIEW_TEMPLATE = 0;
      var RESPONSE_FINISHED = 1;
      var RESPONSE_SUBMIT = 2;
      var RESPONSE_VIEW_FINAL_TEMPLATE = 5;
      var RESPONSE_AUTHENTICATION_FAILED = 8;
      var RESPONSE_STARTING = 9;
      var RESPONSE_KEEPALIVE_CHECKIN = 10;
      var RESPONSE_UNRESUMABLE = 11;
      var RESPONSE_SESSION_LIMIT_REACHED = 12;
      var RESPONSE_TEST_NOT_FOUND = 13;
      var RESPONSE_SESSION_LOST = 14;
      var RESPONSE_WORKER = 15;
      var RESPONSE_ERROR = -1;
      var SOURCE_PANEL_NODE = 0;
      var SOURCE_PROCESS = 1;
      var SOURCE_TEST_NODE = 2;
      var settings = angular.extend({
        debug: false,
        clientDebug: false,
        params: null,
        directory: "/",
        testSlug: null,
        testName: null,
        hash: null,
        unresumableHtml: $templateCache.get("unresumable_template.html"),
        finishedHtml: $templateCache.get("finished_template.html"),
        testErrorHtml: $templateCache.get("test_error_template.html"),
        serverErrorHtml: $templateCache.get("server_error_template.html"),
        clientErrorHtml: $templateCache.get("client_error_template.html"),
        sessionLimitReachedHtml: $templateCache.get("session_limit_reached_template.html"),
        testNotFoundHtml: $templateCache.get("test_not_found_template.html"),
        sessionLostHtml: $templateCache.get("session_lost_template.html"),
        connectionRetryHtml: $templateCache.get("connection_retry_template.html"),
        loaderHtml: $templateCache.get("loading_template.html"),
        timeFormat: "HH:mm:ss",
        keepAliveInterval: 0
      }, scope.options);
      var timeLimit = 0;
      var timer = 0;
      var timerId;
      var retryTimeTotal = 15;
      var retryTimer = 0;
      var retryTimerId;
      var keepAliveTimerPromise;
      var displayState = DISPLAY_UNKNOWN;
      var isViewReady = false;
      var lastResponseTime = 0;
      var lastResponse = null;
      scope.timeLeft = "";
      scope.retryTimeLeft = "";

      scope.html = settings.loaderHtml;
      scope.fileUploader = new FileUploader();
      scope.fileUploader.removeAfterUpload = true;
      scope.R = {};

      scope.$watch('html', function (newValue) {
        try {
          angular.element("#testHtml").empty().append(newValue);
          $compile(element.contents())(scope);
        } catch (e) {
          scope.logClientSideError(e.toString());
        }

        if (displayState === DISPLAY_VIEW_SHOWN && lastResponse != null && lastResponse.code === RESPONSE_VIEW_TEMPLATE) {
          initializeTimer();
          startKeepAlive(lastResponse);
          addSubmitEvents();
        }
      });

      scope.logClientSideError = function (error) {
        $http.post(settings.directory + "test/session/" + lastResponse.hash + "/log", {
          error: error
        });
        console.error(error);
      };

      function joinHtml(css, js, html) {
        if (js != null)
          html = html + "<script>" + js + "</script>";
        if (css != null)
          html = "<style>" + css + "</style>" + html;
        return html;
      }

      function clearTimer() {
        $interval.cancel(timerId);
        $interval.cancel(keepAliveTimerPromise);
        $interval.cancel(retryTimerId);
      }

      function initializeTimer() {
        if (timeLimit > 0) {
          timer = timeLimit;
          scope.timeLeft = dateFilter(new Date(0, 0, 0, 0, 0, timer), settings.timeFormat);
          timerId = $interval(function () {
            timeTick();
          }, 1000);
        } else {
          scope.timeLeft = "";
        }
      }

      function startKeepAlive(lastResponse) {
        if (settings.clientDebug)
          console.log("start keep alive (" + settings.keepAliveInterval + ")");
        if (settings.keepAliveInterval > 0) {
          keepAliveTimerPromise = $interval(function () {
            $http.post(settings.directory + "test/session/" + lastResponse.hash + "/keepalive", {}).success(function (response) {
              if (settings.clientDebug)
                console.log("keep-alive ping");
              if (displayState !== DISPLAY_VIEW_SHOWN || lastResponse == null || lastResponse.code !== RESPONSE_VIEW_TEMPLATE || response.code !== RESPONSE_KEEPALIVE_CHECKIN)
                $interval.cancel(keepAliveTimerPromise);
            });
          }, settings.keepAliveInterval * 1000);
        }
      }

      function timeTick() {
        if (timer > 0) {
          timer--;
          scope.timeLeft = dateFilter(new Date(0, 0, 0, 0, 0, timer), settings.timeFormat);
          if (timer === 0) {
            scope.submitView("timeout", true);
          }
        }
      }

      function startNewTest() {
        if (settings.clientDebug)
          console.log("start");

        showLoader();
        var path = "";
        if (settings.debug) {
          path = settings.directory + "admin/test/" + settings.testSlug + "/session/start/debug/" + encodeURIComponent(settings.params);
        } else {
          if (settings.testName !== null) {
            path = settings.directory + "test_n/" + settings.testName + "/session/start/" + encodeURIComponent(settings.params);
          } else {
            path = settings.directory + "test/" + settings.testSlug + "/session/start/" + encodeURIComponent(settings.params);
          }
        }

        $http.post(path, {}).success(function (response) {
          if (settings.clientDebug)
            console.log(response);
          if (settings.debug && response.debug)
            console.log(response.debug);
          lastResponse = response;
          lastResponseTime = new Date();
          isViewReady = true;

          switch (lastResponse.code) {
            case RESPONSE_VIEW_TEMPLATE:
            case RESPONSE_VIEW_FINAL_TEMPLATE: {
              settings.hash = response.hash;
              timeLimit = response.timeLimit;
              updateLoader(response.data);
              break;
            }
          }

          showView();
        });
      }

      function updateLoader(data) {
        var loaderHead = data.loaderHead ? data.loaderHead.trim() : null;
        var loaderCss = data.loaderCss ? data.loaderCss.trim() : null;
        var loaderJs = data.loaderJs ? data.loaderJs.trim() : null;
        var loaderHtml = data.loaderHtml ? data.loaderHtml.trim() : null;
        if (loaderCss || loaderJs || loaderHtml) {
          settings.loaderHtml = joinHtml(loaderCss, loaderJs, loaderHtml);
        }
        if (loaderHead) {<commit_msg>server and client errors handling on session start<commit_after>'use strict';

testRunner.directive('concertoTest', ['$http', '$interval', '$timeout', '$sce', '$compile', '$templateCache', 'dateFilter', 'FileUploader', '$window',
  function ($http, $interval, $timeout, $sce, $compile, $templateCache, dateFilter, FileUploader, $window) {
    function link(scope, element, attrs) {

      $window.addEventListener('unload', function (e) {
        clearTimer();

        $.ajax({
          type: "POST",
          url: settings.directory + "test/session/" + lastResponse.hash + "/kill",
          async: false,
          data: {}
        });
      });

      var DISPLAY_UNKNOWN = -1;
      var DISPLAY_LOADER_SHOWING = 0;
      var DISPLAY_LOADER_SHOWN = 1;
      var DISPLAY_LOADER_HIDING = 2;
      var DISPLAY_LOADER_HIDDEN = 3;
      var DISPLAY_VIEW_SHOWING = 4;
      var DISPLAY_VIEW_SHOWN = 5;
      var DISPLAY_VIEW_HIDING = 6;
      var DISPLAY_VIEW_HIDDEN = 7;
      var RESPONSE_VIEW_TEMPLATE = 0;
      var RESPONSE_FINISHED = 1;
      var RESPONSE_SUBMIT = 2;
      var RESPONSE_VIEW_FINAL_TEMPLATE = 5;
      var RESPONSE_AUTHENTICATION_FAILED = 8;
      var RESPONSE_STARTING = 9;
      var RESPONSE_KEEPALIVE_CHECKIN = 10;
      var RESPONSE_UNRESUMABLE = 11;
      var RESPONSE_SESSION_LIMIT_REACHED = 12;
      var RESPONSE_TEST_NOT_FOUND = 13;
      var RESPONSE_SESSION_LOST = 14;
      var RESPONSE_WORKER = 15;
      var RESPONSE_ERROR = -1;
      var SOURCE_PANEL_NODE = 0;
      var SOURCE_PROCESS = 1;
      var SOURCE_TEST_NODE = 2;
      var settings = angular.extend({
        debug: false,
        clientDebug: false,
        params: null,
        directory: "/",
        testSlug: null,
        testName: null,
        hash: null,
        unresumableHtml: $templateCache.get("unresumable_template.html"),
        finishedHtml: $templateCache.get("finished_template.html"),
        testErrorHtml: $templateCache.get("test_error_template.html"),
        serverErrorHtml: $templateCache.get("server_error_template.html"),
        clientErrorHtml: $templateCache.get("client_error_template.html"),
        sessionLimitReachedHtml: $templateCache.get("session_limit_reached_template.html"),
        testNotFoundHtml: $templateCache.get("test_not_found_template.html"),
        sessionLostHtml: $templateCache.get("session_lost_template.html"),
        connectionRetryHtml: $templateCache.get("connection_retry_template.html"),
        loaderHtml: $templateCache.get("loading_template.html"),
        timeFormat: "HH:mm:ss",
        keepAliveInterval: 0
      }, scope.options);
      var timeLimit = 0;
      var timer = 0;
      var timerId;
      var retryTimeTotal = 15;
      var retryTimer = 0;
      var retryTimerId;
      var keepAliveTimerPromise;
      var displayState = DISPLAY_UNKNOWN;
      var isViewReady = false;
      var lastResponseTime = 0;
      var lastResponse = null;
      scope.timeLeft = "";
      scope.retryTimeLeft = "";

      scope.html = settings.loaderHtml;
      scope.fileUploader = new FileUploader();
      scope.fileUploader.removeAfterUpload = true;
      scope.R = {};

      scope.$watch('html', function (newValue) {
        try {
          angular.element("#testHtml").empty().append(newValue);
          $compile(element.contents())(scope);
        } catch (e) {
          scope.logClientSideError(e.toString());
        }

        if (displayState === DISPLAY_VIEW_SHOWN && lastResponse != null && lastResponse.code === RESPONSE_VIEW_TEMPLATE) {
          initializeTimer();
          startKeepAlive(lastResponse);
          addSubmitEvents();
        }
      });

      scope.logClientSideError = function (error) {
        $http.post(settings.directory + "test/session/" + lastResponse.hash + "/log", {
          error: error
        });
        console.error(error);
      };

      function joinHtml(css, js, html) {
        if (js != null)
          html = html + "<script>" + js + "</script>";
        if (css != null)
          html = "<style>" + css + "</style>" + html;
        return html;
      }

      function clearTimer() {
        $interval.cancel(timerId);
        $interval.cancel(keepAliveTimerPromise);
        $interval.cancel(retryTimerId);
      }

      function initializeTimer() {
        if (timeLimit > 0) {
          timer = timeLimit;
          scope.timeLeft = dateFilter(new Date(0, 0, 0, 0, 0, timer), settings.timeFormat);
          timerId = $interval(function () {
            timeTick();
          }, 1000);
        } else {
          scope.timeLeft = "";
        }
      }

      function startKeepAlive(lastResponse) {
        if (settings.clientDebug)
          console.log("start keep alive (" + settings.keepAliveInterval + ")");
        if (settings.keepAliveInterval > 0) {
          keepAliveTimerPromise = $interval(function () {
            $http.post(settings.directory + "test/session/" + lastResponse.hash + "/keepalive", {}).success(function (response) {
              if (settings.clientDebug)
                console.log("keep-alive ping");
              if (displayState !== DISPLAY_VIEW_SHOWN || lastResponse == null || lastResponse.code !== RESPONSE_VIEW_TEMPLATE || response.code !== RESPONSE_KEEPALIVE_CHECKIN)
                $interval.cancel(keepAliveTimerPromise);
            });
          }, settings.keepAliveInterval * 1000);
        }
      }

      function timeTick() {
        if (timer > 0) {
          timer--;
          scope.timeLeft = dateFilter(new Date(0, 0, 0, 0, 0, timer), settings.timeFormat);
          if (timer === 0) {
            scope.submitView("timeout", true);
          }
        }
      }

      function startNewTest() {
        if (settings.clientDebug)
          console.log("start");

        showLoader();
        var path = "";
        if (settings.debug) {
          path = settings.directory + "admin/test/" + settings.testSlug + "/session/start/debug/" + encodeURIComponent(settings.params);
        } else {
          if (settings.testName !== null) {
            path = settings.directory + "test_n/" + settings.testName + "/session/start/" + encodeURIComponent(settings.params);
          } else {
            path = settings.directory + "test/" + settings.testSlug + "/session/start/" + encodeURIComponent(settings.params);
          }
        }

        $http.post(path, {}).success(function (response) {
          if (settings.clientDebug)
            console.log(response);
          if (settings.debug && response.debug)
            console.log(response.debug);
          lastResponse = response;
          lastResponseTime = new Date();
          isViewReady = true;

          switch (lastResponse.code) {
            case RESPONSE_VIEW_TEMPLATE:
            case RESPONSE_VIEW_FINAL_TEMPLATE: {
              settings.hash = response.hash;
              timeLimit = response.timeLimit;
              updateLoader(response.data);
              break;
            }
          }

          showView();
        }).error(function(error, status) {
          if (status >= 500 && status < 600) {
            if (settings.clientDebug)
              console.log("server error");
            isViewReady = true;
            showView(settings.serverErrorHtml);
          } else if (status >= 400 && status < 500) {
            if (settings.clientDebug)
              console.log("client error");
            isViewReady = true;
            showView(settings.clientErrorHtml);
          }
        });
      }

      function updateLoader(data) {
        var loaderHead = data.loaderHead ? data.loaderHead.trim() : null;
        var loaderCss = data.loaderCss ? data.loaderCss.trim() : null;
        var loaderJs = data.loaderJs ? data.loaderJs.trim() : null;
        var loaderHtml = data.loaderHtml ? data.loaderHtml.trim() : null;
        if (loaderCss || loaderJs || loaderHtml) {
          settings.loaderHtml = joinHtml(loaderCss, loaderJs, loaderHtml);
        }
        if (loaderHead) {
{'fraction_non_alphanumeric': 0.12129467470973601, 'fraction_numerical': 0.008561977038334306, 'mean_word_length': 2.249315068493151, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '264572', 'n_tokens_mistral': 4623, 'n_tokens_neox': 4464, 'n_words': 884}