<commit_before>var Client = module.exports

var Promise = require("bluebird")
var request = require("request")
var routes = require("../routes")

var d = require("debug")("raptorjs:client:http")

Client.create = function (container) {

    var emit = function() {
        container.emit.apply(container, arguments)
    }

    var opts = container.config

    var addDefaultHeaders = function(opts, token) {
        if(!opts.headers) {
            opts.headers = {
                "Content-Type": "application/json"
            }
        }
        if(token) {
            opts.headers.Authorization = `Bearer ${token}`
        }
    }

    var defaultsOptions = {
        baseUrl: opts.url,
        json: true,
        debug: opts.debug
    }

    addDefaultHeaders(defaultsOptions)

    var client = request.defaults(defaultsOptions)

    d("Created new client %s", defaultsOptions.baseUrl)

    var instance = {}

    instance.baseRequest = (options) => {
        return new Promise(function (resolve, reject) {

            options.headers = Object.assign({}, defaultsOptions.headers || {}, options.headers || {})

            d("Performing request %j", options)
            client(options, function (err, res, body) {

                if(err) {
                    d("Request failed %s", err.message)

                    emit("request.error", err)
                    emit("request.complete", false)

                    return reject(err)
                }

                var json
                try {
                    json = JSON.parse(body)
                } catch(e) {
                    json = body
                }

                if(res.statusCode >= 400 || res.statusCode < 200) {

                    if (res.statusCode === 0) {
                        res.statusMessage = "Cannot perform request"
                    }

                    let error = {
                        code: json ? json.code : res.statusCode,
                        message: json ? json.message : res.statusMessage,
                    }

                    if (body) {
                        d("Error body: \n %j", body)
                    }

                    d("Request error %s %s", error.code, error.message)

                    emit("request.error", error)
                    emit("request.complete", false)

                    const err = new Error(error.message)
                    err.code = error.code

                    return reject(err)
                }

                d("Request response: %j", json)

                emit("request.complete", json)
                resolve(json)
            })

        })
    }

    instance.request = function (options) {

        // do not try to login if requesting login / get user
        var userReq =  (
            options.url === routes.LOGIN ||
                options.url === routes.USER_GET_ME ||
                    options.url === routes.REFRESH_TOKEN
        ) ?
            Promise.resolve() : container.Auth().loadUser()

        emit("request.start", options)

        return userReq.then(function () {

            if(container.Auth().getToken()) {
                addDefaultHeaders(options, container.Auth().getToken())
            }

            return instance.baseRequest(options)
        })

    }

    instance.get = function (url) {
        return instance.request({
            method: "GET",
            url: url
        })
    }

    instance.delete = function (url) {
        return instance.request({
            method: "DELETE",
            url: url
        })
    }

    instance.put = function (url, data) {
        return instance.request({
            method: "PUT",
            url: url,
            body: data
        })
    }

    instance.post = function (url, data) {
        return instance.request({
            method: "POST",
            url: url,
            body: data
        })
    }

    instance.client = client

    return instance
}
<commit_msg>use axios instead of requests<commit_after>var Client = module.exports

var Promise = require("bluebird")
//var request = require("request")
var routes = require("../routes")
var axios = require("axios")

var d = require("debug")("raptorjs:client:http")

Client.create = function (container) {

    var emit = function() {
        container.emit.apply(container, arguments)
    }

    var opts = container.config

    var addDefaultHeaders = function(opts, token) {
        if(!opts.headers) {
            opts.headers = {
                "Content-Type": "application/json"
            }
        }
        if(token) {
            opts.headers.Authorization = `Bearer ${token}`
        }
    }

    var defaultsOptions = {
        baseUrl: opts.url
        //json: true,
        //debug: opts.debug
    }

    addDefaultHeaders(defaultsOptions)

    //var client = request.defaults(defaultsOptions)
    console.log('using axios')
    var client = axios.defaults(defaultsOptions)

    d("Created new client %s", defaultsOptions.baseUrl)

    var instance = {}

    instance.baseRequest = (options) => {
        return new Promise(function (resolve, reject) {

            options.headers = Object.assign({}, defaultsOptions.headers || {}, options.headers || {})

            d("Performing request %j", options)
            //client(options, function (err, res, body) {
            axios(options).then((res) {

                var json
                try {
                    json = JSON.parse(res.data)
                } catch(e) {
                    json = res.data
                }

                if(res.status >= 400 || res.status < 200) {

                    if (res.status === 0) {
                        res.statusMessage = "Cannot perform request"
                    }

                    let error = {
                        code: json ? json.code : res.status,
                        message: json ? json.message : res.statusText,
                    }

                    if (res.data) {
                        d("Error body: \n %j", res.data)
                    }

                    d("Request error %s %s", error.code, error.message)

                    emit("request.error", error)
                    emit("request.complete", false)

                    const err = new Error(error.message)
                    err.code = error.code

                    return reject(err)
                }

                d("Request response: %j", json)

                emit("request.complete", json)
                resolve(json)
            }).catch(function (error) {
                console.error(error)
                return reject(error)
            })

        })
    }

    instance.request = function (options) {

        // do not try to login if requesting login / get user
        var userReq =  (
            options.url === routes.LOGIN ||
                options.url === routes.USER_GET_ME ||
                    options.url === routes.REFRESH_TOKEN
        ) ?
            Promise.resolve() : container.Auth().loadUser()

        emit("request.start", options)

        return userReq.then(function () {

            if(container.Auth().getToken()) {
                addDefaultHeaders(options, container.Auth().getToken())
            }

            return instance.baseRequest(options)
        })

    }

    instance.get = function (url) {
        return instance.request({
            method: "GET",
            url: url
        })
    }

    instance.delete = function (url) {
        return instance.request({
            method: "DELETE",
            url: url
        })
    }

    instance.put = function (url, data) {
        return instance.request({
            method: "PUT",
            url: url,
            data: data
        })
    }

    instance.post = function (url, data) {
        return instance.request({
            method: "POST",
            url: url,
            data: data
        })
    }

    instance.client = client

    return instance
}
<|endoftext|>


<commit_before>/* global $:false,bootbox,document,BootBoxWiz,Server,processPanelMessages,processDataSourceMessages,displayPanelDialog,WidgetManager, AgileSprintManager, JenkinsBuildManager */

/*
 * Main javascript logic for index.html
 *
 * Dependancies:
 *    jquery
 *    css/styles.css
 */

var server = null;
var addPanelMode = false;
var panelDragAndDrop;
var agileSprintManager = null;
var jenkinsBuildManager = null;
var widgetManager = null;
var dataSourceManager = null;
var preferenceManager = null;
var localPreferenceManager = null;
// TODO: refactor this to get rid of globals
var configMode = false;

function configureApplication() {
  widgetManager = new WidgetManager();
  agileSprintManager = new AgileSprintManager({widgetManager: widgetManager});
  jenkinsBuildManager = new JenkinsBuildManager({widgetManager: widgetManager});
  dataSourceManager = new DataSourceManager();
  preferenceManager = new PreferenceManager();
  localPreferenceManager = new LocalPreferenceManager();

  addApplicationButtonListeners();

  // apply select picker styling
  $('.selectpicker').selectpicker();

  // apply jasny rowlink logic to tables
  // $('tbody.rowlink').rowlink();

  server = new Server({
    messageHandlers: [
      processPanelMessages,
      dataSourceManager.processMessages.bind(dataSourceManager),
      preferenceManager.processMessages.bind(preferenceManager),
      localPreferenceManager.processMessages.bind(localPreferenceManager),
      widgetManager.processMessages.bind(widgetManager),
      agileSprintManager.processMessages.bind(agileSprintManager),
      jenkinsBuildManager.processMessages.bind(jenkinsBuildManager),
    ]
  });

  widgetManager.server = server;
  widgetManager.dataSourceManager = dataSourceManager;
  dataSourceManager.server = server;
  preferenceManager.server = server;
  localPreferenceManager.server = server;
  server.connect();

  panelDragAndDrop = new PanelDragAndDrop({
    server: server,
    columnSelector: ".column",
    panelSelector: ".panel",
    handle: ".panel-heading",
    placeholderClass: "panel-placeholder",
    doNotSelect: ".panel-controls",
    dragClass: "draggable",
  });
}

function addApplicationButtonListeners() {

  $("body").on('change', '#toggleConfigMode', function() {
    toggleConfigMode();
  });

  $("body").on('click', '#viewHome', function() {
    toggleButtonViewSelection('viewHome');
    showAddPanelButton();
    displayPane("homePane");
  });

  $("body").on('click', '#viewSettings', function() {
    toggleButtonViewSelection('viewSettings');
    hideAddPanelButton();
    displayPane("settingsPane");
  });

  $("body").on('click', '#viewThemes', function() {
    toggleButtonViewSelection('viewThemes');
    hideAddPanelButton();
    displayPane("themesPane");
  });

  $("body").on('click', '#viewContent', function() {
    toggleButtonViewSelection('viewContent');
    hideAddPanelButton();
    displayPane("bannerContentPane");
  });

  $("#viewDataSources").on('click', function() {
    toggleButtonViewSelection('viewDataSources');
    hideAddPanelButton();
    displayPane("dataSourcesPane");
  });

  $("body").on('click', '#addPanel', function() {
    displayPanelDialog('add');
  });

  // TODO: better manage adding triggers for sub areas
  dataSourceManager.setupDataSourcesPane();
  preferenceManager.setupPreferencePane();
  localPreferenceManager.setupLocalPreference();
}

function enableConfigMode() {
  configMode = true;
  $(".config-buttons").fadeIn("slow", function() {}).addClass('displayButton').css('display', '');
  panelDragAndDrop.enable();
  widgetManager.enableConfigMode();
}

function disableConfigMode() {
  configMode = false;
  var currentPaneId = $('.activePane').attr('id');

  if(currentPaneId !== "") {
    $("#viewHome").trigger('click');
  }

  panelDragAndDrop.disable();
  widgetManager.disableConfigMode();
  $(".config-buttons").fadeOut("slow", function() {$(".config-buttons").css("display", ""); }).removeClass('displayButton');
}

function toggleConfigMode() {
  if(configMode) {
    disableConfigMode();
  } else {
    enableConfigMode();
    addPanelMode = true;
  }
}

function toggleButtonViewSelection(buttonId) {
  var previousId = $('.config-button-active').attr('id');

  $('#' + previousId).toggleClass('config-button-inactive');
  $('#' + previousId).toggleClass('config-button-active');

  $('#' + buttonId).toggleClass('config-button-inactive');
  $('#' + buttonId).toggleClass('config-button-active');
}

function showAddPanelButton() {
  showPanelButton('addPanel');
  addPanelMode = true;
}

function hideAddPanelButton() {
  hidePanelButton('addPanel');
  addPanelMode = false;
}

function showPanelButton(buttonId) {
  $('#' + buttonId).removeClass('hiddenButton');
  panelDragAndDrop.enable();
  widgetManager.enableConfigMode();
}

function hidePanelButton(buttonId) {
  $('#' + buttonId).addClass('hiddenButton');
  panelDragAndDrop.disable();
  widgetManager.disableConfigMode();
}

function displayPane(paneId) {
  var previousId = $('.activePane').attr('id');

  if(previousId === paneId) {
    return;
  }

  $('#' + previousId).fadeToggle("fast", function() {
    $(this).toggleClass('activePane');
    $('#' + paneId).fadeToggle("fast", function() {
      $(this).toggleClass('activePane');
    });
  });
}

function viewDataSourceDetailPane(key) {
  displayPane("dataSourceDetail");
}<commit_msg>Renamed calls to setup preferences to setup<commit_after>/* global $:false,bootbox,document,BootBoxWiz,Server,processPanelMessages,processDataSourceMessages,displayPanelDialog,WidgetManager, AgileSprintManager, JenkinsBuildManager */

/*
 * Main javascript logic for index.html
 *
 * Dependancies:
 *    jquery
 *    css/styles.css
 */

var server = null;
var addPanelMode = false;
var panelDragAndDrop;
var agileSprintManager = null;
var jenkinsBuildManager = null;
var widgetManager = null;
var dataSourceManager = null;
var preferenceManager = null;
var localPreferenceManager = null;
// TODO: refactor this to get rid of globals
var configMode = false;

function configureApplication() {
  widgetManager = new WidgetManager();
  agileSprintManager = new AgileSprintManager({widgetManager: widgetManager});
  jenkinsBuildManager = new JenkinsBuildManager({widgetManager: widgetManager});
  dataSourceManager = new DataSourceManager();
  preferenceManager = new PreferenceManager();
  localPreferenceManager = new LocalPreferenceManager();

  addApplicationButtonListeners();

  // apply select picker styling
  $('.selectpicker').selectpicker();

  // apply jasny rowlink logic to tables
  // $('tbody.rowlink').rowlink();

  server = new Server({
    messageHandlers: [
      processPanelMessages,
      dataSourceManager.processMessages.bind(dataSourceManager),
      preferenceManager.processMessages.bind(preferenceManager),
      localPreferenceManager.processMessages.bind(localPreferenceManager),
      widgetManager.processMessages.bind(widgetManager),
      agileSprintManager.processMessages.bind(agileSprintManager),
      jenkinsBuildManager.processMessages.bind(jenkinsBuildManager),
    ]
  });

  widgetManager.server = server;
  widgetManager.dataSourceManager = dataSourceManager;
  dataSourceManager.server = server;
  preferenceManager.server = server;
  localPreferenceManager.server = server;
  server.connect();

  panelDragAndDrop = new PanelDragAndDrop({
    server: server,
    columnSelector: ".column",
    panelSelector: ".panel",
    handle: ".panel-heading",
    placeholderClass: "panel-placeholder",
    doNotSelect: ".panel-controls",
    dragClass: "draggable",
  });
}

function addApplicationButtonListeners() {

  $("body").on('change', '#toggleConfigMode', function() {
    toggleConfigMode();
  });

  $("body").on('click', '#viewHome', function() {
    toggleButtonViewSelection('viewHome');
    showAddPanelButton();
    displayPane("homePane");
  });

  $("body").on('click', '#viewSettings', function() {
    toggleButtonViewSelection('viewSettings');
    hideAddPanelButton();
    displayPane("settingsPane");
  });

  $("body").on('click', '#viewThemes', function() {
    toggleButtonViewSelection('viewThemes');
    hideAddPanelButton();
    displayPane("themesPane");
  });

  $("body").on('click', '#viewContent', function() {
    toggleButtonViewSelection('viewContent');
    hideAddPanelButton();
    displayPane("bannerContentPane");
  });

  $("#viewDataSources").on('click', function() {
    toggleButtonViewSelection('viewDataSources');
    hideAddPanelButton();
    displayPane("dataSourcesPane");
  });

  $("body").on('click', '#addPanel', function() {
    displayPanelDialog('add');
  });

  // TODO: better manage adding triggers for sub areas
  dataSourceManager.setupDataSourcesPane();
  localPreferenceManager.setup();
  preferenceManager.setup();
}

function enableConfigMode() {
  configMode = true;
  $(".config-buttons").fadeIn("slow", function() {}).addClass('displayButton').css('display', '');
  panelDragAndDrop.enable();
  widgetManager.enableConfigMode();
}

function disableConfigMode() {
  configMode = false;
  var currentPaneId = $('.activePane').attr('id');

  if(currentPaneId !== "") {
    $("#viewHome").trigger('click');
  }

  panelDragAndDrop.disable();
  widgetManager.disableConfigMode();
  $(".config-buttons").fadeOut("slow", function() {$(".config-buttons").css("display", ""); }).removeClass('displayButton');
}

function toggleConfigMode() {
  if(configMode) {
    disableConfigMode();
  } else {
    enableConfigMode();
    addPanelMode = true;
  }
}

function toggleButtonViewSelection(buttonId) {
  var previousId = $('.config-button-active').attr('id');

  $('#' + previousId).toggleClass('config-button-inactive');
  $('#' + previousId).toggleClass('config-button-active');

  $('#' + buttonId).toggleClass('config-button-inactive');
  $('#' + buttonId).toggleClass('config-button-active');
}

function showAddPanelButton() {
  showPanelButton('addPanel');
  addPanelMode = true;
}

function hideAddPanelButton() {
  hidePanelButton('addPanel');
  addPanelMode = false;
}

function showPanelButton(buttonId) {
  $('#' + buttonId).removeClass('hiddenButton');
  panelDragAndDrop.enable();
  widgetManager.enableConfigMode();
}

function hidePanelButton(buttonId) {
  $('#' + buttonId).addClass('hiddenButton');
  panelDragAndDrop.disable();
  widgetManager.disableConfigMode();
}

function displayPane(paneId) {
  var previousId = $('.activePane').attr('id');

  if(previousId === paneId) {
    return;
  }

  $('#' + previousId).fadeToggle("fast", function() {
    $(this).toggleClass('activePane');
    $('#' + paneId).fadeToggle("fast", function() {
      $(this).toggleClass('activePane');
    });
  });
}

function viewDataSourceDetailPane(key) {
  displayPane("dataSourceDetail");
}<|endoftext|>


<commit_before>/**
 * Functions/constants needed by both the client and server (but only in node).
 * These are separate from common.js so they can be skipped when bundling for the browser.
 */

var Buffer = require('safe-buffer').Buffer
var querystring = require('querystring')

exports.IPV4_RE = /^[\d.]+$/
exports.IPV6_RE = /^[\da-fA-F:]+$/
exports.REMOVE_IPV4_MAPPED_IPV6_RE = /^::ffff:/

exports.CONNECTION_ID = Buffer.concat([ toUInt32(0x417), toUInt32(0x27101980) ])
exports.ACTIONS = { CONNECT: 0, ANNOUNCE: 1, SCRAPE: 2, ERROR: 3 }
exports.EVENTS = { update: 0, completed: 1, started: 2, stopped: 3 }
exports.EVENT_IDS = {
  0: 'update',
  1: 'completed',
  2: 'started',
  3: 'stopped'
}
exports.EVENT_NAMES = {
  update: 'update',
  completed: 'complete',
  started: 'start',
  stopped: 'stop'
}

/**
 * Client request timeout. How long to wait before considering a request to a
 * tracker server to have timed out.
 */
exports.REQUEST_TIMEOUT = 15000

/**
 * Client destroy timeout. How long to wait before forcibly cleaning up all
 * pending requests, open sockets, etc.
 */
exports.DESTROY_TIMEOUT = 1000

function toUInt32 (n) {
  var buf = Buffer.allocUnsafe(4)
  buf.writeUInt32BE(n, 0)
  return buf
}
exports.toUInt32 = toUInt32

/**
 * `querystring.parse` using `unescape` instead of decodeURIComponent, since bittorrent
 * clients send non-UTF8 querystrings
 * @param  {string} q
 * @return {Object}
 */
exports.querystringParse = function (q) {
  var saved = querystring.unescape
  querystring.unescape = unescape // global
  var ret = querystring.parse(q)
  querystring.unescape = saved
  return ret
}

/**
 * `querystring.stringify` using `escape` instead of encodeURIComponent, since bittorrent
 * clients send non-UTF8 querystrings
 * @param  {Object} obj
 * @return {string}
 */
exports.querystringStringify = function (obj) {
  var ret = querystring.stringify(obj, { encodeURIComponent: escape })
  ret = ret.replace(/[@*/+]/g, function (char) {
    // `escape` doesn't encode the characters @*/+ so we do it manually
    return '%' + char.charCodeAt(0).toString(16).toUpperCase()
  })
  return ret
}
<commit_msg>Update common-node.js<commit_after>/**
 * Functions/constants needed by both the client and server (but only in node).
 * These are separate from common.js so they can be skipped when bundling for the browser.
 */

var Buffer = require('safe-buffer').Buffer
var querystring = require('querystring')

exports.IPV4_RE = /^[\d.]+$/
exports.IPV6_RE = /^[\da-fA-F:]+$/
exports.REMOVE_IPV4_MAPPED_IPV6_RE = /^::ffff:/

exports.CONNECTION_ID = Buffer.concat([ toUInt32(0x417), toUInt32(0x27101980) ])
exports.ACTIONS = { CONNECT: 0, ANNOUNCE: 1, SCRAPE: 2, ERROR: 3 }
exports.EVENTS = { update: 0, completed: 1, started: 2, stopped: 3 }
exports.EVENT_IDS = {
  0: 'update',
  1: 'completed',
  2: 'started',
  3: 'stopped'
}
exports.EVENT_NAMES = {
  update: 'update',
  completed: 'complete',
  started: 'start',
  stopped: 'stop'
}

/**
 * Client request timeout. How long to wait before considering a request to a
 * tracker server to have timed out.
 */
exports.REQUEST_TIMEOUT = 15000

/**
 * Client destroy timeout. How long to wait before forcibly cleaning up all
 * pending requests, open sockets, etc.
 */
exports.DESTROY_TIMEOUT = 1000

function toUInt32 (n) {
  var buf = Buffer.allocUnsafe(4)
  buf.writeUInt32BE(n, 0)
  return buf
}
exports.toUInt32 = toUInt32

/**
 * `querystring.parse` using `unescape` instead of decodeURIComponent, since bittorrent
 * clients send non-UTF8 querystrings
 * @param  {string} q
 * @return {Object}
 */
exports.querystringParse = function (q) {
  return querystring.parse(q, { decodeURIComponent: unescape })
}

/**
 * `querystring.stringify` using `escape` instead of encodeURIComponent, since bittorrent
 * clients send non-UTF8 querystrings
 * @param  {Object} obj
 * @return {string}
 */
exports.querystringStringify = function (obj) {
  var ret = querystring.stringify(obj, { encodeURIComponent: escape })
  ret = ret.replace(/[@*/+]/g, function (char) {
    // `escape` doesn't encode the characters @*/+ so we do it manually
    return '%' + char.charCodeAt(0).toString(16).toUpperCase()
  })
  return ret
}
<|endoftext|>


<commit_before>var parsedResponse;
$(function () {
    drawGraphs();
});

function drawGraphs() {
    var url = window.location.pathname;
    var comps = url.split('/');
    var type = comps[comps.length - 2];
    var operation = comps[comps.length - 3];
    var action = 'getAppsPopularity';
    var dateRange = $('#date-range').val();

    var from = dateRange.split('to')[0].trim() + ":00";
    var to = dateRange.split('to')[1].trim() + ":00";

    $.ajax({
               async: false,
               url: caramel.context + '/api/assets/' + operation + '/' + type + '/' + action + '/',
               type: 'POST',
               data: {
                   'startDate': from,
                   'endDate': to
               },
               success: function (response) {
                   parsedResponse = response;
                   drawPopularityOverTime(parsedResponse);
                   $('#spinner').hide();
               },
               error: function (response) {
                   alert('Error occurred at statistics graph rendering');
               }
           });

    $('.btn-remove').on('click', function () {
        $(this).parents('.graph-maximized').removeClass('graph-maximized');
        $('.backdrop').hide();
        drawPopularityOverTime(parsedResponse);
    });

}

var drawPopularityOverTime = function (parsedResponse) {
    var data = [];
    var length = parsedResponse.length;

    var dataStructure = [];
    var app = '';
    var hitCount = 0;
    $("#tooltipTable").find("tr:gt(0)").remove();
    for (var p = 0; p < parsedResponse.length; p++) {
        var appName = parsedResponse[p].AppName.replace(/\s+/g, '');
        data.push({
                      App: appName,
                      Hits: parsedResponse[p].TotalHits
                  });
    }

    $('.graph-container').html('');
    $('#tableContainer').html('');
    var svg = dimple.newSvg(".graph-container", "100%", 500);
    chart = new dimple.chart(svg, data);

    chart.setBounds("10%", "10%", "75%", "60%");
    x = chart.addCategoryAxis("x", "App");

    y = chart.addMeasureAxis("y", "Hits");
    y.title = "Hit Count";
    var data = [];
    var length = parsedResponse.length;

    var dataStructure = [];
    var app = '';
    var hitCount = 0;
    $("#tooltipTable").find("tr:gt(0)").remove();
    for (var p = 0; p < parsedResponse.length; p++) {
        var appName = parsedResponse[p].AppName.replace(/\s+/g, '');
        data.push({
                      App: appName,
                      Hits: parsedResponse[p].TotalHits
                  });
    }

    $('.graph-container').html('');
    $('#tableContainer').html('');
    var svg = dimple.newSvg(".graph-container", "100%", 500);
    chart = new dimple.chart(svg, data);

    chart.setBounds("10%", "10%", "75%", "60%");
    x = chart.addCategoryAxis("x", "App");
    y = chart.addMeasureAxis("y", "Hits");
    chart.addButtonName
    y.title = "Hit Count";
    x.title = "Apps";
    y.tickFormat = '1d';

    s = chart.addSeries("App", dimple.plot.bar);
    var div = d3.select("body").append("div").attr("class", "toolTip");

    var filterValues = dimple.getUniqueValues(data, "App");
    var state_array = [];
    var defaultFilterValues = [];
    var sortData = [];
    var chartData = [];

    var $dataTable = $('

');
    $dataTable.append($('

' +
                        '	' +
                        'App Name	' +
                        'Hits Count	'+
                        '

'));

    sortData = dimple.filterData(data, "App", filterValues);
    sortData.sort(function (obj1, obj2) {
        return obj2.Hits - obj1.Hits;
    });

    for (var n = 0; n < sortData.length; n++) {
        if (n < 20) {
            $dataTable.append($('
'
                                    + '<input name="item_checkbox' + n + '"  checked   id=' + n +
                                '  type="checkbox"  data-item=' + sortData[n].App  + ' class="inputCheckbox"/>'
                                    + '	'
                                    + '' + sortData[n].App +' 	'
                                    +''+sortData[n].Hits +'	'
                                    +'
'));
            state_array.push(true);
            defaultFilterValues.push(sortData[n].App);
            chartData.push(sortData[n].App);
        } else {
            $dataTable.append($('
'
                                    +'<input name="item_checkbox'+n+'"  id='+n+'  type="checkbox"  data-item='+sortData[n].App +' class="inputCheckbox"/>'
                                    +'	'
                                    +''+sortData[n].App +' 	'
                                    +''+sortData[n].Hits +'	'
                                    +'
'));
            state_array.push(false);
            chartData.push(sortData[n].App);
        }
    }

    if (parsedResponse.length == 0) {
        $('.graph-container').html('
No data available
');
    } else {
        $('.graph-container').show();
        $('#tableContainer').append($dataTable);
        $('#tableContainer').show();
        var table= $('#apiSelectTable').DataTable({
                                                      retrieve: true,
                                                      "order": [
                                                          [ 1, "desc" ]
                                                      ],
                                                      "fnDrawCallback": function(){
                                                          if(this.fnSettings().fnRecordsDisplay()<=$("#apiSelectTable_length option:selected" ).val()
                                                              || $("#apiSelectTable_length option:selected" ).val()==-1)
                                                              $('#apiSelectTable_paginate').hide();
                                                          else
                                                              $('#apiSelectTable_paginate').show();
                                                      },
                                                      "aoColumns": [
                                                          { "bSortable": false },
                                                          null,
                                                          null
                                                      ]
                                                  });

        $('.details-control').removeClass('sorting');
        var detailRows = [];
        $('#apiSelectTable tbody').on( 'click', 'tr td.details-control', function () {
            var tr = $(this).closest('tr');
            var row = table.row( tr );
            if ( row.child.isShown() ) {
                $('div.slider', row.child()).slideUp( function () {
                    row.child.hide();
                    tr.removeClass('shown');
                } );
            }
            else {
                row.child( format(row.data()), 'no-padding' ).show();
                tr.addClass('shown');
                $('div.slider', row.child()).slideDown();
            }
        } );

        $('select').css('width','60px');
        chart.data = dimple.filterData(data, "App", defaultFilterValues);
        var count = 20;
        $('#apiSelectTable').on( 'change', 'input.inputCheckbox', function () {
            var id =  $(this).attr('id');
            var check=$(this).is(':checked');
            var draw_chart=[];

            if (check) {
                $('#displayMsg').html('');
                count++;
                //limiting to show 20 entries at a time
                if(count>20){
                    $('#displayMsg').html('
Please Note that the graph will be showing only 20 entries
');
                    state_array[id] = false;
                    $(this).prop("checked", "");
                    count--;
                }else{
                    state_array[id] = true;
                }
            } else {
                $('#displayMsg').html('');
                state_array[id] = false;
                count--;
            }

            $.each(chartData, function (index, value) {
                if (state_array[index]){
                    draw_chart.push(value);
                }
            });

            chart.data = dimple.filterData(data, "App", draw_chart);
            chart.draw();
        });

        s.afterDraw = function (shp, d) {
            var shape = d3.select(shp);
            var bar = d3.selectAll("rect");
            bar.on("click", function (d) {
                drawPopupChart(parsedResponse, d.aggField, this);
            });
            bar.on("mouseout", function (d) {
                div.style("display", "none");
            });
        };
        chart.draw();
        window.onresize = function () {
            chart.draw(0, true);
        };
    }
}

var onDateSelected = function () {
    clearTables();
    drawGraphs();

}

function clearTables() {
    $('#webAppTable').remove();
    $('#webAppTable2').remove();
    $('#webAppTable3').remove();
    $('#webAppTable4').remove();
    $('#webAppTable5').remove();
}

function drawPopupChart(parsedResponse, appName, holderId) {

    $('#lineWithFocusChart').html($('<svg style="height:450px;"></svg>
'));
    var div = document.getElementById('div-selected-app-name');
    div.innerHTML = "User Hits Of " + appName;
    $(holderId).parents('.widget').addClass('graph-maximized');
    $('.backdrop').show();
    $('.widget-head').show();
    $(holderId).hide();

    $('.btn-remove').on('click', function () {
        $('.widget-head').hide();
        $(holderId).show();
    })

    var userHitsStats = [];

    for (var x = 0; x < parsedResponse.length; x++) {
        var responsedAppName = parsedResponse[x].AppName.replace(/\s+/g, '');
        if (appName == responsedAppName) {
            var userHitsResponse = parsedResponse[x].UserHits;
            for (var y = 0; y < userHitsResponse.length; y++) {
                userHitsStats.push({
                                       "User": userHitsResponse[y].UserName,
                                       "Hits": userHitsResponse[y].Hits
                                   });
            }
        }
    }

    $('.graph-container').html('');
    $('#tableContainer').html('');
    $('#lineWithFocusChart').html('');
    var svg = dimple.newSvg(".graph-container", "100%", 500);
    chart = new dimple.chart(svg, userHitsStats);

    chart.setBounds("10%", "10%", "75%", "60%");
    x = chart.addCategoryAxis("x", "User");

    y = chart.addMeasureAxis("y", "Hits");
    y.title = "User Hits Count";
    x.title = "User Id";
    y.tickFormat = '1d';

    s = chart.addSeries("User", dimple.plot.bar);
    var div = d3.select("body").append("div").attr("class", "toolTip");

    var filterValues = dimple.getUniqueValues(userHitsStats, "User");
    var state_array = [];
    var defaultFilterValues = [];
    var sortData = [];
    var chartData = [];

    var $dataTable = $('

');

    $dataTable.append($('

' +
                        '	' +
                        'User	' +
                        'User Hits Count	' +
                        '

'));

    sortData = dimple.filterData(userHitsStats, "User", filterValues);
    sortData.sort(function (obj1, obj2) {
        return obj2.Hits - obj1.Hits;
    });

    for (var n = 0; n < sortData.length; n++) {

        if (n < 20) {
            $dataTable.append($('
'
                                    + '<input name="item_checkbox' + n + '"  checked   id=' + n +
                                '  type="checkbox"  data-item=' + sortData[n].User + ' class="inputCheckbox"/>'
                                    + '	'
                                    + '' + sortData[n].User + ' 	'
                                    + '' + sortData[n].Hits + '	'
                                    + '
'));
            state_array.push(true);
            defaultFilterValues.push(sortData[n].User);
            chartData.push(sortData[n].User);
        } else {
            $dataTable.append($('
'
                                    + '<input name="item_checkbox' + n + '"  id=' + n + '  type="checkbox"  data-item=' + sortData[n].User + ' class="inputCheckbox"/>'
                                    + '	'
                                    + '' + sortData[n].User + ' 	'
                                    + '' + sortData[n].Hits + '	'
                                    + '
'));
            state_array.push(false);
            chartData.push(sortData[n].App);
        }
    }

    $('#tableContainer').append($dataTable);
    $('#tableContainer').show();

    var table = $('#apiSelectTable').DataTable({
                                                   retrieve: true,
                                                   "order": [
                                                       [ 2, "desc" ]
                                                   ],
                                                   "fnDrawCallback": function () {
                                                       if (this.fnSettings().fnRecordsDisplay() <= $("#apiSelectTable_length option:selected").val()
                                                           || $("#apiSelectTable_length option:selected").val() == -1)
                                                           $('#apiSelectTable_paginate').hide();
                                                       else
                                                           $('#apiSelectTable_paginate').show();
                                                   },
                                                   "aoColumns": [
                                                       { "bSortable": false },
                                                       null,
                                                       null
                                                   ]

                                               });

    $('.details-control').removeClass('sorting');

    // Array to track the ids of the details displayed rows
    var detailRows = [];
    chart.data = dimple.filterData(userHitsStats, "User", defaultFilterValues);
    var count = 20;
    $('.details-control').removeClass('sorting');

    // Array to track the ids of the details displayed rows
    var detailRows = [];

    $('#apiSelectTable tbody').on('click', 'tr td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);
        if (row.child.isShown()) {
            // This row is already open - close it
            $('div.slider', row.child()).slideUp(function () {
                row.child.hide();
                tr.removeClass('shown');
            });
        } else {
            row.child(format(row.data()), 'no-padding').show();
            tr.addClass('shown');
            $('div.slider', row.child()).slideDown();
        }
    });

    $('select').css('width', '60px');

    var count = 20;

    //on checkbox check and uncheck event
    $('#apiSelectTable').on('change', 'input.inputCheckbox', function () {
        var id = $(this).attr('id');
        var check = $(this).is(':checked');
        var draw_chart = [];

        if (check) {
            $('#displayMsg').html('');
            count++;
            //limiting to show 20 entries at a time
            if (count > 20) {
                $('#displayMsg').html('
Please Note that the graph will be showing only 20 entries
');
                state_array[id] = false;
                $(this).prop("checked", "");
                count--;
            } else {
                state_array[id] = true;
            }
        } else {
            $('#displayMsg').html('');
            state_array[id] = false;
            count--;
        }

        $.each(chartData, function (index, value) {
            if (state_array[index]) {
                draw_chart.push(value);
            }
        });

        chart.data = dimple.filterData(userHitsStats, "User", draw_chart);
        chart.draw();
    });

    s.afterDraw = function (shp, d) {
        var shape = d3.select(shp);
        var circle = d3.selectAll("circle");

        circle.on("mouseout", function (d) {
            div.style("display", "none");
        });
    };
    chart.draw();
    window.onresize = function () {
        chart.draw(0, true);
    };
}
<commit_msg>variable 'parsedResponse' renamed to 'ajaxResponse' and reduced its scope to function-local as per https://github.com/wso2/carbon-appmgt/pull/146/files#r51833883 discussion<commit_after>$(function () {
    drawGraphs();
});

function drawGraphs() {
    var url = window.location.pathname;
    var comps = url.split('/');
    var type = comps[comps.length - 2];
    var operation = comps[comps.length - 3];
    var action = 'getAppsPopularity';
    var dateRange = $('#date-range').val();

    var from = dateRange.split('to')[0].trim() + ":00";
    var to = dateRange.split('to')[1].trim() + ":00";
    var ajaxResponse;

    $.ajax({
               async: false,
               url: caramel.context + '/api/assets/' + operation + '/' + type + '/' + action + '/',
               type: 'POST',
               data: {
                   'startDate': from,
                   'endDate': to
               },
               success: function (response) {
                   drawPopularityOverTime(response);
                   $('#spinner').hide();
                   ajaxResponse = response;
               },
               error: function (response) {
                   alert('Error occurred at statistics graph rendering');
               }
           });

    $('.btn-remove').on('click', function () {
        $(this).parents('.graph-maximized').removeClass('graph-maximized');
        $('.backdrop').hide();
        drawPopularityOverTime(ajaxResponse);
    });

}

var drawPopularityOverTime = function (parsedResponse) {
    var data = [];
    var length = parsedResponse.length;

    var dataStructure = [];
    var app = '';
    var hitCount = 0;
    $("#tooltipTable").find("tr:gt(0)").remove();
    for (var p = 0; p < parsedResponse.length; p++) {
        var appName = parsedResponse[p].AppName.replace(/\s+/g, '');
        data.push({
                      App: appName,
                      Hits: parsedResponse[p].TotalHits
                  });
    }

    $('.graph-container').html('');
    $('#tableContainer').html('');
    var svg = dimple.newSvg(".graph-container", "100%", 500);
    chart = new dimple.chart(svg, data);

    chart.setBounds("10%", "10%", "75%", "60%");
    x = chart.addCategoryAxis("x", "App");

    y = chart.addMeasureAxis("y", "Hits");
    y.title = "Hit Count";
    var data = [];
    var length = parsedResponse.length;

    var dataStructure = [];
    var app = '';
    var hitCount = 0;
    $("#tooltipTable").find("tr:gt(0)").remove();
    for (var p = 0; p < parsedResponse.length; p++) {
        var appName = parsedResponse[p].AppName.replace(/\s+/g, '');
        data.push({
                      App: appName,
                      Hits: parsedResponse[p].TotalHits
                  });
    }

    $('.graph-container').html('');
    $('#tableContainer').html('');
    var svg = dimple.newSvg(".graph-container", "100%", 500);
    chart = new dimple.chart(svg, data);

    chart.setBounds("10%", "10%", "75%", "60%");
    x = chart.addCategoryAxis("x", "App");
    y = chart.addMeasureAxis("y", "Hits");
    chart.addButtonName
    y.title = "Hit Count";
    x.title = "Apps";
    y.tickFormat = '1d';

    s = chart.addSeries("App", dimple.plot.bar);
    var div = d3.select("body").append("div").attr("class", "toolTip");

    var filterValues = dimple.getUniqueValues(data, "App");
    var state_array = [];
    var defaultFilterValues = [];
    var sortData = [];
    var chartData = [];

    var $dataTable = $('

');
    $dataTable.append($('

' +
                        '	' +
                        'App Name	' +
                        'Hits Count	'+
                        '

'));

    sortData = dimple.filterData(data, "App", filterValues);
    sortData.sort(function (obj1, obj2) {
        return obj2.Hits - obj1.Hits;
    });

    for (var n = 0; n < sortData.length; n++) {
        if (n < 20) {
            $dataTable.append($('
'
                                    + '<input name="item_checkbox' + n + '"  checked   id=' + n +
                                '  type="checkbox"  data-item=' + sortData[n].App  + ' class="inputCheckbox"/>'
                                    + '	'
                                    + '' + sortData[n].App +' 	'
                                    +''+sortData[n].Hits +'	'
                                    +'
'));
            state_array.push(true);
            defaultFilterValues.push(sortData[n].App);
            chartData.push(sortData[n].App);
        } else {
            $dataTable.append($('
'
                                    +'<input name="item_checkbox'+n+'"  id='+n+'  type="checkbox"  data-item='+sortData[n].App +' class="inputCheckbox"/>'
                                    +'	'
                                    +''+sortData[n].App +' 	'
                                    +''+sortData[n].Hits +'	'
                                    +'
'));
            state_array.push(false);
            chartData.push(sortData[n].App);
        }
    }

    if (parsedResponse.length == 0) {
        $('.graph-container').html('
No data available
');
    } else {
        $('.graph-container').show();
        $('#tableContainer').append($dataTable);
        $('#tableContainer').show();
        var table= $('#apiSelectTable').DataTable({
                                                      retrieve: true,
                                                      "order": [
                                                          [ 1, "desc" ]
                                                      ],
                                                      "fnDrawCallback": function(){
                                                          if(this.fnSettings().fnRecordsDisplay()<=$("#apiSelectTable_length option:selected" ).val()
                                                              || $("#apiSelectTable_length option:selected" ).val()==-1)
                                                              $('#apiSelectTable_paginate').hide();
                                                          else
                                                              $('#apiSelectTable_paginate').show();
                                                      },
                                                      "aoColumns": [
                                                          { "bSortable": false },
                                                          null,
                                                          null
                                                      ]
                                                  });

        $('.details-control').removeClass('sorting');
        var detailRows = [];
        $('#apiSelectTable tbody').on( 'click', 'tr td.details-control', function () {
            var tr = $(this).closest('tr');
            var row = table.row( tr );
            if ( row.child.isShown() ) {
                $('div.slider', row.child()).slideUp( function () {
                    row.child.hide();
                    tr.removeClass('shown');
                } );
            }
            else {
                row.child( format(row.data()), 'no-padding' ).show();
                tr.addClass('shown');
                $('div.slider', row.child()).slideDown();
            }
        } );

        $('select').css('width','60px');
        chart.data = dimple.filterData(data, "App", defaultFilterValues);
        var count = 20;
        $('#apiSelectTable').on( 'change', 'input.inputCheckbox', function () {
            var id =  $(this).attr('id');
            var check=$(this).is(':checked');
            var draw_chart=[];

            if (check) {
                $('#displayMsg').html('');
                count++;
                //limiting to show 20 entries at a time
                if(count>20){
                    $('#displayMsg').html('
Please Note that the graph will be showing only 20 entries
');
                    state_array[id] = false;
                    $(this).prop("checked", "");
                    count--;
                }else{
                    state_array[id] = true;
                }
            } else {
                $('#displayMsg').html('');
                state_array[id] = false;
                count--;
            }

            $.each(chartData, function (index, value) {
                if (state_array[index]){
                    draw_chart.push(value);
                }
            });

            chart.data = dimple.filterData(data, "App", draw_chart);
            chart.draw();
        });

        s.afterDraw = function (shp, d) {
            var shape = d3.select(shp);
            var bar = d3.selectAll("rect");
            bar.on("click", function (d) {
                drawPopupChart(parsedResponse, d.aggField, this);
            });
            bar.on("mouseout", function (d) {
                div.style("display", "none");
            });
        };
        chart.draw();
        window.onresize = function () {
            chart.draw(0, true);
        };
    }
}

var onDateSelected = function () {
    clearTables();
    drawGraphs();

}

function clearTables() {
    $('#webAppTable').remove();
    $('#webAppTable2').remove();
    $('#webAppTable3').remove();
    $('#webAppTable4').remove();
    $('#webAppTable5').remove();
}

function drawPopupChart(parsedResponse, appName, holderId) {

    $('#lineWithFocusChart').html($('<svg style="height:450px;"></svg>
'));
    var div = document.getElementById('div-selected-app-name');
    div.innerHTML = "User Hits Of " + appName;
    $(holderId).parents('.widget').addClass('graph-maximized');
    $('.backdrop').show();
    $('.widget-head').show();
    $(holderId).hide();

    $('.btn-remove').on('click', function () {
        $('.widget-head').hide();
        $(holderId).show();
    })

    var userHitsStats = [];

    for (var x = 0; x < parsedResponse.length; x++) {
        var responsedAppName = parsedResponse[x].AppName.replace(/\s+/g, '');
        if (appName == responsedAppName) {
            var userHitsResponse = parsedResponse[x].UserHits;
            for (var y = 0; y < userHitsResponse.length; y++) {
                userHitsStats.push({
                                       "User": userHitsResponse[y].UserName,
                                       "Hits": userHitsResponse[y].Hits
                                   });
            }
        }
    }

    $('.graph-container').html('');
    $('#tableContainer').html('');
    $('#lineWithFocusChart').html('');
    var svg = dimple.newSvg(".graph-container", "100%", 500);
    chart = new dimple.chart(svg, userHitsStats);

    chart.setBounds("10%", "10%", "75%", "60%");
    x = chart.addCategoryAxis("x", "User");

    y = chart.addMeasureAxis("y", "Hits");
    y.title = "User Hits Count";
    x.title = "User Id";
    y.tickFormat = '1d';

    s = chart.addSeries("User", dimple.plot.bar);
    var div = d3.select("body").append("div").attr("class", "toolTip");

    var filterValues = dimple.getUniqueValues(userHitsStats, "User");
    var state_array = [];
    var defaultFilterValues = [];
    var sortData = [];
    var chartData = [];

    var $dataTable = $('

');

    $dataTable.append($('

' +
                        '	' +
                        'User	' +
                        'User Hits Count	' +
                        '

'));

    sortData = dimple.filterData(userHitsStats, "User", filterValues);
    sortData.sort(function (obj1, obj2) {
        return obj2.Hits - obj1.Hits;
    });

    for (var n = 0; n < sortData.length; n++) {

        if (n < 20) {
            $dataTable.append($('
'
                                    + '<input name="item_checkbox' + n + '"  checked   id=' + n +
                                '  type="checkbox"  data-item=' + sortData[n].User + ' class="inputCheckbox"/>'
                                    + '	'
                                    + '' + sortData[n].User + ' 	'
                                    + '' + sortData[n].Hits + '	'
                                    + '
'));
            state_array.push(true);
            defaultFilterValues.push(sortData[n].User);
            chartData.push(sortData[n].User);
        } else {
            $dataTable.append($('
'
                                    + '<input name="item_checkbox' + n + '"  id=' + n + '  type="checkbox"  data-item=' + sortData[n].User + ' class="inputCheckbox"/>'
                                    + '	'
                                    + '' + sortData[n].User + ' 	'
                                    + '' + sortData[n].Hits + '	'
                                    + '
'));
            state_array.push(false);
            chartData.push(sortData[n].App);
        }
    }

    $('#tableContainer').append($dataTable);
    $('#tableContainer').show();

    var table = $('#apiSelectTable').DataTable({
                                                   retrieve: true,
                                                   "order": [
                                                       [ 2, "desc" ]
                                                   ],
                                                   "fnDrawCallback": function () {
                                                       if (this.fnSettings().fnRecordsDisplay() <= $("#apiSelectTable_length option:selected").val()
                                                           || $("#apiSelectTable_length option:selected").val() == -1)
                                                           $('#apiSelectTable_paginate').hide();
                                                       else
                                                           $('#apiSelectTable_paginate').show();
                                                   },
                                                   "aoColumns": [
                                                       { "bSortable": false },
                                                       null,
                                                       null
                                                   ]

                                               });

    $('.details-control').removeClass('sorting');

    // Array to track the ids of the details displayed rows
    var detailRows = [];
    chart.data = dimple.filterData(userHitsStats, "User", defaultFilterValues);
    var count = 20;
    $('.details-control').removeClass('sorting');

    // Array to track the ids of the details displayed rows
    var detailRows = [];

    $('#apiSelectTable tbody').on('click', 'tr td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);
        if (row.child.isShown()) {
            // This row is already open - close it
            $('div.slider', row.child()).slideUp(function () {
                row.child.hide();
                tr.removeClass('shown');
            });
        } else {
            row.child(format(row.data()), 'no-padding').show();
            tr.addClass('shown');
            $('div.slider', row.child()).slideDown();
        }
    });

    $('select').css('width', '60px');

    var count = 20;

    //on checkbox check and uncheck event
    $('#apiSelectTable').on('change', 'input.inputCheckbox', function () {
        var id = $(this).attr('id');
        var check = $(this).is(':checked');
        var draw_chart = [];

        if (check) {
            $('#displayMsg').html('');
            count++;
            //limiting to show 20 entries at a time
            if (count > 20) {
                $('#displayMsg').html('
Please Note that the graph will be showing only 20 entries
');
                state_array[id] = false;
                $(this).prop("checked", "");
                count--;
            } else {
                state_array[id] = true;
            }
        } else {
            $('#displayMsg').html('');
            state_array[id] = false;
            count--;
        }

        $.each(chartData, function (index, value) {
            if (state_array[index]) {
                draw_chart.push(value);
            }
        });

        chart.data = dimple.filterData(userHitsStats, "User", draw_chart);
        chart.draw();
    });

    s.afterDraw = function (shp, d) {
        var shape = d3.select(shp);
        var circle = d3.selectAll("circle");

        circle.on("mouseout", function (d) {
            div.style("display", "none");
        });
    };
    chart.draw();
    window.onresize = function () {
        chart.draw(0, true);
    };
}
<|endoftext|>


<commit_before>Ext.define('devilry_subjectadmin.view.passedpreviousperiod.PassedPreviousPeriodOverview' ,{
    extend: 'Ext.panel.Panel',
    alias: 'widget.passedpreviousperiodoverview',
    cls: 'devilry_subjectadmin_passedpreviousperiodoverview',
    requires: [
        'devilry_subjectadmin.view.passedpreviousperiod.SelectGroupsGrid',
        'devilry_subjectadmin.view.passedpreviousperiod.ConfirmGroupsGrid',
        'devilry_extjsextras.PrimaryButton',
        'devilry_extjsextras.AlertMessage'
    ],

    /**
     * @cfg {String} assignment_id (required)
     */

    initComponent: function() {
        Ext.apply(this, {
            bodyPadding: '20 40 20 40',
            layout: 'border',
            border: false,

            items: [{
                xtype: 'box',
                region: 'north',
                height: 70,
                cls: 'bootstrap',
                html: [
                    '
',
                        gettext('Passed previously'),
                    '
'
                    ].join('')
            }, {
                xtype: 'container',
                region: 'center',
                layout: 'card',
                itemId: 'cardContainer',
                items: [{
                    xtype: 'container',
                    itemId: 'pageOne',
                    layout: 'border',
                    items: [{
                        xtype: 'selectpassedpreviousgroupsgrid',
                        region: 'center',

                        fbar: [{
                            xtype: 'checkbox',
                            boxLabel: gettext('Show groups that Devilry believes should not be marked as previously passed?'),
                            itemId: 'showUnRecommendedCheckbox',
                            cls: 'showUnRecommendedCheckbox'
                        }, '->', {
                            xtype: 'button',
                            scale: 'large',
                            text: gettext('Next'),
                            disabled: true,
                            itemId: 'nextButton'
                        }]
                    }, {
                        xtype: 'box',
                        region: 'west',
                        width: 300,
                        cls: 'bootstrap',
                        padding: '0 30 0 0',
                        html: [
                            '
',
                                interpolate(gettext('Select one or more groups. Groups that we belive have passed this assignment before has been selected automatically, and they are marked with the name of the old %(period_term)s.'), {
                                        period_term: gettext('period')
                                    }, true),
                            '
',
                            '
',
                                gettext('The search for previously passed students match the short name of old assignments against the short name of this assignment. Only groups with exactly one student in both the old and the current assignment is matched. You can find the short name of an assignment by looking at the breadcrumb in the header, or in the title of the Rename-section of "Dangerous actions" when visiting the assignment.'),
                            '
'
                        ].join('')
                    }]
                }, {
                    xtype: 'container',
                    itemId: 'pageTwo',
                    layout: 'border',
                    items: [{
                        xtype: 'box',
                        region: 'west',
                        width: 300,
                        cls: 'bootstrap',
                        padding: '0 30 0 0',
                        html: [
                            '
',
                                gettext('Make sure you really want to mark these groups as previously passed before saving.'),
                            '
',
                            '
',
                                gettext('This will create a new delivery on each of the groups, mark the delivery as a placeholder for a previously approved delivery, and create a feedback with passing grade on the delivery.'),
                            '
'
                        ].join('')
                    }, {
                        xtype: 'confirmpassedpreviousgroupsgrid',
                        region: 'center',
                        fbar: [{
                            xtype: 'button',
                            text: gettext('Back'),
                            itemId: 'backButton'
                        }, '->', {
                            xtype: 'primarybutton',
                            text: gettext('Save'),
                            itemId: 'saveButton'
                        }]
                    }]
                }, {
                    itemId: 'unsupportedGradeEditor',
                    xtype: 'alertmessage',
                    type: 'error',
                    title: 'Unsupported grading system',
                    message: 'The passed previously functionality only supports the Approved/not approved grading system. We will fix this before the version you are testing is released.'
                }]
            }]
        });
        this.callParent(arguments);
    }
});
<commit_msg>subjectadmin...passedpreviousperiod: Layout.<commit_after>Ext.define('devilry_subjectadmin.view.passedpreviousperiod.PassedPreviousPeriodOverview' ,{
    extend: 'Ext.container.Container',
    alias: 'widget.passedpreviousperiodoverview',
    cls: 'devilry_subjectadmin_passedpreviousperiodoverview',
    requires: [
        'devilry_subjectadmin.view.passedpreviousperiod.SelectGroupsGrid',
        'devilry_subjectadmin.view.passedpreviousperiod.ConfirmGroupsGrid',
        'devilry_extjsextras.PrimaryButton',
        'devilry_extjsextras.AlertMessage'
    ],

    /**
     * @cfg {String} assignment_id (required)
     */

    // Internal attribute used for the width of the west-panel on all pages
    sideBarWidth: 250,

    initComponent: function() {
        Ext.apply(this, {
            padding: '20 40 20 40',
            layout: 'border',
            style: 'background: transparent !important;',

            items: [{
                xtype: 'box',
                region: 'north',
                height: 55,
                cls: 'bootstrap',
                html: [
                    '
',
                        gettext('Passed previously'),
                    '
'
                    ].join('')
            }, {
                xtype: 'container',
                region: 'center',
                layout: 'card',
                itemId: 'cardContainer',
                items: [{
                    xtype: 'container',
                    itemId: 'pageOne',
                    layout: 'border',
                    style: 'background: transparent !important;',
                    items: [{
                        xtype: 'selectpassedpreviousgroupsgrid',
                        region: 'center',
                        fbar: [{
                            xtype: 'checkbox',
                            boxLabel: gettext('Show groups that Devilry believes should not be marked as previously passed?'),
                            itemId: 'showUnRecommendedCheckbox',
                            cls: 'showUnRecommendedCheckbox'
                        }, '->', {
                            xtype: 'button',
                            scale: 'large',
                            text: gettext('Next'),
                            disabled: true,
                            itemId: 'nextButton'
                        }]
                    }, {
                        xtype: 'box',
                        region: 'west',
                        width: this.sideBarWidth,
                        cls: 'bootstrap',
                        padding: '0 30 0 0',
                        html: [
                            '
',
                                interpolate(gettext('Select one or more groups. Groups that we belive have passed this assignment before has been selected automatically, and they are marked with the name of the old %(period_term)s.'), {
                                        period_term: gettext('period')
                                    }, true),
                            '
',
                            '
',
                                gettext('The search for previously passed students match the short name of old assignments against the short name of this assignment. Only groups with exactly one student in both the old and the current assignment is matched. You can find the short name of an assignment by looking at the breadcrumb in the header, or in the title of the Rename-section of "Dangerous actions" when visiting the assignment.'),
                            '
'
                        ].join('')
                    }]
                }, {
                    xtype: 'container',
                    itemId: 'pageTwo',
                    style: 'background: transparent !important;',
                    layout: 'border',
                    items: [{
                        xtype: 'box',
                        region: 'west',
                        width: this.sideBarWidth,
                        cls: 'bootstrap',
                        padding: '0 30 0 0',
                        html: [
                            '
',
                                gettext('Make sure you really want to mark these groups as previously passed before saving.'),
                            '
',
                            '
',
                                gettext('This will create a new delivery on each of the groups, mark the delivery as a placeholder for a previously approved delivery, and create a feedback with passing grade on the delivery.'),
                            '
'
                        ].join('')
                    }, {
                        xtype: 'confirmpassedpreviousgroupsgrid',
                        region: 'center',
                        fbar: [{
                            xtype: 'button',
                            text: gettext('Back'),
                            itemId: 'backButton'
                        }, '->', {
                            xtype: 'primarybutton',
                            text: gettext('Save'),
                            itemId: 'saveButton'
                        }]
                    }]
                }, {
                    itemId: 'unsupportedGradeEditor',
                    xtype: 'alertmessage',
                    type: 'error',
                    title: 'Unsupported grading system',
                    message: 'The passed previously functionality only supports the Approved/not approved grading system. We will fix this before the version you are testing is released.'
                }]
            }]
        });
        this.callParent(arguments);
    }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import module from '../helpers/module-for-db';
import { test } from '../helpers/qunit';

const {
  run,
  RSVP: { allSettled }
} = Ember;

module('paginated-loader', {
  async beforeEach() {
    this.owner = Ember.Object.create({ id: null });
    this.opts = {
      owner: [ 'id' ],
      query(owner) {
        let id = owner.get('id');
        return { id };
      }
    };
    this.loader = () => this.db._createInternalPaginatedLoader(this.owner, this.opts).model(true);
    this.settle = loader => allSettled(loader._internal.operations.map(op => op.promise));
  }
});

test('it exists', function(assert) {
  this.opts.autoload = false;

  let loader = this.loader();
  assert.ok(loader);

  console.log(loader);

  // run(() => loader.destroy());
});
<commit_msg>cleanup<commit_after>import Ember from 'ember';
import module from '../helpers/module-for-db';
import { test } from '../helpers/qunit';

const {
  run,
  RSVP: { allSettled }
} = Ember;

module('paginated-loader', {
  async beforeEach() {
    this.owner = Ember.Object.create({ id: null });
    this.opts = {
      owner: [ 'id' ],
      query(owner) {
        let id = owner.get('id');
        return { id };
      }
    };
    this.loader = () => this.db._createInternalPaginatedLoader(this.owner, this.opts).model(true);
    this.settle = loader => allSettled(loader._internal.operations.map(op => op.promise));
  }
});

test('it exists', function(assert) {
  this.opts.autoload = false;

  let loader = this.loader();
  assert.ok(loader);

  run(() => loader.destroy());
});
<|endoftext|>


<commit_before>module.exports = {
    run : function(creep){
        var myflag = Game.flags[creep.memory.myflag];
        if(myflag == undefined){
            myflag = Game.flags['Raid'];
        }
        var damaged = _.sortBy(creep.pos.findInRange(FIND_MY_CREEPS,1,{filter: (c) => c.hits < c.hitsMax}),'hits');
        if(damaged.length){
            creep.heal(damaged[0]);
        }
        else{
            var damagedAtRange = _.sortBy(creep.pos.findInRange(FIND_MY_CREEPS,3,{filter: (c) => c.hits < c.hitsMax}),'hits');
            if(damagedAtRange.length){
                creep.rangedHeal(damagedAtRange[0]);
            }
        }
        if(creep.room.name==myflag.pos.roomName){
            var closestRaider = creep.pos.findClosestByRange(FIND_MY_CREEPS,{filter: (c) => c.memory.role == 'raider'});
            if(closestRaider != undefined){
                creep.moveTo(closestRaider,{reusePath:0});
            }
            else{
                creep.moveTo(myflag,{reusePath:0});
            }
        }
        else{
                creep.moveTo(myflag);
            }
        }
    }
}
<commit_msg>minor fix<commit_after>module.exports = {
    run : function(creep){
        var myflag = Game.flags[creep.memory.myflag];
        if(myflag == undefined){
            myflag = Game.flags['Raid'];
        }
        var damaged = _.sortBy(creep.pos.findInRange(FIND_MY_CREEPS,1,{filter: (c) => c.hits < c.hitsMax}),'hits');
        if(damaged.length){
            creep.heal(damaged[0]);
        }
        else{
            var damagedAtRange = _.sortBy(creep.pos.findInRange(FIND_MY_CREEPS,3,{filter: (c) => c.hits < c.hitsMax}),'hits');
            if(damagedAtRange.length){
                creep.rangedHeal(damagedAtRange[0]);
            }
        }
        if(creep.room.name==myflag.pos.roomName){
            var closestRaider = creep.pos.findClosestByRange(FIND_MY_CREEPS,{filter: (c) => c.memory.role == 'raider'});
            if(closestRaider != undefined){
                creep.moveTo(closestRaider,{reusePath:0});
            }
            else{
                creep.moveTo(myflag,{reusePath:0});
            }
        }
        else{
            creep.moveTo(myflag);
        }
    }
}
<|endoftext|>


<commit_before>"use strict";

var Formatter = require("./Formatter.js"),
    moment = require("moment"),
    Util = require("./Util.js");

var formatter;
var template = require("../../html/chat_message.handlebars");

module.exports = function (data, input, roomList, activityObserver, dataHandler) {
    formatter = formatter || new Formatter(roomList);

    var id = data.messageId;
    var room = data.roomId;
    var text = data.messageText;
    var starred = data.starred;

    var node = Util.html2node(template(data));

    if (data.user.id === user.id) {
        node.classList.add("chat-message-me");
    }

    formatter.formatMessage(room, node.querySelector(".chat-message-text"), text, data.reply, data.user);

    node.querySelector("time").textContent = moment.unix(data.time).fromNow();
    node.querySelector("time").setAttribute("title", moment.unix(data.time).format("LLL"));
    node.querySelector("time").parentNode.href = "/messages/" + id + "#" + id;

    node.querySelector(".chat-message-stars").addEventListener("click", function () {
        starred = !starred;

        var event = starred ? "star" : "unstar";
        this.setAttribute("data-starred", starred ? "1" : "0");

        dataHandler.send(event, {
            messageId: id
        });
    });

    node.querySelector(".chat-message-reply").addEventListener("click", function () {
        input.replyTo(id);
    });

    if (data.user.id === user.id) {
        node.addEventListener("longpress", function () {
            input.edit(data.messageId);
        });
    }

    node.addEventListener("mouseenter", function () {
        var nodes = document.querySelectorAll(".chat-message[data-reply='" + id + "']");

        nodes.forEach(function (node) {
            node.classList.add("reply");
        });

        if (data.reply) {
            var message = roomList.getCurrent().getMessageList().get(data.reply.messageId);

            if (message) {
                message.getNode().classList.add("reply");
            }
        }
    });

    node.addEventListener("mouseleave", function () {
        var nodes = document.querySelectorAll(".reply");

        nodes.forEach(function (node) {
            node.classList.remove("reply");
        });
    });

    if (window.isTouchDevice()) {
        node.classList.add("unselectable");
    }

    return {
        getId: function () {
            return id;
        },

        getRoom: function () {
            return room;
        },

        getText: function () {
            return text;
        },

        getAuthorId: function () {
            return data.user.id;
        },

        getTime: function () {
            return data.time;
        },

        getNode: function () {
            return node;
        },

        setText: function (value) {
            formatter.formatMessage(room, node.querySelector(".chat-message-text"), value, data.reply, data.user);
            text = value;
        },

        setStars: function (value) {
            var starNode = node.querySelector(".chat-message-stars");
            starNode.setAttribute("data-stars", value);
        },

        setStarred: function (value) {
            var starNode = node.querySelector(".chat-message-stars");
            starNode.setAttribute("data-starred", value ? "1" : "0");
            starred = value;
        },

        highlight: function () {
            var pos = node.offsetTop;
            var height = node.clientHeight;

            if (pos < node.parentNode.scrollTop) {
                node.parentNode.scrollTop = pos;
            }

            else if (pos + height > node.parentNode.scrollTop + node.parentNode.clientHeight) {
                node.parentNode.scrollTop = pos + height - node.parentNode.clientHeight;
            }

            // TODO: use css class

            node.style.backgroundColor = "#b33636";

            setTimeout(function () {
                node.style.backgroundColor = "";
            }, 1000);
        }
    }
};
<commit_msg>Change message highlight color<commit_after>"use strict";

var Formatter = require("./Formatter.js"),
    moment = require("moment"),
    Util = require("./Util.js");

var formatter;
var template = require("../../html/chat_message.handlebars");

module.exports = function (data, input, roomList, activityObserver, dataHandler) {
    formatter = formatter || new Formatter(roomList);

    var id = data.messageId;
    var room = data.roomId;
    var text = data.messageText;
    var starred = data.starred;

    var node = Util.html2node(template(data));

    if (data.user.id === user.id) {
        node.classList.add("chat-message-me");
    }

    formatter.formatMessage(room, node.querySelector(".chat-message-text"), text, data.reply, data.user);

    node.querySelector("time").textContent = moment.unix(data.time).fromNow();
    node.querySelector("time").setAttribute("title", moment.unix(data.time).format("LLL"));
    node.querySelector("time").parentNode.href = "/messages/" + id + "#" + id;

    node.querySelector(".chat-message-stars").addEventListener("click", function () {
        starred = !starred;

        var event = starred ? "star" : "unstar";
        this.setAttribute("data-starred", starred ? "1" : "0");

        dataHandler.send(event, {
            messageId: id
        });
    });

    node.querySelector(".chat-message-reply").addEventListener("click", function () {
        input.replyTo(id);
    });

    if (data.user.id === user.id) {
        node.addEventListener("longpress", function () {
            input.edit(data.messageId);
        });
    }

    node.addEventListener("mouseenter", function () {
        var nodes = document.querySelectorAll(".chat-message[data-reply='" + id + "']");

        nodes.forEach(function (node) {
            node.classList.add("reply");
        });

        if (data.reply) {
            var message = roomList.getCurrent().getMessageList().get(data.reply.messageId);

            if (message) {
                message.getNode().classList.add("reply");
            }
        }
    });

    node.addEventListener("mouseleave", function () {
        var nodes = document.querySelectorAll(".reply");

        nodes.forEach(function (node) {
            node.classList.remove("reply");
        });
    });

    if (window.isTouchDevice()) {
        node.classList.add("unselectable");
    }

    return {
        getId: function () {
            return id;
        },

        getRoom: function () {
            return room;
        },

        getText: function () {
            return text;
        },

        getAuthorId: function () {
            return data.user.id;
        },

        getTime: function () {
            return data.time;
        },

        getNode: function () {
            return node;
        },

        setText: function (value) {
            formatter.formatMessage(room, node.querySelector(".chat-message-text"), value, data.reply, data.user);
            text = value;
        },

        setStars: function (value) {
            var starNode = node.querySelector(".chat-message-stars");
            starNode.setAttribute("data-stars", value);
        },

        setStarred: function (value) {
            var starNode = node.querySelector(".chat-message-stars");
            starNode.setAttribute("data-starred", value ? "1" : "0");
            starred = value;
        },

        highlight: function () {
            var pos = node.offsetTop;
            var height = node.clientHeight;

            if (pos < node.parentNode.scrollTop) {
                node.parentNode.scrollTop = pos;
            }

            else if (pos + height > node.parentNode.scrollTop + node.parentNode.clientHeight) {
                node.parentNode.scrollTop = pos + height - node.parentNode.clientHeight;
            }

            // TODO: use css class

            node.style.backgroundColor = "#ff9";

            setTimeout(function () {
                node.style.backgroundColor = "";
            }, 1000);
        }
    }
};
<|endoftext|>


<commit_before>var fs = require('fs-extra'),
    _ = require('underscore'),
    templates = require('./templates'),
    path = require('path'),
    zlib = require('zlib');

/**
*
* Module definitions
*
**/

function Repo(root_dir, storage) {
  this.root_dir = path.resolve(root_dir);
  this.storage = storage;
}

Repo.prototype.init = function(callback) {
  var self = this;

  // Try to initialize from existing /.git
  this.storage.check_directories(this.root_dir, function(err) {
    if(err) {
      // Create a new /.git and subfolders
      self.storage.create_directories(self.root_dir, function(err) {
        if(err) {
          return callback(err);
        } else {
          // Create git files
          self.storage.create_files(self.root_dir, function(err) {
            if(err) {
              return callback(err);
            } else {
              return callback();
            }
          });

        }
      });
    } else {
      return callback();
    }
  });
}

function get_blob_path(key) {
  var blob_path = key.substring(0, 2) + '/' + key.substring(2);
  return blob_path;
}

Repo.prototype.write_blob = function(blob, callback) {
  var blob_path = get_blob_path(blob.key);
  blob_path = path.resolve(this.root_dir + '/objects/' + blob_path);
  var content = zlib.deflate(blob.header + blob.content, function(err, content) {
    fs.outputFile(blob_path, blob.content, function(err) {
      if(err) {
        return callback(err);
      }

      return callback();
    });
  });
}

Repo.prototype.read_blob_from_key = function(key, callback) {
  var blob_path = get_blob_path(key);
  blob_path = path.resolve(this.root_dir + '/objects/' + blob_path);
  var content = zlib.deflate(blob.header + blob.content, function(err, content) {
    fs.outputFile(blob_path, blob.content, function(err) {
      if(err) {
        return callback(err);
      }

      return callback();
    });
  });
}

module.exports = Repo;<commit_msg>Add write_blob method and cleanup code<commit_after>var fs = require('fs-extra'),
    _ = require('underscore'),
    templates = require('./templates'),
    path = require('path'),
    Blob = require('./blob'),
    zlib = require('zlib');

/**
*
* Module definitions
*
**/

function Repo(root_dir, storage) {
  this.root_dir = path.resolve(root_dir);
  this.storage = storage;
  this.blobs = {};
}

Repo.prototype.get_root_dir = function(dir) {
  var root_dir = dir || '.';

  if(program.args.length > 0) {
    root_dir = program.args[0];
  }

  if(program.separateGitDir) {
    root_dir += '/' + program.separateGitDir;
  }

  if(!program.bare) {
    root_dir += '/.git';
  }

  return root_dir;
}

Repo.prototype.init = function(callback) {
  var self = this;

  // Try to initialize from existing /.git
  this.storage.check_directories(this.root_dir, function(err) {
    if(err) {
      // Create a new /.git and subfolders
      self.storage.create_directories(self.root_dir, function(err) {
        if(err) {
          return callback(err);
        } else {
          // Create git files
          self.storage.create_files(self.root_dir, function(err) {
            if(err) {
              return callback(err);
            } else {
              return callback();
            }
          });

        }
      });
    } else {
      return callback();
    }
  });
}

Repo.prototype.write_blob = function(options, callback) {
  var options = _.defaults(options, {
    type: 'blob',
    content: ''
  });

  var self = this;
  var blob = new Blob(options.content, options.type);
  this.blobs[blob.key] = blob;

  var blob_file = zlib.deflate(blob.header + blob.content, function(err, buffer) {
    if(err) {
      return callback(err);
    } else {
      var blob_path = self.root_dir + '/objects/' + get_blob_path(blob.key);
      fs.createFile(blob_path, function(err) {
        if(err) {
          return callback(err);
        } else {
          fs.open(blob_path, 'w', function(err, fd) {
            if(err) {
              // File already exists
              return callback(null, blob);
            } else {
              fs.write(fd, buffer, 0, buffer.length, 0, function(err, written) {
                if(err) {
                  return callback(err);
                } else {
                  return callback(null, blob);
                }
              });
            }
          });
        }
      });
    }
  });
}

function get_blob_path(key) {
  var blob_path = key.substring(0, 2) + '/' + key.substring(2);
  return blob_path;
}

function get_blob_key(path) {
  var blob_key = path.replace('/', '');
  return blob_key;
}

module.exports = Repo;<|endoftext|>