<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    console.log(viewModel.users().length);
                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        console.log(data);
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
        console.log(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

}

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData.length == 0) {
        viewModel.tempTableData = viewModel.tabledata;
    }
    else
    {
        viewModel.tabledata = viewModel.tempTableData;
    }

    var data = [];

    viewModel.tabledata().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            data.push(item);
            console.log(item);
        }
    });

    viewModel.tabledata = data;

    console.log(data);
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        console.log(viewModel.users().length);
        return viewModel.users().length;
    });
}<commit_msg>search<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    console.log(viewModel.users().length);
                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        console.log(data);
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
        console.log(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

}

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData.length == 0) {
        viewModel.tempTableData = viewModel.tabledata;
    }
    else
    {
        viewModel.tabledata = viewModel.tempTableData;
    }

    var data = [];

    viewModel.tabledata().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            data.push(item);
            console.log(item);
        }
    });

    viewModel.tabledata = ko.observableArray([]);
    viewModel.tabledata = data;
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        console.log(viewModel.users().length);
        return viewModel.users().length;
    });
}<|endoftext|>


<commit_before>const extend = require('extend');  // deep clone, not like shallow Object.assign
const config = require('./defaults');
const errors = require('./errors');
const type = require('./type');
const env = require('dotenv').config({ silent: true });

for (let key in env) {
  if (key !== key.toLowerCase()){
    env[key.toLowerCase()] = type(env[key]);
    delete env[key];
  }
}

const proc = {};
for (let key in process.env) {
  proc[key.toLowerCase()] = type(process.env[key]);
}

module.exports = (user = {}, plugins = false, app = false) => {

  // If it's a number it's the port
  if (typeof user === 'number') {
    user = { port: user };
  }

  let options = extend({}, config);

  // Load the options from the plugin array, namespaced with the plugin name
  if (plugins) {
    plugins.forEach(plugin => {
      const valuify = cb => cb instanceof Function ? cb(options) : cb;
      const obj = { [plugin.name]: valuify(plugin.options) };
      options = extend(true, {}, options, obj);
    });
  }

  extend(true, options, user);

  // Overwrite with the env variables if set
  // They are cast for numbers and booleans
  for (let key in env) {
    options[key.toLowerCase()] = env[key];
  }

  // TODO: these notifications should not be here
  if (options.secret === 'your-random-string-here') {
    throw errors.NotSoSecret();
  }

  if ((/^secret-/.test(options.secret)) && options.verbose) {
    console.log(`
      Please change the secret in your environment configuration.
      The default one is not recommended and should be changed.
      More info in https://serverjs.io/errors#defaultSecret
    `);
  }

  return new Proxy(options, {
    get: (orig, key) => {
      // It was set from .env file
      if (typeof options[key] !== 'undefined') {
        return options[key];
      }
      // It was set through other means
      return proc[key];
    }
  });
};
<commit_msg>Hopefully fixed<commit_after>const extend = require('extend');  // deep clone, not like shallow Object.assign
const config = require('./defaults');
const errors = require('./errors');
const type = require('./type');
require('dotenv').config({ silent: true });

// Get the process variables in lowercase
const proc = {};
for (let key in process.env) {
  proc[key.toLowerCase()] = type(process.env[key]);
}

module.exports = (user = {}, plugins = []) => {

  // If it's a number it's the port
  if (typeof user === 'number') {
    user = { port: user };
  }

  let options = extend({}, config);

  // Load the options from the plugin array, namespaced with the plugin name
  plugins.forEach(plugin => {
    const valuify = cb => cb instanceof Function ? cb(options) : cb;
    const obj = { [plugin.name]: valuify(plugin.options) };
    options = extend(true, {}, options, obj);
  });

  extend(true, options, user);

  // TODO: these notifications should not be here
  if (options.secret === 'your-random-string-here') {
    throw errors.NotSoSecret();
  }

  if ((/^secret-/.test(options.secret)) && options.verbose) {
    console.log(`
      Please change the secret in your environment configuration.
      The default one is not recommended and should be changed.
      More info in https://serverjs.io/errors#defaultSecret
    `);
  }

  return new Proxy(options, {
    get: (orig, key) => {

      // If it is set in the environment some other way
      if (typeof proc[key] !== 'undefined') {
        return proc[key];
      }

      // It was set in the options
      return options[key];
    }
  });
};
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    console.log(viewModel.users().length);
                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        console.log(data);
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
        console.log(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

}

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData.length == 0) {
        viewModel.tempTableData = viewModel.tabledata;
    }
    else
    {
        viewModel.tabledata = viewModel.tempTableData;
    }

    viewModel.tableData([]);
    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
        }
    });

    console.log(viewModel.tabledata.length);

}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        console.log(viewModel.users().length);
        return viewModel.users().length;
    });
}<commit_msg>search<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    console.log(viewModel.users().length);
                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        console.log(data);
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
        console.log(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

}

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData.length == 0) {
        viewModel.tempTableData = viewModel.tabledata;
    }
    else
    {
        viewModel.tabledata = viewModel.tempTableData;
    }

    viewModel.tableData([]);
    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
        }
    });

    console.log(viewModel.tabledata().length);

}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        console.log(viewModel.users().length);
        return viewModel.users().length;
    });
}<|endoftext|>


<commit_before>export default {
  // Address of news feeds in Hugo format
  feedAddress: 'https://sjtug-portal-1251836446.file.myqcloud.com/tags/mirror-news/index.xml',
  // Address of help articles
  helpAddress: 'https://sjtug-portal-1251836446.file.myqcloud.com/tags/mirror-help/index.xml',
  // All packages should be accessible at backendAddressBase + '/' + repo.name
  backendAddressBase: 'https://mirrors.sjtug.org',
  // Address of the summary of backend in sjtug/lug format
  backendSummaryAddress: 'https://mirrors.sjtug.org/lug/v1/manager/summary'
}
<commit_msg>config: update backend address<commit_after>export default {
  // Address of news feeds in Hugo format
  feedAddress: 'https://sjtug-portal-1251836446.file.myqcloud.com/tags/mirror-news/index.xml',
  // Address of help articles
  helpAddress: 'https://sjtug-portal-1251836446.file.myqcloud.com/tags/mirror-help/index.xml',
  // All packages should be accessible at backendAddressBase + '/' + repo.name
  backendAddressBase: 'https://mirrors.sjtug.sjtu.edu.cn',
  // Address of the summary of backend in sjtug/lug format
  backendSummaryAddress: 'https://mirrors.sjtug.sjtu.edu.cn/lug/v1/manager/summary'
}
<|endoftext|>


<commit_before>{
	const Color = {
		Red: "#F44336",
		Pink: "#E91E63",
		Purple: "#9C27B0",
		Deep_Purple: "#673AB7",
		Indigo: "#3F51B5",
		Blue: "#2196F3",
		Light_Blue: "#03A9F4",
		Cyan: "#00BCD4",
		Teal: "#009688",
		Green: "#4CAF50",
		Light_Green: "#8BC34A",
		Lime: "#CDDC39",
		Yellow: "#FFEB3B",
		Amber: "#FFC107",
		Orange: "#FF9800",
		Deep_Orange: "#FF5722",
		Brown: "#795548",
		Grey: "#9E9E9E",
		Blue_Grey: "#607D8B"
	};

	class Canvas {
		constructor(element) {
			this.canvas = element;
			this.canvas.width = window.innerWidth;
			this.canvas.height = window.innerHeight;
			this.context = this.canvas.getContext("2d");
			this.objects = [];
			this.events();
		}

		addObject(object) {
			this.objects.push(object);
		}

		render() {
			this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
			this.objects.forEach(object => {
				object.move(this.canvas);
				object.draw(this.context);
			});
		}

		events() {
			window.addEventListener("resize", () => {
				this.canvas.width = window.innerWidth;
				this.canvas.height = window.innerHeight;
				this.render();
			});
		}
	}

	class Circle {
		constructor(x, y, radius, fillStyle, strokeStyle) {
			this.x = x;
			this.y = y;
			this.vx = Math.random() * 5 - 2.5;
			this.vy = Math.random() * 5 - 2.5;
			this.ax = 0;
			this.ay = 0.1;
			this.radius = radius;
			this.fillStyle = fillStyle;
			this.strokeStyle = strokeStyle;
		}

		draw(context) {
			if (context) {
				context.beginPath();
				context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
				if (this.fillStyle) {
					context.fillStyle = this.fillStyle;
					context.fill();
				}
				if (this.strokeStyle) {
					context.strokeStyle = this.strokeStyle;
					context.stroke();
				}
			}
		}

		move(canvas) {
			this.x += this.vx;
			this.y += this.vy;
			this.vx += this.ax;
			this.vy += this.ay;

			if (this.vx > -0.001 && this.vx < 0.001) {
				this.vx = 0;
			}

			if (this.vy > -0.001 && this.vy < 0.001) {
				this.vy = 0;
			}

			if (this.x <= this.radius) {
				this.x = this.radius;
				this.vx = -this.vx * 0.99;
			}
			else if (this.x >= canvas.width - this.radius) {
				this.x = canvas.width - this.radius;
				this.vx = -this.vx * 0.99;
			}

			if (this.y <= this.radius) {
				this.y = this.radius;
				this.vy = -this.vy * 0.99;
			}
			else if (this.y >= canvas.height - this.radius) {
				this.y = canvas.height - this.radius;
				this.vy = -this.vy * 0.99;
			}
		}
	}

	window.addEventListener("load", () => {
		const canvas = new Canvas(document.getElementById("canvas"));

		do {
			canvas.addObject(new Circle(window.innerWidth * Math.random(), window.innerHeight * Math.random(), Math.random() * 10 + 5, randomColor()));
		} while (Math.random() > 0.1);

		canvas.render();
		animate(canvas);

		function randomColor() {
			let keys = Object.keys(Color);
			return Color[keys[Math.trunc(keys.length * Math.random())]];
		}

		function animate(canvases) {
			canvas.render();
			window.requestAnimationFrame(animate.bind(this, canvas));
		}
	});
}
<commit_msg>Update main.js<commit_after>{
	const Color = {
		Red: "#F44336",
		Pink: "#E91E63",
		Purple: "#9C27B0",
		Deep_Purple: "#673AB7",
		Indigo: "#3F51B5",
		Blue: "#2196F3",
		Light_Blue: "#03A9F4",
		Cyan: "#00BCD4",
		Teal: "#009688",
		Green: "#4CAF50",
		Light_Green: "#8BC34A",
		Lime: "#CDDC39",
		Yellow: "#FFEB3B",
		Amber: "#FFC107",
		Orange: "#FF9800",
		Deep_Orange: "#FF5722",
		Brown: "#795548",
		Grey: "#9E9E9E",
		Blue_Grey: "#607D8B"
	};

	class Canvas {
		constructor(element) {
			this.canvas = element;
			this.canvas.width = window.innerWidth;
			this.canvas.height = window.innerHeight;
			this.context = this.canvas.getContext("2d");
			this.objects = [];
			this.events();
		}

		addObject(object) {
			this.objects.push(object);
		}

		render() {
			this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
			this.objects.forEach(object => {
				object.move(this.canvas);
				object.draw(this.context);
			});
		}

		events() {
			window.addEventListener("resize", () => {
				this.canvas.width = window.innerWidth;
				this.canvas.height = window.innerHeight;
				this.render();
			});
		}
	}

	class Circle {
		constructor() {
			this.x = window.innerWidth * Math.random();
			this.y = window.innerHeight * Math.random();
			this.vx = Math.random() * 5 - 2.5;
			this.vy = Math.random() * 5 - 2.5;
			this.ax = 0;
			this.ay = 0.1;
			this.radius = Math.random() * 10 + 5;
			this.fillStyle = randomColor();
			this.strokeStyle = undefined;
		}

		draw(context) {
			if (context) {
				context.beginPath();
				context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
				if (this.fillStyle) {
					context.fillStyle = this.fillStyle;
					context.fill();
				}
				if (this.strokeStyle) {
					context.strokeStyle = this.strokeStyle;
					context.stroke();
				}
			}
		}

		move(canvas) {
			this.x += this.vx;
			this.y += this.vy;
			this.vx += this.ax;
			this.vy += this.ay;

			if (this.vx > -0.001 && this.vx < 0.001) {
				this.vx = 0;
			}

			if (this.vy > -0.001 && this.vy < 0.001) {
				this.vy = 0;
			}

			if (this.x <= this.radius) {
				this.x = this.radius;
				this.vx = -this.vx * 0.99;
			}
			else if (this.x >= canvas.width - this.radius) {
				this.x = canvas.width - this.radius;
				this.vx = -this.vx * 0.99;
			}

			if (this.y <= this.radius) {
				this.y = this.radius;
				this.vy = -this.vy * 0.99;
			}
			else if (this.y >= canvas.height - this.radius) {
				this.y = canvas.height - this.radius;
				this.vy = -this.vy * 0.99;
			}
		}

		function randomColor() {
			let keys = Object.keys(Color);
			return Color[keys[Math.trunc(keys.length * Math.random())]];
		}
	}

	window.addEventListener("load", () => {
		const canvas = new Canvas(document.getElementById("canvas"));

		do {
			canvas.addObject(new Circle());
		} while (Math.random() > 0.1);

		canvas.render();
		animate(canvas);

		function animate(canvases) {
			canvas.render();
			window.requestAnimationFrame(animate.bind(this, canvas));
		}
	});
}
<|endoftext|>


<commit_before>Wish = new Meteor.Collection('Wish');

Wish.schema = new SimpleSchema({
  title: {
    type: String,
    label: 'Your wish',
    min: 10
  },
  description: {
    type: String,
    label: 'Detail',
    max: 500,
    optional: true,
    autoform: {
      rows: 3
    }
  },
  owner_id: {
    type: String,
    optional: true,
    autoValue: function() {
      var userId = Meteor.userId() || '';
      if (this.isInsert) {
        return userId;
      } else if (this.isUpsert) {
        return {$setOnInsert: userId};
      } else {
        this.unset();  // Prevent user from supplying their own value
      }
    },
    autoform: {
      type: "hidden"
    }
  },
  date_created: {
    type: Date,
    optional: false,
    autoValue: function() {
      if (this.isInsert) {
        return new Date();
      } else if (this.isUpsert) {
        return {$setOnInsert: new Date()};
      } else {
        this.unset();  // Prevent user from supplying their own value
      }
    },
    autoform: {
      omit: true
    }
  }
});

Wish.attachSchema(Wish.schema);

Wish.allow({
  insert: (userId, document) => userId===Meteor.userId(),
  update: () => false,
  remove: () => false
});

Wish.deny({
  insert: () => false,
  update: () => true,
  remove: () => true
});

Wish.helpers({
  ownerName() {
    let owner = Meteor.users.findOne(this.owner_id);
    let emailName = (x) => x.address.split('@')[0];
    return owner && owner.emails && owner.emails.length>0 && emailName(owner.emails[0]);
  }
});
<commit_msg>Added no_of_comment field, allow date_created to be optional.<commit_after>Wish = new Meteor.Collection('Wish');

Wish.schema = new SimpleSchema({
  title: {
    type: String,
    label: 'Your wish',
    min: 10
  },
  description: {
    type: String,
    label: 'Detail',
    max: 500,
    optional: true,
    autoform: {
      rows: 3
    }
  },
  owner_id: {
    type: String,
    optional: true,
    autoValue: function() {
      var userId = Meteor.userId() || '';
      if (this.isInsert) {
        return userId;
      } else if (this.isUpsert) {
        return {$setOnInsert: userId};
      } else {
        this.unset();  // Prevent user from supplying their own value
      }
    },
    autoform: {
      type: "hidden"
    }
  },
  date_created: {
    type: Date,
    optional: true,
    autoValue: function() {
      if (this.isInsert) {
        return new Date();
      } else if (this.isUpsert) {
        return {$setOnInsert: new Date()};
      } else {
        this.unset();  // Prevent user from supplying their own value
      }
    },
    autoform: {
      omit: true
    }
  },

  no_of_comments: {
    type: Number,
    optional: true,
    defaultValue: 0,
    autoform: {
      omit: true
    }
  }
});

Wish.attachSchema(Wish.schema);

Wish.allow({
  insert: (userId, document) => userId===Meteor.userId(),
  update: () => false,
  remove: () => false
});

Wish.deny({
  insert: () => false,
  update: () => true,
  remove: () => true
});

Wish.helpers({
  ownerName() {
    let owner = Meteor.users.findOne(this.owner_id);
    let emailName = (x) => x.address.split('@')[0];
    return owner && owner.emails && owner.emails.length>0 && emailName(owner.emails[0]);
  }
});
<|endoftext|>


<commit_before>module.exports = require('../password/PasswordFilter');<commit_msg>The color field filter should inherit from the Text type, not Password<commit_after>module.exports = require('../text/TextFilter');
<|endoftext|>


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

  try {
    window._update = false;
    navigator.serviceWorker.register('https://sheeptester.github.io/words-go-here/misc/frontwall-sw.js').then(regis => {
      regis.onupdatefound = () => {
        const installingWorker = regis.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed' && navigator.serviceWorker.controller) {
            window._update = true;
          }
        };
      };
    }, err => {});
  } catch (e) {}

  const content = document.querySelector('table tr:nth-child(2) td:last-child'),
        pageName = document.querySelector('title'),
        path = window.location.pathname,
        page = {

    set title(tabName) {
      pageName.textContent = 'Gamepro5 - ' + tabName;
    },

    get topify() {
      content.vAlign = 'top';
    },

    swapLink(oldLink, newLink) {
      document.querySelectorAll(`a[href="${oldLink}"]`).forEach(el => el.href = newLink);
    }

  };

  page.swapLink('https://goo.gl/forms/tj4LqFKzyMPuOlqg1', 'https://goo.gl/forms/EeA1rGx8marT03MB3');
  page.swapLink('https://goo.gl/forms/ziifb6S4XmK0k3QS2', 'https://goo.gl/forms/AOE4M5FjmbfvbTis2');

  let customButtons = 0;
  function button(text, onclick = '#') {
    if (typeof onclick === 'string') {
      return `<a class="button" href="${onclick}">${text}</a>`
    } else if (typeof onclick === 'function') {
      let fnName = btoa(customButtons++).replace(/[^a-z]/gi, '') || 'a' + customButtons;
      window[fnName] = () => onclick();
      return `<button onclick="window.${fnName}()" class="dropbtn">${text}</button>`
    }
  }

  if (path.startsWith('/programs')) {

    function newProgram(title, description, url) {
      const id = title.toLowerCase().replace(/\s/g, '_');
      if (path === '/programs/' + id) {
        page.title = 'Programs';
        content.innerHTML = `

${title}

          ${description ? `<p>${description}</p>` : ''}

        `;
      } else if (path[9] !== '/') {
        content.appendChild(document.createElement('p')).innerHTML = `
          ${title}

                ${button('play', '/programs/' + id)}
        `;
      }
    }

    // ====== CUSTOM PROGRAMS ======
    // newProgram('test', 'hmmm', 'https://sheeptester.github.io/');

  }
  else switch (path) {

    case '/':

      function newNotif(title) {
        const wrapper = document.createElement('center');
        const id = atob(title).replace(/[^a-z]/gi, '') || 'a' + content.textContent.length;
        if (localStorage[id] === 'yes') wrapper.style.display = 'none';
        content.insertBefore(wrapper, content.querySelector('center:nth-of-type(2)'));
        return {
          set innerHTML(html) {
            wrapper.innerHTML = `

              ×

${title}

              ${html}

            `;
          }
        }
      }

      // ====== CUSTOM ALERTS ======
      // newNotif('test').innerHTML = `lollololollol<p><a class="popupbutton" href="#">do nothing</a></p>`;

      break;

    case '/news':
    case '/news_list':
      const list = path === '/news_list';

      const postLinks = content.querySelector('td > center');
      const posts = content.querySelector('.shadow');

      function newPost(title, date) {
        const id = title.replace(/\s/g, '_').replace(/[^a-z_]/gi, '');
        if (!list)
          postLinks.insertBefore(document.createElement('p'), postLinks.firstElementChild)
            .innerHTML = `<a href="#${id}" class="article">${id}</a>`;

        return {
          set innerHTML(html) {
            const post = document.createElement('div');
            post.innerHTML = `<i>${formatDate(date)}</i><p><b></b></p>`
              + `<h3><b>${title}</b></h3>`
              + html;
            if (list) {
              post.insertBefore(document.createElement('hr'), post.firstElementChild)
                .color = 'red';
              content.insertBefore(post, content.querySelector('hr'));
            } else {
              post.className = 'popup';
              post.id = id;
              posts.appendChild(post);
            }
          }
        }
      }

      const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
      const months = ['January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'];
      function formatDate(date) {
        return `${days[date.getDay()]}, ${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`
      }

      // ====== CUSTOM POSTS ======
      // newPost('Title', new Date()).innerHTML = ``;

      break;

    case '/is-gamepro5-good-programmer':
      page.title = 'Is Gamekeeper 5 a gud programer?';
      content.innerHTML = `

Is Gamekeeper 5 a gud programer?

            <big><big><big><big><big><big><big><big><big><big><big><big><big>NO!</big></big></big></big></big></big></big></big></big></big></big></big></big>

          ${button('why?', '/about-website?programing')}

      `;
      break;

    case '/about-website':

      if (window.location.search === '?programing') {
        const paragraph = content.querySelector('p');
        paragraph.innerHTML = paragraph.innerHTML
          .replace('This site is by far my greatest accomplishment.', '<x-highlight>$&</x-highlight>');
        document.head.appendChild(document.createElement('style')).textContent = `
          x-highlight {
            background-color: rgba(255, 0, 0, 0.1);
            font-weight: bold;
            /* border-bottom: 2px dashed red; */
          }
        `;
      }

      break;

  }

}());
<commit_msg>is there an error?<commit_after>(function() {
  'use strict';

  try {
    window._update = false;
    navigator.serviceWorker.register('https://sheeptester.github.io/words-go-here/misc/frontwall-sw.js').then(regis => {
      regis.onupdatefound = () => {
        const installingWorker = regis.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed' && navigator.serviceWorker.controller) {
            window._update = true;
          }
        };
      };
    }, err => {
      console.log(err);
    });
  } catch (e) {}

  const content = document.querySelector('table tr:nth-child(2) td:last-child'),
        pageName = document.querySelector('title'),
        path = window.location.pathname,
        page = {

    set title(tabName) {
      pageName.textContent = 'Gamepro5 - ' + tabName;
    },

    get topify() {
      content.vAlign = 'top';
    },

    swapLink(oldLink, newLink) {
      document.querySelectorAll(`a[href="${oldLink}"]`).forEach(el => el.href = newLink);
    }

  };

  page.swapLink('https://goo.gl/forms/tj4LqFKzyMPuOlqg1', 'https://goo.gl/forms/EeA1rGx8marT03MB3');
  page.swapLink('https://goo.gl/forms/ziifb6S4XmK0k3QS2', 'https://goo.gl/forms/AOE4M5FjmbfvbTis2');

  let customButtons = 0;
  function button(text, onclick = '#') {
    if (typeof onclick === 'string') {
      return `<a class="button" href="${onclick}">${text}</a>`
    } else if (typeof onclick === 'function') {
      let fnName = btoa(customButtons++).replace(/[^a-z]/gi, '') || 'a' + customButtons;
      window[fnName] = () => onclick();
      return `<button onclick="window.${fnName}()" class="dropbtn">${text}</button>`
    }
  }

  if (path.startsWith('/programs')) {

    function newProgram(title, description, url) {
      const id = title.toLowerCase().replace(/\s/g, '_');
      if (path === '/programs/' + id) {
        page.title = 'Programs';
        content.innerHTML = `

${title}

          ${description ? `<p>${description}</p>` : ''}

        `;
      } else if (path[9] !== '/') {
        content.appendChild(document.createElement('p')).innerHTML = `
          ${title}

                ${button('play', '/programs/' + id)}
        `;
      }
    }

    // ====== CUSTOM PROGRAMS ======
    // newProgram('test', 'hmmm', 'https://sheeptester.github.io/');

  }
  else switch (path) {

    case '/':

      function newNotif(title) {
        const wrapper = document.createElement('center');
        const id = atob(title).replace(/[^a-z]/gi, '') || 'a' + content.textContent.length;
        if (localStorage[id] === 'yes') wrapper.style.display = 'none';
        content.insertBefore(wrapper, content.querySelector('center:nth-of-type(2)'));
        return {
          set innerHTML(html) {
            wrapper.innerHTML = `

              ×

${title}

              ${html}

            `;
          }
        }
      }

      // ====== CUSTOM ALERTS ======
      // newNotif('test').innerHTML = `lollololollol<p><a class="popupbutton" href="#">do nothing</a></p>`;

      break;

    case '/news':
    case '/news_list':
      const list = path === '/news_list';

      const postLinks = content.querySelector('td > center');
      const posts = content.querySelector('.shadow');

      function newPost(title, date) {
        const id = title.replace(/\s/g, '_').replace(/[^a-z_]/gi, '');
        if (!list)
          postLinks.insertBefore(document.createElement('p'), postLinks.firstElementChild)
            .innerHTML = `<a href="#${id}" class="article">${id}</a>`;

        return {
          set innerHTML(html) {
            const post = document.createElement('div');
            post.innerHTML = `<i>${formatDate(date)}</i><p><b></b></p>`
              + `<h3><b>${title}</b></h3>`
              + html;
            if (list) {
              post.insertBefore(document.createElement('hr'), post.firstElementChild)
                .color = 'red';
              content.insertBefore(post, content.querySelector('hr'));
            } else {
              post.className = 'popup';
              post.id = id;
              posts.appendChild(post);
            }
          }
        }
      }

      const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
      const months = ['January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'];
      function formatDate(date) {
        return `${days[date.getDay()]}, ${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`
      }

      // ====== CUSTOM POSTS ======
      // newPost('Title', new Date()).innerHTML = ``;

      break;

    case '/is-gamepro5-good-programmer':
      page.title = 'Is Gamekeeper 5 a gud programer?';
      content.innerHTML = `

Is Gamekeeper 5 a gud programer?

            <big><big><big><big><big><big><big><big><big><big><big><big><big>NO!</big></big></big></big></big></big></big></big></big></big></big></big></big>

          ${button('why?', '/about-website?programing')}

      `;
      break;

    case '/about-website':

      if (window.location.search === '?programing') {
        const paragraph = content.querySelector('p');
        paragraph.innerHTML = paragraph.innerHTML
          .replace('This site is by far my greatest accomplishment.', '<x-highlight>$&</x-highlight>');
        document.head.appendChild(document.createElement('style')).textContent = `
          x-highlight {
            background-color: rgba(255, 0, 0, 0.1);
            font-weight: bold;
            /* border-bottom: 2px dashed red; */
          }
        `;
      }

      break;

  }

}());
<|endoftext|>


<commit_before>describe("getSet function", function () {
    // vars for all tests
    var stubParentObject;

    // setup and teardown
    beforeAll(function () {});

    beforeEach(function () {
        stubParentObject = {};
    });

    afterEach(function () {});

    // specs
    describe("called without arguments", function () {
        it("should throw a TypeError for parentObject", function () {
            expect(function () {
                getSet();
            }).toThrowError(TypeError, "getSet: Could not determine argument 'parentObject'. 'parentObject' is of type 'Undefined'.");
        });
    });

    describe("called without a propertyPath", function () {
        it("should throw a TypeError for propertyPath", function () {
            expect(function () {
                getSet(stubParentObject);
            }).toThrowError(TypeError, "getSet: Could not determine argument 'propertyPath'. 'propertyPath' is of type 'Undefined'.");
        });
    });

    describe("getting a deep undefined property", function () {
        it("should just return undefined", function () {
            expect(getSet(stubParentObject, 'foo.bar')).toBeUndefined();
        });
        it("should not create any path to the deep property that didn't already exist", function () {
            expect(stubParentObject.foo).toBeUndefined();
        });
    });

    describe("setting a value on a deep property path", function () {
        var testSetValue;
        beforeEach(function () {
            testSetValue = 123
        });
        it("should create the path to the property, set the value and return it", function () {
            expect(getSet(stubParentObject, 'foo.bar', testSetValue)).toBe(testSetValue);
        });
        it("should set the value at the full path supplied", function () {
            getSet(stubParentObject, 'foo.bar', testSetValue);
            expect(stubParentObject.foo.bar).toBe(testSetValue);
        });
    });

    describe("setting a value as a property of a string object", function () {
        beforeEach(function () {
            stubParentObject.foo = 'some string value';
        });
        it("should throw a TypeError for that property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo.bar', 123);
            }).toThrowError(TypeError, "getSet: Could not create 'foo.bar'. 'foo' is of type 'String'.");
        });
        it("should not create the property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo.bar', 123);
            }).toThrowError(TypeError, "getSet: Could not create 'foo.bar'. 'foo' is of type 'String'.");
            expect(stubParentObject.foo.bar).toBeUndefined();
        });
    });

    describe("setting a value as a property of a number object", function () {
        beforeEach(function () {
            stubParentObject.foo = 123;
        });
        it("should throw a TypeError for that property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo.bar', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not create 'foo.bar'. 'foo' is of type 'Number'.");
        });
        it("should not create the property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo.bar', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not create 'foo.bar'. 'foo' is of type 'Number'.");
            expect(stubParentObject.foo.bar).toBeUndefined();
        });
    });

    describe("called with || option in propertyPath, and a setValue defined", function () {
        it("should get the value if the property already existed", function () {
            stubParentObject.foo = 123;
            expect(getSet(stubParentObject, 'foo || ', 456)).toBe(123);
        });
        it("should set the property if it didn't exist", function () {
            getSet(stubParentObject, 'bar || ', 789);
            expect(stubParentObject.bar).toBe(789);
        });
        it("should return the passed value if the property didn't exist", function () {
            expect(getSet(stubParentObject, 'bar || ', 789)).toBe(789);
        });
    });

    describe("called with ++ operator in propertyPath (without setValue)", function () {
        it("should increment the value of an undefined path to 1 and return the value", function () {
            expect(getSet(stubParentObject, 'foo ++ ')).toBe(1);
        });
        it("should increment the value of a defined path by 1 and return the value", function () {
            getSet(stubParentObject, 'foo ++ ');
            expect(getSet(stubParentObject, 'foo ++ ')).toBe(2);
        });
    });

    describe("called with -- operator in propertyPath (without setValue)", function () {
        it("should decrement the value of an undefined path to -1 and return the value", function () {
            expect(getSet(stubParentObject, 'foo -- ')).toBe(-1);
        });
        it("should decrement the value of a defined path by 1 and return the value", function () {
            getSet(stubParentObject, 'foo -- ');
            expect(getSet(stubParentObject, 'foo -- ')).toBe(-2);
        });
    });

    describe("called with ++ operator in propertyPath (with numeric setValue)", function () {
        it("should set the value of an undefined path and return the value (Number)", function () {
            expect(getSet(stubParentObject, 'foo ++ ', 3)).toBe(3);
        });
        it("should increment the value of a defined path and return the value (Number)", function () {
            getSet(stubParentObject, 'foo', 3);
            expect(getSet(stubParentObject, 'foo ++ ', 3)).toBe(6);
        });
        it("should set the value of an undefined path and return the value (String)", function () {
            expect(getSet(stubParentObject, 'foo ++ ', '3')).toBe(3);
        });
        it("should increment the value of a defined path and return the value (String)", function () {
            getSet(stubParentObject, 'foo', '3');
            expect(getSet(stubParentObject, 'foo ++ ', '3')).toBe(6);
        });
    });

    describe("called with -- operator in propertyPath (with numeric setValue)", function () {
        it("should set the value of an undefined path and return the value (Number)", function () {
            expect(getSet(stubParentObject, 'foo -- ', 3)).toBe(-3);
        });
        it("should decrement the value of a defined path and return the value (Number)", function () {
            getSet(stubParentObject, 'foo', -3);
            expect(getSet(stubParentObject, 'foo -- ', 3)).toBe(-6);
        });
        it("should set the value of an undefined path and return the value (String)", function () {
            expect(getSet(stubParentObject, 'foo -- ', '3')).toBe(-3);
        });
        it("should decrement the value of a defined path and return the value (String)", function () {
            getSet(stubParentObject, 'foo', '-3');
            expect(getSet(stubParentObject, 'foo -- ', '3')).toBe(-6);
        });
    });

    describe("called with ++ operator in propertyPath (with a non-numeric setValue)", function () {
        it("should throw a TypeError for setting that value on an undefined property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo ++ ', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'Undefined'.");
            expect(stubParentObject.foo).toBeUndefined();
        });
        it("should throw a TypeError for setting that value on an existing String property", function () {
            getSet(stubParentObject, 'foo', 'some string value');
            expect(function () {
                getSet(stubParentObject, 'foo ++ ', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'String'.");
            expect(stubParentObject.foo).toBe('some string value');
        });
        it("should throw a TypeError for setting that value on an existing Number property", function () {
            getSet(stubParentObject, 'foo', 123);
            expect(function () {
                getSet(stubParentObject, 'foo ++ ', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'Number'.");
            expect(stubParentObject.foo).toBe(123);
        });
    });

    describe("called with -- operator in propertyPath (with a non-numeric setValue)", function () {
        it("should throw a TypeError for setting that value on an undefined property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo -- ', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'Undefined'.");
            expect(stubParentObject.foo).toBeUndefined();
        });
        it("should throw a TypeError for setting that value on an existing String property", function () {
            getSet(stubParentObject, 'foo', 'some string value');
            expect(function () {
                getSet(stubParentObject, 'foo -- ', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'String'.");
            expect(stubParentObject.foo).toBe('some string value');
        });
        it("should throw a TypeError for setting that value on an existing Number property", function () {
            getSet(stubParentObject, 'foo', 123);
            expect(function () {
                getSet(stubParentObject, 'foo -- ', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'Number'.");
            expect(stubParentObject.foo).toBe(123);
        });
    });
});
<commit_msg>Updated for new 'option' parameters<commit_after>describe("getSet function", function () {
    // vars for all tests
    var stubParentObject;

    // setup and teardown
    beforeAll(function () {});

    beforeEach(function () {
        stubParentObject = {};
    });

    afterEach(function () {});

    // specs
    describe("called without arguments", function () {
        it("should throw a TypeError for parentObject", function () {
            expect(function () {
                getSet();
            }).toThrowError(TypeError, "getSet: Could not determine argument 'parentObject'. 'parentObject' is of type 'Undefined'.");
        });
    });

    describe("called without a propertyPath", function () {
        it("should throw a TypeError for propertyPath", function () {
            expect(function () {
                getSet(stubParentObject);
            }).toThrowError(TypeError, "getSet: Could not determine argument 'propertyPath'. 'propertyPath' is of type 'Undefined'.");
        });
    });

    describe("getting a deep undefined property", function () {
        it("should just return undefined", function () {
            expect(getSet(stubParentObject, 'foo.bar')).toBeUndefined();
        });
        it("should not create any path to the deep property that didn't already exist", function () {
            expect(stubParentObject.foo).toBeUndefined();
        });
    });

    describe("setting a value on a deep property path", function () {
        var testSetValue;
        beforeEach(function () {
            testSetValue = 123
        });
        it("should create the path to the property, set the value and return it", function () {
            expect(getSet(stubParentObject, 'foo.bar', testSetValue)).toBe(testSetValue);
        });
        it("should set the value at the full path supplied", function () {
            getSet(stubParentObject, 'foo.bar', testSetValue);
            expect(stubParentObject.foo.bar).toBe(testSetValue);
        });
    });

    describe("setting a value as a property of a string object", function () {
        beforeEach(function () {
            stubParentObject.foo = 'some string value';
        });
        it("should throw a TypeError for that property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo.bar', 123);
            }).toThrowError(TypeError, "getSet: Could not create 'foo.bar'. 'foo' is of type 'String'.");
        });
        it("should not create the property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo.bar', 123);
            }).toThrowError(TypeError, "getSet: Could not create 'foo.bar'. 'foo' is of type 'String'.");
            expect(stubParentObject.foo.bar).toBeUndefined();
        });
    });

    describe("setting a value as a property of a number object", function () {
        beforeEach(function () {
            stubParentObject.foo = 123;
        });
        it("should throw a TypeError for that property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo.bar', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not create 'foo.bar'. 'foo' is of type 'Number'.");
        });
        it("should not create the property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo.bar', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not create 'foo.bar'. 'foo' is of type 'Number'.");
            expect(stubParentObject.foo.bar).toBeUndefined();
        });
    });

    describe("called with 'or' option in setValueOrOption, and an optionValue defined", function () {
        it("should get the value if the property already existed", function () {
            stubParentObject.foo = 123;
            expect(getSet(stubParentObject, 'foo', 'or', 456)).toBe(123);
        });
        it("should set the property if it didn't exist", function () {
            getSet(stubParentObject, 'bar', 'or', 789);
            expect(stubParentObject.bar).toBe(789);
        });
        it("should return the passed value if the property didn't exist", function () {
            expect(getSet(stubParentObject, 'bar', 'or', 789)).toBe(789);
        });
    });

    describe("called with '++' operator in setValueOrOption (without optionValue)", function () {
        it("should increment the value of an undefined path to 1 and return the value", function () {
            expect(getSet(stubParentObject, 'foo', '++')).toBe('++');
        });
    });

    describe("called with '--' operator in setValueOrOption (without optionValue)", function () {
        it("should decrement the value of an undefined path to -1 and return the value", function () {
            expect(getSet(stubParentObject, 'foo', '--')).toBe('--');
        });
    });

    describe("called with '++' operator in setValueOrOption (with numeric optionValue)", function () {
        it("should set the value of an undefined path and return the value (Number)", function () {
            expect(getSet(stubParentObject, 'foo', '++', 3)).toBe(3);
        });
        it("should increment the value of a defined path and return the value (Number)", function () {
            getSet(stubParentObject, 'foo', 3);
            expect(getSet(stubParentObject, 'foo', '++', 3)).toBe(6);
        });
        it("should set the value of an undefined path and return the value (String)", function () {
            expect(getSet(stubParentObject, 'foo', '++', '3')).toBe(3);
        });
        it("should increment the value of a defined path and return the value (String)", function () {
            getSet(stubParentObject, 'foo', '3');
            expect(getSet(stubParentObject, 'foo', '++', '3')).toBe(6);
        });
    });

    describe("called with '--' operator in setValueOrOption (with numeric optionValue)", function () {
        it("should set the value of an undefined path and return the value (Number)", function () {
            expect(getSet(stubParentObject, 'foo', '--', 3)).toBe(-3);
        });
        it("should decrement the value of a defined path and return the value (Number)", function () {
            getSet(stubParentObject, 'foo', -3);
            expect(getSet(stubParentObject, 'foo', '--', 3)).toBe(-6);
        });
        it("should set the value of an undefined path and return the value (String)", function () {
            expect(getSet(stubParentObject, 'foo', '--', '3')).toBe(-3);
        });
        it("should decrement the value of a defined path and return the value (String)", function () {
            getSet(stubParentObject, 'foo', '-3');
            expect(getSet(stubParentObject, 'foo', '--', '3')).toBe(-6);
        });
    });

    describe("called with '++' operator in setValueOrOption (with a non-numeric optionValue)", function () {
        it("should throw a TypeError for setting that value on an undefined property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo', '++', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'Undefined'.");
            expect(stubParentObject.foo).toBeUndefined();
        });
        it("should throw a TypeError for setting that value on an existing String property", function () {
            getSet(stubParentObject, 'foo', 'some string value');
            expect(function () {
                getSet(stubParentObject, 'foo', '++', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'String'.");
            expect(stubParentObject.foo).toBe('some string value');
        });
        it("should throw a TypeError for setting that value on an existing Number property", function () {
            getSet(stubParentObject, 'foo', 123);
            expect(function () {
                getSet(stubParentObject, 'foo', '++', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'Number'.");
            expect(stubParentObject.foo).toBe(123);
        });
    });

    describe("called with '--' operator in setValueOrOption (with a non-numeric optionValue)", function () {
        it("should throw a TypeError for setting that value on an undefined property", function () {
            expect(function () {
                getSet(stubParentObject, 'foo', '--', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'Undefined'.");
            expect(stubParentObject.foo).toBeUndefined();
        });
        it("should throw a TypeError for setting that value on an existing String property", function () {
            getSet(stubParentObject, 'foo', 'some string value');
            expect(function () {
                getSet(stubParentObject, 'foo', '--', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'String'.");
            expect(stubParentObject.foo).toBe('some string value');
        });
        it("should throw a TypeError for setting that value on an existing Number property", function () {
            getSet(stubParentObject, 'foo', 123);
            expect(function () {
                getSet(stubParentObject, 'foo', '--', 'some string value');
            }).toThrowError(TypeError, "getSet: Could not in/decrement with value 'some string value' on property 'foo'. 'foo' is of type 'Number'.");
            expect(stubParentObject.foo).toBe(123);
        });
    });
});
<|endoftext|>


<commit_before>"use strict";

var remote = require('remote')
var Menu = remote.require('menu')
var MenuItem = remote.require('menu-item')
let hoxy = require('hoxy');
let highlight = require('highlight.js');
//window.$ = window.jQuery = require('jquery');

//require("../bower_components/jquery.splitter/js/jquery.splitter-0.20.0.js");

// Build our new menu
var menu = new Menu()
menu.append(new MenuItem({
  label: 'Delete',
  click: function() {
    // Trigger an alert when menu item is clicked
    alert('Deleted')
  }
}))
menu.append(new MenuItem({
  label: 'More Info...',
  click: function() {
    // Trigger an alert when menu item is clicked
    alert('Here is more information')
  }
}))

// Add the listener
document.addEventListener('DOMContentLoaded', function () {
  // document.querySelector('.js-context-menu').addEventListener('click', function (event) {
  //   menu.popup(remote.getCurrentWindow());
  // })
  document.addEventListener('contextmenu', function (event) {
    menu.popup(remote.getCurrentWindow());
  })
})

angular.module("BoxyApp", [])
.controller("MainController", function($scope) {
  this.serverList = [
    {
      name: "HTTP Bin",
      remoteURL: "http://httpbin.org",
      localPort: "8080",
      started: false,
      requestList: []
    },
    {
      name: "Example.com",
      remoteURL: "http://example.com",
      localPort: "8081",
      started: false,
      requestList: []
    }
  ];
  this.editableServer = {
    name: "",
    remoteURL: "",
    localPort: "",
    started: false
  }
  this.selectedServer = undefined;
  this.dialogMode = "ADD";
  this.selectedRequest = undefined;
  this.activeTab = undefined;

  this.isServerSelected = function(server) {
    return server === this.selectedServer;
  }
  this.selectServer = function(server) {
    this.selectedServer = server;
    this.selectedRequest = undefined;
  }
  this.startButtonEnabled = function() {
    return this.selectedServer !== undefined && !this.selectedServer.started;
  }
  this.stopButtonEnabled = function() {
    return this.selectedServer !== undefined && this.selectedServer.started;
  }
  this.openNewServerDialog = function() {
    this.dialogMode = "ADD";
    this.editableServer.name = "";
    this.editableServer.remoteURL = "";
    this.editableServer.localPort = "";

    document.getElementById("editableServerDialog").showModal();
  }
  this.closeNewServerDialog = function() {
    document.getElementById("editableServerDialog").close();
  }

  this.addNewServer = function() {
    console.log("Adding new server.");
    this.closeNewServerDialog();
    var server = {
      name: this.editableServer.name,
      remoteURL: this.editableServer.remoteURL,
      localPort: this.editableServer.localPort,
      started: this.editableServer.started,
      requestList: []
    }
    this.serverList.push(server);
    this.selectedServer = server;
  };

  this.removeServer = function() {
    if (this.selectedServer === undefined) {
      return;
    }

    var idx = this.serverList.indexOf(this.selectedServer);

    if (idx < 0) {
      return;
    }

    //Stop the server.
    if (this.selectedServer.started) {
      this.stopServer();
    }

    //Remove the server.
    this.serverList.splice(idx, 1);

    this.selectedServer = undefined;
  }

  this.openEditServerDialog = function() {
    if (this.selectedServer === undefined) {
      return;
    }

    this.dialogMode = "EDIT";

    this.editableServer.name = this.selectedServer.name;
    this.editableServer.remoteURL = this.selectedServer.remoteURL;
    this.editableServer.localPort = this.selectedServer.localPort;

    document.getElementById("editableServerDialog").showModal();
  }

  this.updateServerSettings = function() {
    if (this.selectedServer === undefined) {
      return;
    }

    this.selectedServer.name = this.editableServer.name;
    this.selectedServer.remoteURL = this.editableServer.remoteURL;
    this.selectedServer.localPort = this.editableServer.localPort;

    if (this.selectedServer.started) {
      //Restart the server
      this.stopServer();
      this.startServer();
    }

    document.getElementById("editableServerDialog").close();
  }

  this.startServer = function() {
    if (this.selectedServer === undefined || this.selectedServer.started) {
      return;
    }

    var textTypes = [
      "application/xml",
      "application/json",
      "text/html",
      "text/json"
    ];
    var theServer = this.selectedServer; //Closure variable

    theServer.proxy = hoxy.createServer({
      reverse: theServer.remoteURL
    }).listen(theServer.localPort);
    theServer.started = true;

    theServer.proxy.intercept({
      phase: 'request',
      as: 'buffer'
    }, (req, resp, cycle) => {
      //console.log(req.buffer.toString('utf8'));
      var contentType = req.headers["content-type"];
      var reqTxt = "";

      if (textTypes.some((type) => {
          return type === contentType;
      })) {
        console.log("Detected text type request.")
        var buff = req.buffer;
        if (buff !== undefined) {
          reqTxt = buff.toString('utf8');
        } else {
          console.log("Request buffer is undefined.");
        }
      }
      req.boxyRequestData = {
        requestText: reqTxt,
        request: req,
        startTime: new Date()
      };
    });

    theServer.proxy.intercept({
      phase: 'response',
      as: 'buffer'
    }, (req, resp, cycle) => {
      console.log(req);
      console.log(resp);
      var contentType = resp.headers["content-type"];
      var respTxt = "";

      if (textTypes.some((type) => {
          return type === contentType;
      })) {
        console.log("Detected text type response.")
        var buff = resp.buffer;
        if (buff !== undefined) {
          respTxt = buff.toString('utf8');
        } else {
          console.log("Response buffer is undefined.");
        }
      }

      req.boxyRequestData.response = resp;
      req.boxyRequestData.responseText = respTxt;
      req.boxyRequestData.endTime = new Date();
      req.boxyRequestData.duration = req.boxyRequestData.endTime.getTime() -
        req.boxyRequestData.startTime.getTime();
      req.boxyRequestData.formattedStartTime = "" +
        (req.boxyRequestData.startTime.getMonth() + 1) + "/" +
        req.boxyRequestData.startTime.getDate() + "/" +
        req.boxyRequestData.startTime.getFullYear() + " " +
        req.boxyRequestData.startTime.getHours() + ":" +
        req.boxyRequestData.startTime.getMinutes();

      theServer.requestList.push(req.boxyRequestData);

      $scope.$apply();
    });
  }

  this.stopServer = function() {
    if (this.selectedServer === undefined || !this.selectedServer.started) {
      return;
    }

    this.selectedServer.proxy.close();
    this.selectedServer.proxy = undefined;
    this.selectedServer.started = false;
  }

  this.selectRequest = function(req) {
    this.selectedRequest = req;
    this.activeTab = 'request';
    console.log("Request: %s\n", req.requestText);
    console.log("Response: %s\n", req.responseText);
  }

  this.isRequestSelected = function(req) {
    return this.selectedRequest === req;
  }

});
<commit_msg>Do error handling for server starts.<commit_after>"use strict";

var remote = require('remote')
var Menu = remote.require('menu')
var MenuItem = remote.require('menu-item')
let hoxy = require('hoxy');
let highlight = require('highlight.js');
//window.$ = window.jQuery = require('jquery');

//require("../bower_components/jquery.splitter/js/jquery.splitter-0.20.0.js");

// Build our new menu
var menu = new Menu()
menu.append(new MenuItem({
  label: 'Delete',
  click: function() {
    // Trigger an alert when menu item is clicked
    alert('Deleted')
  }
}))
menu.append(new MenuItem({
  label: 'More Info...',
  click: function() {
    // Trigger an alert when menu item is clicked
    alert('Here is more information')
  }
}))

// Add the listener
document.addEventListener('DOMContentLoaded', function () {
  // document.querySelector('.js-context-menu').addEventListener('click', function (event) {
  //   menu.popup(remote.getCurrentWindow());
  // })
  document.addEventListener('contextmenu', function (event) {
    menu.popup(remote.getCurrentWindow());
  })
})

angular.module("BoxyApp", [])
.controller("MainController", function($scope) {
  this.serverList = [
    {
      name: "HTTP Bin",
      remoteURL: "http://httpbin.org",
      localPort: "8080",
      started: false,
      requestList: []
    },
    {
      name: "Example.com",
      remoteURL: "http://example.com",
      localPort: "8081",
      started: false,
      requestList: []
    }
  ];
  this.editableServer = {
    name: "",
    remoteURL: "",
    localPort: "",
    started: false
  }
  this.selectedServer = undefined;
  this.dialogMode = "ADD";
  this.selectedRequest = undefined;
  this.activeTab = 'request';

  this.isServerSelected = function(server) {
    return server === this.selectedServer;
  }
  this.selectServer = function(server) {
    this.selectedServer = server;
    this.selectedRequest = undefined;
  }
  this.startButtonEnabled = function() {
    return this.selectedServer !== undefined && !this.selectedServer.started;
  }
  this.stopButtonEnabled = function() {
    return this.selectedServer !== undefined && this.selectedServer.started;
  }
  this.openNewServerDialog = function() {
    this.dialogMode = "ADD";
    this.editableServer.name = "";
    this.editableServer.remoteURL = "";
    this.editableServer.localPort = "";

    document.getElementById("editableServerDialog").showModal();
  }
  this.closeNewServerDialog = function() {
    document.getElementById("editableServerDialog").close();
  }

  this.addNewServer = function() {
    console.log("Adding new server.");
    this.closeNewServerDialog();
    var server = {
      name: this.editableServer.name,
      remoteURL: this.editableServer.remoteURL,
      localPort: this.editableServer.localPort,
      started: this.editableServer.started,
      requestList: []
    }
    this.serverList.push(server);
    this.selectedServer = server;
  };

  this.removeServer = function() {
    if (this.selectedServer === undefined) {
      return;
    }

    var idx = this.serverList.indexOf(this.selectedServer);

    if (idx < 0) {
      return;
    }

    //Stop the server.
    if (this.selectedServer.started) {
      this.stopServer();
    }

    //Remove the server.
    this.serverList.splice(idx, 1);

    this.selectedServer = undefined;
  }

  this.openEditServerDialog = function() {
    if (this.selectedServer === undefined) {
      return;
    }

    this.dialogMode = "EDIT";

    this.editableServer.name = this.selectedServer.name;
    this.editableServer.remoteURL = this.selectedServer.remoteURL;
    this.editableServer.localPort = this.selectedServer.localPort;

    document.getElementById("editableServerDialog").showModal();
  }

  this.updateServerSettings = function() {
    if (this.selectedServer === undefined) {
      return;
    }

    this.selectedServer.name = this.editableServer.name;
    this.selectedServer.remoteURL = this.editableServer.remoteURL;
    this.selectedServer.localPort = this.editableServer.localPort;

    if (this.selectedServer.started) {
      //Restart the server
      this.stopServer();
      this.startServer();
    }

    document.getElementById("editableServerDialog").close();
  }

  this.startServer = function() {
    if (this.selectedServer === undefined || this.selectedServer.started) {
      return;
    }

    var textTypes = [
      "application/xml",
      "application/json",
      "text/html",
      "text/json"
    ];
    var theServer = this.selectedServer; //Closure variable

    theServer.proxy = hoxy.createServer({
      reverse: theServer.remoteURL
    })
    .listen(theServer.localPort, function() {
      theServer.started = true;
      $scope.$apply();

      theServer.proxy.intercept({
        phase: 'request',
        as: 'buffer'
      }, (req, resp, cycle) => {
        //console.log(req.buffer.toString('utf8'));
        var contentType = req.headers["content-type"];
        var reqTxt = "";

        if (textTypes.some((type) => {
            return type === contentType;
        })) {
          console.log("Detected text type request.")
          var buff = req.buffer;
          if (buff !== undefined) {
            reqTxt = buff.toString('utf8');
          } else {
            console.log("Request buffer is undefined.");
          }
        }
        req.boxyRequestData = {
          requestText: reqTxt,
          request: req,
          startTime: new Date()
        };
      });

      theServer.proxy.intercept({
        phase: 'response',
        as: 'buffer'
      }, (req, resp, cycle) => {
        console.log(req);
        console.log(resp);
        var contentType = resp.headers["content-type"];
        var respTxt = "";

        if (textTypes.some((type) => {
            return type === contentType;
        })) {
          console.log("Detected text type response.")
          var buff = resp.buffer;
          if (buff !== undefined) {
            respTxt = buff.toString('utf8');
          } else {
            console.log("Response buffer is undefined.");
          }
        }

        req.boxyRequestData.response = resp;
        req.boxyRequestData.responseText = respTxt;
        req.boxyRequestData.endTime = new Date();
        req.boxyRequestData.duration = req.boxyRequestData.endTime.getTime() -
          req.boxyRequestData.startTime.getTime();
        req.boxyRequestData.formattedStartTime = "" +
          (req.boxyRequestData.startTime.getMonth() + 1) + "/" +
          req.boxyRequestData.startTime.getDate() + "/" +
          req.boxyRequestData.startTime.getFullYear() + " " +
          req.boxyRequestData.startTime.getHours() + ":" +
          req.boxyRequestData.startTime.getMinutes();

        theServer.requestList.push(req.boxyRequestData);

        $scope.$apply();
      });
    })
    .on("error", function(err) {
      console.log(err);
      if (err.code === 'EADDRINUSE') {
        alert(`Could not start server. Port ${err.port} is already in use.`);
      } else if (err.code === 'EACCES') {
          alert(`Could not start server. You don't have access to port ${err.port}.`);
      } else {
        alert("Failed to start server.")
      }
    });
  }

  this.stopServer = function() {
    if (this.selectedServer === undefined || !this.selectedServer.started) {
      return;
    }

    this.selectedServer.proxy.close();
    this.selectedServer.proxy = undefined;
    this.selectedServer.started = false;
  }

  this.selectRequest = function(req) {
    this.selectedRequest = req;
    this.activeTab = 'request';
    console.log("Request: %s\n", req.requestText);
    console.log("Response: %s\n", req.responseText);
  }

  this.isRequestSelected = function(req) {
    return this.selectedRequest === req;
  }

});
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * Model of the point tool. Knows when it is placed on one of the quadratics.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const DerivedProperty = require( 'AXON/DerivedProperty' );
  const DerivedPropertyIO = require( 'AXON/DerivedPropertyIO' );
  const GQQueryParameters = require( 'GRAPHING_QUADRATICS/common/GQQueryParameters' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const Property = require( 'AXON/Property' );
  const PropertyIO = require( 'AXON/PropertyIO' );
  const QuadraticIO = require( 'GRAPHING_QUADRATICS/common/model/QuadraticIO' );
  const Tandem = require( 'TANDEM/Tandem' );
  const Vector2 = require( 'DOT/Vector2' );
  const Vector2IO = require( 'DOT/Vector2IO' );

  // ifphetio
  const NullableIO = require( 'ifphetio!PHET_IO/types/NullableIO' );

  // constants
  const PROBE_SIDES = [ 'right', 'left' ];
  // snap to quadratic when <= this distance from the quadratic, in model coordinates
  const SNAP_DISTANCE = GQQueryParameters.snapDistance;

  class PointTool {

    /**
     * @param {ObservableArray.<Quadratic>} quadratics - Quadratics that the tool might intersect
     * @param {Object} [options]
     */
    constructor( quadratics, options ) {

      options = _.extend( {
        location: Vector2.ZERO, // {Vector2} initial location
        probeSide: 'left', // {string} which side the probe is on, see PROBE_SIDES
        dragBounds: null, // {Bounds2|null} drag bounds, in model coordinate frame
        tandem: Tandem.required
      }, options );

      assert && assert( PROBE_SIDES.includes( options.probeSide ),
        'invalid probeSide: ' + options.probeSide );

      // @public (read-only)
      this.quadratics = quadratics;
      this.probeSide = options.probeSide;
      this.dragBounds = options.dragBounds;
      this.snapDistance = SNAP_DISTANCE;

      // @public {Vector2}
      this.locationProperty = new Property( options.location, {
        valueType: Vector2,
        tandem: options.tandem.createTandem( 'locationProperty' ),
        phetioType: PropertyIO( NullableIO( Vector2IO ) ),
        phetioDocumentation: 'location of this point tool'
      } );

      // @public {DerivedProperty.<Quadratic|null>}
      this.snapQuadraticProperty = new DerivedProperty( [ this.locationProperty, quadratics.lengthProperty ],
        ( location, length ) => {
          for ( let i = 0; i < length; i++ ) {
            let quadratic = quadratics.get( i );
            if ( quadratic.isOnQuadratic( this.locationProperty.value, this.snapDistance ) ) {
              return quadratic;
            }
          }
          return null;
        }, {
          tandem: options.tandem.createTandem( 'snapQuadraticProperty' ),
          phetioType: DerivedPropertyIO( NullableIO( QuadraticIO ) ),
          phetioDocumentation: 'the quadratic that this point tool is snapped to, null if no quadratic'
        } );
    }

    // @public
    reset() {
      this.locationProperty.reset();
    }
  }

  return graphingQuadratics.register( 'PointTool', PointTool );
} );

<commit_msg>fix phetioType for locationProperty, #57<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * Model of the point tool. Knows when it is placed on one of the quadratics.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const DerivedProperty = require( 'AXON/DerivedProperty' );
  const DerivedPropertyIO = require( 'AXON/DerivedPropertyIO' );
  const GQQueryParameters = require( 'GRAPHING_QUADRATICS/common/GQQueryParameters' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const Property = require( 'AXON/Property' );
  const PropertyIO = require( 'AXON/PropertyIO' );
  const QuadraticIO = require( 'GRAPHING_QUADRATICS/common/model/QuadraticIO' );
  const Tandem = require( 'TANDEM/Tandem' );
  const Vector2 = require( 'DOT/Vector2' );
  const Vector2IO = require( 'DOT/Vector2IO' );

  // ifphetio
  const NullableIO = require( 'ifphetio!PHET_IO/types/NullableIO' );

  // constants
  const PROBE_SIDES = [ 'right', 'left' ];
  // snap to quadratic when <= this distance from the quadratic, in model coordinates
  const SNAP_DISTANCE = GQQueryParameters.snapDistance;

  class PointTool {

    /**
     * @param {ObservableArray.<Quadratic>} quadratics - Quadratics that the tool might intersect
     * @param {Object} [options]
     */
    constructor( quadratics, options ) {

      options = _.extend( {
        location: Vector2.ZERO, // {Vector2} initial location
        probeSide: 'left', // {string} which side the probe is on, see PROBE_SIDES
        dragBounds: null, // {Bounds2|null} drag bounds, in model coordinate frame
        tandem: Tandem.required
      }, options );

      assert && assert( PROBE_SIDES.includes( options.probeSide ),
        'invalid probeSide: ' + options.probeSide );

      // @public (read-only)
      this.quadratics = quadratics;
      this.probeSide = options.probeSide;
      this.dragBounds = options.dragBounds;
      this.snapDistance = SNAP_DISTANCE;

      // @public {Vector2}
      this.locationProperty = new Property( options.location, {
        valueType: Vector2,
        tandem: options.tandem.createTandem( 'locationProperty' ),
        phetioType: PropertyIO( Vector2IO ),
        phetioDocumentation: 'location of this point tool'
      } );

      // @public {DerivedProperty.<Quadratic|null>}
      this.snapQuadraticProperty = new DerivedProperty( [ this.locationProperty, quadratics.lengthProperty ],
        ( location, length ) => {
          for ( let i = 0; i < length; i++ ) {
            let quadratic = quadratics.get( i );
            if ( quadratic.isOnQuadratic( this.locationProperty.value, this.snapDistance ) ) {
              return quadratic;
            }
          }
          return null;
        }, {
          tandem: options.tandem.createTandem( 'snapQuadraticProperty' ),
          phetioType: DerivedPropertyIO( NullableIO( QuadraticIO ) ),
          phetioDocumentation: 'the quadratic that this point tool is snapped to, null if no quadratic'
        } );
    }

    // @public
    reset() {
      this.locationProperty.reset();
    }
  }

  return graphingQuadratics.register( 'PointTool', PointTool );
} );

<|endoftext|>