<commit_before>/**
 * Given a MagpieClient, get all models with a certain datatype
 * @param client [in|out] Connected MagpieServerClient
 * @param dataType [in] Desired data type
 * @return Map of name -> Model info for models that have the target type
 */
function getModelsOfType(client, dataType) {
    var allModels = client.getModelInformation();
    var output = new Array();
    for (var model in allModels) {
        if (allModels[model].dataType.includes(dataType)) {
            output[model] = allModels[model];
        }
    }
    return output;
}

/**
 * Create a table to store output data. Looks something like
 *
 *          oqmd_dH             oqmd_vol
 *          ΔH (eV/atom)  V (Ang^3/atom)
 * entry_1  model1_entry1       model2_entry1
 * entry_2  model1_entry2       model2_entry2
 * @param modelInfo [in] Information about all models
 * @param models    [in] Models to print
 * @param entries   [in] Entries to print
 * @return A table object, as specified
 */
function createTable(modelInfo, models, entries) {
    // Thanks to: http://stackoverflow.com/questions/14643617/create-table-using-javascript
    var tbl = document.createElement('table');
    var tbody = document.createElement('tbdy');
    tbl.appendChild(tbody)
    var tr = document.createElement('tr');

    // List out the model names
    var td = document.createElement('th');
    tr.appendChild(td);
    td.innerHTML = "Model:";
    for (model in models) {
        td = document.createElement('th');
        td.innerHTML = models[model]
        tr.appendChild(td)
    }
    tbody.appendChild(tr);

    // List out model properties
    var td = document.createElement('th');
    tr = document.createElement('tr');
    td.innerHTML = "Property:";
    tr.appendChild(td);
    for (model in models) {
        td = document.createElement('th');
        name = models[model];
        td.innerHTML = modelInfo[name].property + " (" + modelInfo[name].units + ")";
        tr.appendChild(td);
    }
    tbody.appendChild(tr);

    // Print out
    for (i in entries) {
        var entry = entries[i]
        tr = document.createElement('tr');
        td = document.createElement('td');
        td.innerHTML = entry.name
        tr.appendChild(td)
        for (model in models) {
        	mname = models[model]
            td = document.createElement('td');
            var num = entry.predictedProperties[mname];
            if (entry.classProbs[mname] == undefined) {
	            td.innerHTML = num.toPrecision(3)
            } else {
            	td.innerHTML = modelInfo[mname].units.split(";")[num]
            	td.innerHTML += " ("
            	x = entry.classProbs[mname][num] * 100
            	td.innerHTML += x.toFixed(1)
            	td.innerHTML += "%)"
            }
            tr.appendChild(td)
        }
        tbody.appendChild(tr)
    }

    return tbl;
}

/**
 * Write out model information
 *
 * @param modelInfo [in] Information about model
 * @param outputDiv [in] Part of page to output data
 */
function outputModelInfo(modelInfo, outputDiv) {

	if (modelInfo === undefined) {
		outputDiv.innerHTML += "
No such model.
";
	}
	outputDiv.innerHTML += "
" + modelInfo.notes + "
";

	// Make a table storing general information about model
	output = "
General Information
";
	output += "Property	" + modelInfo.property + "	";
	output += "
Units	" + modelInfo.units + "	";
	output += "
Training Set	" + modelInfo.training + "	";
	output += "
Author	" + modelInfo.author + "	";
	output += "
Citation	" + modelInfo.citation + "	";

	outputDiv.innerHTML += output;

	// Print out model performance
	output = "
Model Performance
"
	output += "
Validation Method" + modelInfo.valMethod + "
"
	if (modelInfo.classifier) {
		output += "Accuracy" + (modelInfo.valScore.Accuracy * 100).toFixed(2) + "%"
		output += "
Kappa" + modelInfo.valScore.Kappa.toFixed(4)
		output += "
Sensitivity" + (modelInfo.valScore.Sensitivity * 100).toFixed(2) + "%"
		output += "
False Positive Rate" + (modelInfo.valScore.FPR * 100).toFixed(2) + "%"
		output += "
Area Under ROC" + modelInfo.valScore.ROCAUC.toFixed(4)
	} else {
		output += "R" + modelInfo.valScore.R.toFixed(4)
		output += "
ρ" + modelInfo.valScore.Rho.toFixed(4)
		output += "
τ" + modelInfo.valScore.Tau.toFixed(4)
		output += "
MAE" + modelInfo.valScore.MAE.toPrecision(3) + " " + modelInfo.units
		output += "
RMSE" + modelInfo.valScore.RMSE.toPrecision(3) + " " + modelInfo.units
		if (modelInfo.valScore.MRE != "NaN") {
			output += "
MRE" + (modelInfo.valScore.MRE * 100).toFixed(2) + "%"
		}
	}

	outputDiv.innerHTML += output

	// Print out model structure
	output = "
Model Structure
"
	output += "
"
	typeLines = modelInfo.modelType.split("\n")
	for (i in typeLines) {
		line = typeLines[i]

		words = line.split(" ")

		// Look for names of magpie classes
		for (j in words) {
			word = words[j]
			if (word.indexOf("magpie.") == 0) {
				words[j] = getDocReference(words[j])
			}
		}

		// Output line
		for (j in words) {
			output += " " + words[j]
		}

	}
	output += "
"

	outputDiv.innerHTML += output
}

var javadocURL = "http://oqmd.org/static/analytics/magpie/javadoc/"
/**
 * Get weblink to a certain magpie class
 * @param className [in] Full name of magpie class (should start with "magpie.")
 * @return Hyperlink to its documentation page
 */
function getDocReference(className) {
	return "" + className + ""
}<commit_msg>Bug fix: include() not supported by Firefox<commit_after>/**
 * Given a MagpieClient, get all models with a certain datatype
 * @param client [in|out] Connected MagpieServerClient
 * @param dataType [in] Desired data type
 * @return Map of name -> Model info for models that have the target type
 */
function getModelsOfType(client, dataType) {
    var allModels = client.getModelInformation();
    var output = new Array();
    for (var model in allModels) {
        if (allModels[model].dataType.indexOf(dataType) !== -1) {
            output[model] = allModels[model];
        }
    }
    return output;
}

/**
 * Create a table to store output data. Looks something like
 *
 *          oqmd_dH             oqmd_vol
 *          ΔH (eV/atom)  V (Ang^3/atom)
 * entry_1  model1_entry1       model2_entry1
 * entry_2  model1_entry2       model2_entry2
 * @param modelInfo [in] Information about all models
 * @param models    [in] Models to print
 * @param entries   [in] Entries to print
 * @return A table object, as specified
 */
function createTable(modelInfo, models, entries) {
    // Thanks to: http://stackoverflow.com/questions/14643617/create-table-using-javascript
    var tbl = document.createElement('table');
    var tbody = document.createElement('tbdy');
    tbl.appendChild(tbody)
    var tr = document.createElement('tr');

    // List out the model names
    var td = document.createElement('th');
    tr.appendChild(td);
    td.innerHTML = "Model:";
    for (model in models) {
        td = document.createElement('th');
        td.innerHTML = models[model]
        tr.appendChild(td)
    }
    tbody.appendChild(tr);

    // List out model properties
    var td = document.createElement('th');
    tr = document.createElement('tr');
    td.innerHTML = "Property:";
    tr.appendChild(td);
    for (model in models) {
        td = document.createElement('th');
        name = models[model];
        td.innerHTML = modelInfo[name].property + " (" + modelInfo[name].units + ")";
        tr.appendChild(td);
    }
    tbody.appendChild(tr);

    // Print out
    for (i in entries) {
        var entry = entries[i]
        tr = document.createElement('tr');
        td = document.createElement('td');
        td.innerHTML = entry.name
        tr.appendChild(td)
        for (model in models) {
        	mname = models[model]
            td = document.createElement('td');
            var num = entry.predictedProperties[mname];
            if (entry.classProbs[mname] == undefined) {
	            td.innerHTML = num.toPrecision(3)
            } else {
            	td.innerHTML = modelInfo[mname].units.split(";")[num]
            	td.innerHTML += " ("
            	x = entry.classProbs[mname][num] * 100
            	td.innerHTML += x.toFixed(1)
            	td.innerHTML += "%)"
            }
            tr.appendChild(td)
        }
        tbody.appendChild(tr)
    }

    return tbl;
}

/**
 * Write out model information
 *
 * @param modelInfo [in] Information about model
 * @param outputDiv [in] Part of page to output data
 */
function outputModelInfo(modelInfo, outputDiv) {

	if (modelInfo === undefined) {
		outputDiv.innerHTML += "
No such model.
";
	}
	outputDiv.innerHTML += "
" + modelInfo.notes + "
";

	// Make a table storing general information about model
	output = "
General Information
";
	output += "Property	" + modelInfo.property + "	";
	output += "
Units	" + modelInfo.units + "	";
	output += "
Training Set	" + modelInfo.training + "	";
	output += "
Author	" + modelInfo.author + "	";
	output += "
Citation	" + modelInfo.citation + "	";

	outputDiv.innerHTML += output;

	// Print out model performance
	output = "
Model Performance
"
	output += "
Validation Method" + modelInfo.valMethod + "
"
	if (modelInfo.classifier) {
		output += "Accuracy" + (modelInfo.valScore.Accuracy * 100).toFixed(2) + "%"
		output += "
Kappa" + modelInfo.valScore.Kappa.toFixed(4)
		output += "
Sensitivity" + (modelInfo.valScore.Sensitivity * 100).toFixed(2) + "%"
		output += "
False Positive Rate" + (modelInfo.valScore.FPR * 100).toFixed(2) + "%"
		output += "
Area Under ROC" + modelInfo.valScore.ROCAUC.toFixed(4)
	} else {
		output += "R" + modelInfo.valScore.R.toFixed(4)
		output += "
ρ" + modelInfo.valScore.Rho.toFixed(4)
		output += "
τ" + modelInfo.valScore.Tau.toFixed(4)
		output += "
MAE" + modelInfo.valScore.MAE.toPrecision(3) + " " + modelInfo.units
		output += "
RMSE" + modelInfo.valScore.RMSE.toPrecision(3) + " " + modelInfo.units
		if (modelInfo.valScore.MRE != "NaN") {
			output += "
MRE" + (modelInfo.valScore.MRE * 100).toFixed(2) + "%"
		}
	}

	outputDiv.innerHTML += output

	// Print out model structure
	output = "
Model Structure
"
	output += "
"
	typeLines = modelInfo.modelType.split("\n")
	for (i in typeLines) {
		line = typeLines[i]

		words = line.split(" ")

		// Look for names of magpie classes
		for (j in words) {
			word = words[j]
			if (word.indexOf("magpie.") == 0) {
				words[j] = getDocReference(words[j])
			}
		}

		// Output line
		for (j in words) {
			output += " " + words[j]
		}

	}
	output += "
"

	outputDiv.innerHTML += output
}

var javadocURL = "http://oqmd.org/static/analytics/magpie/javadoc/"
/**
 * Get weblink to a certain magpie class
 * @param className [in] Full name of magpie class (should start with "magpie.")
 * @return Hyperlink to its documentation page
 */
function getDocReference(className) {
	return "" + className + ""
}
<|endoftext|>


<commit_before>
function comboBox()
{
    {{ RestStatConfig.extjs_model_class|safe }}
    var store = {{ RestStatConfig.get_extjs_store_object|safe }}
    var simpleCombo = Ext.create('Ext.form.field.ComboBox', {
        fieldLabel: 'Select statistics config',
        renderTo: 'simpleCombo',
        displayField: 'name',
        width: 400,
        labelWidth: 130,
        store: store,
        queryMode: 'local',
        typeAhead: true
    });
}

Ext.onReady(function() {
    comboBox();
});
<commit_msg>Some commentds<commit_after>
function comboBox()
{
    // Get the extjs model generated from the datamodel
    {{ RestStatConfig.extjs_model_class|safe }}

    // Get the extjs store generated from the rest config
    var store = {{ RestStatConfig.get_extjs_store_object|safe }}

    // Use them to create a simple combobox.
    var simpleCombo = Ext.create('Ext.form.field.ComboBox', {
        fieldLabel: 'Select statistics config',
        renderTo: 'simpleCombo',
        displayField: 'name',
        width: 400,
        labelWidth: 130,
        store: store,
        queryMode: 'local',
        typeAhead: true
    });
}

Ext.onReady(function() {
    comboBox();
});
<|endoftext|>


<commit_before>var Check = require('../../models/check');
var request = require('request');
var moment = require('moment');
var fs = require('fs');
var ejs = require('ejs');
var config = require('config');
var _ = require('underscore');

var template = fs.readFileSync(__dirname + '/views/_detailsEdit.ejs', 'utf8');
var api_key = config.geckoboard.api_key;
var reporting_interval = config.geckoboard.reporting_interval * 1000;

function reportStatus(url, status, responseTime, lastDownTimestamp) {
  var statusMessage = status ? "Up" : "Down";
  var downtimeMessage;
  if (lastDownTimestamp) {
    downtimeMessage = moment(lastDownTimestamp).format("MMMM D, h:mma");
  }
  var postData = {
    status: statusMessage,
    responseTime: Math.round(responseTime) + "ms",
    downTime: downtimeMessage
  };
  postToGeckoboard(url, postData);
}

function reportAvailability(url, availability) {
  var postData = {
    item: [{ text: "(30 days)", value: availability, prefix: "%" }]
  };
  postToGeckoboard(url, postData);
}

function postToGeckoboard(url, postData) {
  var postObj = { api_key: api_key, data: postData };
  console.log("Posting to geckoboard", url, JSON.stringify(postData));
  request.post(url, { json: true, body: postObj }, function(err,httpResponse,body){
    if (!err && httpResponse.statusCode !== 200) {
      console.error("Posting data to geckoboard failed");
      if (err) {
        console.err(err);
      } else {
        console.log("Got reponse code " + httpResponse.statusCode);
        console.log(body);
      }
    } else {
      console.log("geckoboard request succeeded");
    }
  });
}

exports.initMonitor = function() {
  setInterval(function(){
    Check.find().exec(function(err, checks){
      if (!err) return;
      _.each(checks, function(check) {
        var geckoboardOptions = check.getPollerParam("geckoboard_options");
        if (!geckoboardOptions) return;
        var availabilityUrl = geckoboardOptions.availability_url;
        if (availabilityUrl) {
          var monthAgo = moment().subtract(30, 'days').toDate();;
          var now = new Date();
          check.getAvailabilityInInterval(monthAgo, now, function(err, data){
            if (err) return;
            reportAvailability(availabilityUrl, data.availability*100);
          });
        }
        var statusUrl = geckoboardOptions.status_url;
        if (statusUrl && check.qos) {
          var outages = check.qos.outages;
          var lastDowntime, lastDowntimestamp;
          if (outages && geckoboardOptions.send_last_downtime) {
            lastDowntime = check.qos.outages[check.qos.outages.length-1];
            lastDowntimestamp = lastDowntime[2] === 0 ? lastDowntime[0] : null;
          }
          reportStatus(statusUrl, check.isUp, check.qos.responseTime, lastDowntimestamp);
        }
      });
    });
  }, reporting_interval);
};

exports.initWebApp = function(options) {
  var dashboard = options.dashboard;

  dashboard.on('checkEdit', function(type, check, partial) {
    var statusUrl = '';
    var availabilityUrl = '';
    var geckoboard_options = check.getPollerParam("geckoboard_options") || {};
    partial.push(ejs.render(template, { locals: { check: check, geckoboard_options: geckoboard_options } }));
  });

  dashboard.on('populateFromDirtyCheck', function(checkDocument, dirtyCheck, type) {
    if (!dirtyCheck.geckoboard_options) return;
    checkDocument.setPollerParam('geckoboard_options', dirtyCheck.geckoboard_options);
  });
};
<commit_msg>rm unused variables<commit_after>var Check = require('../../models/check');
var request = require('request');
var moment = require('moment');
var fs = require('fs');
var ejs = require('ejs');
var config = require('config');
var _ = require('underscore');

var template = fs.readFileSync(__dirname + '/views/_detailsEdit.ejs', 'utf8');
var api_key = config.geckoboard.api_key;
var reporting_interval = config.geckoboard.reporting_interval * 1000;

function reportStatus(url, status, responseTime, lastDownTimestamp) {
  var statusMessage = status ? "Up" : "Down";
  var downtimeMessage;
  if (lastDownTimestamp) {
    downtimeMessage = moment(lastDownTimestamp).format("MMMM D, h:mma");
  }
  var postData = {
    status: statusMessage,
    responseTime: Math.round(responseTime) + "ms",
    downTime: downtimeMessage
  };
  postToGeckoboard(url, postData);
}

function reportAvailability(url, availability) {
  var postData = {
    item: [{ text: "(30 days)", value: availability, prefix: "%" }]
  };
  postToGeckoboard(url, postData);
}

function postToGeckoboard(url, postData) {
  var postObj = { api_key: api_key, data: postData };
  console.log("Posting to geckoboard", url, JSON.stringify(postData));
  request.post(url, { json: true, body: postObj }, function(err,httpResponse,body){
    if (!err && httpResponse.statusCode !== 200) {
      console.error("Posting data to geckoboard failed");
      if (err) {
        console.err(err);
      } else {
        console.log("Got reponse code " + httpResponse.statusCode);
        console.log(body);
      }
    } else {
      console.log("geckoboard request succeeded");
    }
  });
}

exports.initMonitor = function() {
  setInterval(function(){
    Check.find().exec(function(err, checks){
      if (!err) return;
      _.each(checks, function(check) {
        var geckoboardOptions = check.getPollerParam("geckoboard_options");
        if (!geckoboardOptions) return;
        var availabilityUrl = geckoboardOptions.availability_url;
        if (availabilityUrl) {
          var monthAgo = moment().subtract(30, 'days').toDate();;
          var now = new Date();
          check.getAvailabilityInInterval(monthAgo, now, function(err, data){
            if (err) return;
            reportAvailability(availabilityUrl, data.availability*100);
          });
        }
        var statusUrl = geckoboardOptions.status_url;
        if (statusUrl && check.qos) {
          var outages = check.qos.outages;
          var lastDowntime, lastDowntimestamp;
          if (outages && geckoboardOptions.send_last_downtime) {
            lastDowntime = check.qos.outages[check.qos.outages.length-1];
            lastDowntimestamp = lastDowntime[2] === 0 ? lastDowntime[0] : null;
          }
          reportStatus(statusUrl, check.isUp, check.qos.responseTime, lastDowntimestamp);
        }
      });
    });
  }, reporting_interval);
};

exports.initWebApp = function(options) {
  var dashboard = options.dashboard;

  dashboard.on('checkEdit', function(type, check, partial) {
    var geckoboard_options = check.getPollerParam("geckoboard_options") || {};
    partial.push(ejs.render(template, { locals: { check: check, geckoboard_options: geckoboard_options } }));
  });

  dashboard.on('populateFromDirtyCheck', function(checkDocument, dirtyCheck, type) {
    if (!dirtyCheck.geckoboard_options) return;
    checkDocument.setPollerParam('geckoboard_options', dirtyCheck.geckoboard_options);
  });
};
<|endoftext|>


<commit_before>describe('Testing source controller', function () {
    var controller, scope, configService, deferred, $q, httpBackend;

    var windowMock = {
        alert: function(message) {},
        confirm: function(message) {}
    };

    var modalInstance = { open: function() {} };

    beforeEach(function () {
        // load the module
        module('sourceApp', function ($provide) {
            $provide.value('$window', windowMock);
        });

        spyOn(windowMock, 'alert');

        inject(function($controller, $rootScope, _$q_, _configService_, _$httpBackend_){
            scope = $rootScope.$new();
            $q = _$q_;
            httpBackend = _$httpBackend_;
            configService = _configService_;

            deferred = _$q_.defer();
            spyOn(configService, "getConfig").and.returnValue(deferred.promise);
            spyOn(configService, "removeConfig").and.returnValue(deferred.promise);

            controller = $controller('SourceCtrl', {
                $scope: scope,
                configService: configService,
                $uibModal : modalInstance
            });
        });
    });

    it('should define the source controller', function() {
        expect(controller).toBeDefined();
    });

    it('should define the function submit()', function(){
        expect(controller.submit).toBeDefined();
    });

    it('should define the function upload()', function(){
        expect(controller.upload).toBeDefined();
    });

    it('should call the service to get configuration list', function() {
        var result = [{
            mission: "ATest",
            source: {
                filename: "GMAT-6.xlsx",
                ipaddress: "10.0.0.16",
                name: "GMAT"
            }
        }]
        deferred.resolve({ data : result });

        // We have to call digest cycle for this to work
        scope.$digest();

        expect(configService.getConfig).toHaveBeenCalled();
        expect(controller.configlist).toBeDefined();
        expect(controller.configlist).toEqual(result);
    });

    it('should call the upload function when upload form is valid', function(){
        var args = {
            name
:
 "SIM.xlsx"
        };

        controller.upload_form = {
            $valid: true
        };

        controller.config = {
            file: {
                name
:
 "SIM.xlsx"
            },
            mission: "ATest",
            sourceip
:
 "10.0.0.14"
,
            sourcename
:
 "GMAT"

        };

        spyOn(controller, "upload");

        controller.submit();
        expect(controller.upload).toHaveBeenCalled();
        expect(controller.upload).toHaveBeenCalledWith(args);
    });

    it('should alert the user when upload form is valid but the file property does not exist', function(){
        controller.upload_form = {
            $valid: true
        };

        controller.config = {
            mission: "ATest",
            sourceip
:
 "10.0.0.14"
,
            sourcename
:
 "GMAT"

        }

        controller.submit();
        expect(windowMock.alert).toHaveBeenCalledWith('No file passed. Please upload an xlsx file.');
    });

    it('should upload file when upload() is called and successfully alert the user', function(){
        controller.upload_form = {
            $valid: true,
            $setPristine : function(){}
        };
        controller.config = {
            file: {
                name
:
 "SIM.xlsx"
            },
            mission: "ATest",
            sourceip
:
 "10.0.0.14"
,
            sourcename
:
 "GMAT"

        };

        var response = {
            data : {
                status : "ok",
                message : "Configuration data saved successfully for 10.0.0.14"
            }
        }

        var mockFile = {
            "name": "SIM.xlsx",
            "size": 10759,
            "type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        };

        httpBackend.when('POST', '/upload').respond(200, response);
        controller.upload(mockFile);
        httpBackend.flush();

        expect(windowMock.alert).toHaveBeenCalledWith('Configuration data saved successfully for 10.0.0.14');
        expect(controller.config).toEqual({});
    });

    it('should alert user on upload file error(invalid file)', function(){
        controller.config = {
            file: {
                name
:
 "SIM.xlsx"
            },
            mission: "ATest",
            sourceip
:
 "10.0.0.14"
,
            sourcename
:
 "GMAT"

        };

        var response = {
            data : {
                status : "error",
                message : "Invalid File"
            }
        }

        var mockFile = {
            "name": "SIM.xlsx",
            "size": 10759,
            "type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        };

        httpBackend.when('POST', '/upload').respond(200, response);
        controller.upload(mockFile);
        httpBackend.flush();
        expect(windowMock.alert).toHaveBeenCalledWith('Invalid File');
    });

    it('should remove file from list when it is deleted', function(){
        spyOn(windowMock, 'confirm').and.returnValue(true);
        var result = {
            'message' : 'Configuration deleted successfully'
        }

        deferred.resolve({ data : result });
        controller.removeConfig("100.100.100.100");

        expect(configService.removeConfig).toHaveBeenCalledWith("100.100.100.100");
    });

    it('should not remove file from list when the user does not confirm to delete', function(){
        spyOn(windowMock, 'confirm').and.returnValue(false);

        controller.removeConfig("100.100.100.100");
        expect(configService.removeConfig).not.toHaveBeenCalled();
    });

    it('should call showModal function on click on attachment svg', function() {
        var fakeModal = {
            result: {
                then: function(cancelCallback) {
                    //Store the callbacks for later when the user clicks on the Cancel button of the dialog
                    this.cancelCallback = cancelCallback;
                }
            }
        };

        var modalResult = {};
        var mockModalInstance = { result: $q.resolve(modalResult) };
        spyOn(mockModalInstance.result, 'then').and.callThrough();
        spyOn(modalInstance, 'open').and.returnValue(mockModalInstance);

        controller.showModal();
        scope.$digest();
        expect(modalInstance.open).toHaveBeenCalled();
    });

});
<commit_msg>added response in test cases<commit_after>describe('Testing source controller', function () {
    var controller, scope, configService, deferred, $q, httpBackend;

    var windowMock = {
        alert: function(message) {},
        confirm: function(message) {}
    };

    var modalInstance = { open: function() {} };

    beforeEach(function () {
        // load the module
        module('sourceApp', function ($provide) {
            $provide.value('$window', windowMock);
        });

        spyOn(windowMock, 'alert');

        inject(function($controller, $rootScope, _$q_, _configService_, _$httpBackend_){
            scope = $rootScope.$new();
            $q = _$q_;
            httpBackend = _$httpBackend_;
            configService = _configService_;

            deferred = _$q_.defer();
            spyOn(configService, "getConfig").and.returnValue(deferred.promise);
            spyOn(configService, "removeConfig").and.returnValue(deferred.promise);

            controller = $controller('SourceCtrl', {
                $scope: scope,
                configService: configService,
                $uibModal : modalInstance
            });
        });
    });

    it('should define the source controller', function() {
        expect(controller).toBeDefined();
    });

    it('should define the function submit()', function(){
        expect(controller.submit).toBeDefined();
    });

    it('should define the function upload()', function(){
        expect(controller.upload).toBeDefined();
    });

    it('should call the service to get configuration list', function() {
        var result = [{
            mission: "ATest",
            source: {
                filename: "GMAT-6.xlsx",
                ipaddress: "10.0.0.16",
                name: "GMAT"
            }
        }]
        deferred.resolve({ data : result });

        // We have to call digest cycle for this to work
        scope.$digest();

        expect(configService.getConfig).toHaveBeenCalled();
        expect(controller.configlist).toBeDefined();
        expect(controller.configlist).toEqual(result);
    });

    it('should call the upload function when upload form is valid', function(){
        var args = {
            name
:
 "SIM.xlsx"
        };

        controller.upload_form = {
            $valid: true
        };

        controller.config = {
            file: {
                name
:
 "SIM.xlsx"
            },
            mission: "ATest",
            sourceip
:
 "10.0.0.14"
,
            sourcename
:
 "GMAT"

        };

        spyOn(controller, "upload");

        controller.submit();
        expect(controller.upload).toHaveBeenCalled();
        expect(controller.upload).toHaveBeenCalledWith(args);
    });

    it('should alert the user when upload form is valid but the file property does not exist', function(){
        controller.upload_form = {
            $valid: true
        };

        controller.config = {
            mission: "ATest",
            sourceip
:
 "10.0.0.14"
,
            sourcename
:
 "GMAT"

        }

        controller.submit();
        expect(windowMock.alert).toHaveBeenCalledWith('No file passed. Please upload an xlsx file.');
    });

    it('should upload file when upload() is called and successfully alert the user', function(){
        controller.upload_form = {
            $valid: true,
            $setPristine : function(){}
        };
        controller.config = {
            file: {
                name
:
 "SIM.xlsx"
            },
            mission: "ATest",
            sourceip
:
 "10.0.0.14"
,
            sourcename
:
 "GMAT"

        };

        var response = {
            status : "ok",
            message : "Configuration data saved successfully for 10.0.0.14"
        }

        var mockFile = {
            "name": "SIM.xlsx",
            "size": 10759,
            "type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        };

        httpBackend.when('POST', '/upload').respond(200, response);
        controller.upload(mockFile);
        httpBackend.flush();

        expect(windowMock.alert).toHaveBeenCalledWith('Configuration data saved successfully for 10.0.0.14');
        expect(controller.config).toEqual({});
    });

    it('should alert user on upload file error(invalid file)', function(){
        controller.config = {
            file: {
                name
:
 "SIM.xlsx"
            },
            mission: "ATest",
            sourceip
:
 "10.0.0.14"
,
            sourcename
:
 "GMAT"

        };

        var response = {
            status : "error",
            message : "Invalid File"
        }

        var mockFile = {
            "name": "SIM.xlsx",
            "size": 10759,
            "type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        };

        httpBackend.when('POST', '/upload').respond(200, response);
        controller.upload(mockFile);
        httpBackend.flush();
        expect(windowMock.alert).toHaveBeenCalledWith('Invalid File');
    });

    it('should remove file from list when it is deleted', function(){
        spyOn(windowMock, 'confirm').and.returnValue(true);
        var result = {
            'message' : 'Configuration deleted successfully'
        }

        deferred.resolve({ data : result });
        controller.removeConfig("100.100.100.100");

        expect(configService.removeConfig).toHaveBeenCalledWith("100.100.100.100");
    });

    it('should not remove file from list when the user does not confirm to delete', function(){
        spyOn(windowMock, 'confirm').and.returnValue(false);

        controller.removeConfig("100.100.100.100");
        expect(configService.removeConfig).not.toHaveBeenCalled();
    });

    it('should call showModal function on click on attachment svg', function() {
        var fakeModal = {
            result: {
                then: function(cancelCallback) {
                    //Store the callbacks for later when the user clicks on the Cancel button of the dialog
                    this.cancelCallback = cancelCallback;
                }
            }
        };

        var modalResult = {};
        var mockModalInstance = { result: $q.resolve(modalResult) };
        spyOn(mockModalInstance.result, 'then').and.callThrough();
        spyOn(modalInstance, 'open').and.returnValue(mockModalInstance);

        controller.showModal();
        scope.$digest();
        expect(modalInstance.open).toHaveBeenCalled();
    });

});
<|endoftext|>


<commit_before>/*
	Copyright (c) 2010-2012 Filip Moberg, (filip@mcsquare.se)

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	Author:		Filip Moberg
	Name:		inception.js
	Version:	1.2
	Codename:	Di Caprio
	Released:	2012-01-03
	Comments:	This version was so awesome, it deserved TWO new version numbers. Totally rebuilt from scratch - inception revisited.
*/

// Sandbox the environment
/** @param {...undefined} undefined */
(function(window, undefined) {

	// Declare environment variables
	var document = window.document, navigator = window.navigator, location = window.location;

	// Create function in window object
	/** @constructor */
	window.inception = (function inception(oo) {

		var env = this;
		var self = this;
		var core = env.__core__;

		// Make sure core function is instantiated
		if (this === window) {
			return new inception(arguments[0]);
		}

		// Declare core object (with core functions)
		this.__core__ = {

			settings: {
				jQuery: {
					ready: "document"
				},
				error: {
					show: true
				}
			},

			onload: [],

			instance: arguments[0],

			// Extend a primary object with a secondary
			extend: function(o) {

				// If set to true, the returned object will be a copy instead of reference
				if (o.clone === true) {
					o.from = this.clone(o.from);
				}

				for (var n in o.from) {
					if (o.construct === true && typeof o.from[n] === "function" && n !== "wrapper") {

						// Make a clone so the use of multiple selectors won't construct the same function twice
						o.from = this.clone(o.from);
						var core = env.__core__, node = [core.instance].concat(o.node.replace(/@/g, "").split(".")), wrapper = node[0], cache;
						o.wrapper = [];

						cache = core.wrapper.cache[core.instance];

						if (typeof cache === "function") {
							o.wrapper.push(cache);
						}

						for (var i=1; i < node.length; ++i) {
							wrapper = wrapper + "__" + node[i];
							cache = core.wrapper.cache[wrapper];
							if (typeof cache === "function") {
								o.wrapper.push(cache);
							}
						}

						for (var i=o.wrapper.length; i >= 0; --i) {

							// Construct the function
							o.from[n] = this.functionConstructor({method: o.from[n], func: n, node: o.node, loop: o.loop, wrapper: o.wrapper[i]});
						}
					}

					if (typeof o.from[n] === "object" && n !== "selector" && n !== "$") {

						if (typeof o.to[n] === "undefined") {
							if (o.from[n] === null) {
								o.to[n] = null;
							} else if (o.from[n].constructor.toString().indexOf("Array") !== -1) {
								o.to[n] = [];
							} else {
								o.to[n] = {};
							}
						}

						this.extend({to: o.to[n], from: o.from[n], construct: o.construct, node: o.node, loop: o.loop});
					} else {
						o.to[n] = o.from[n];
					}
				}

				return o.to;
			},

			// Create deep copy of target object
			clone: function() {
				return this.extend({to: {}, from: arguments[0]});
			},

			// Count child objects
			count : function(o) {

				var c = 0, i;

				for (i in o) {
					if (o.hasOwnProperty(o)) {
						++c;
					}
				}

				return c;
			},

			// Create object from node string
			stringToObject: function() {

				var selector = arguments[0].replace(/ /g, "").split("@").slice(1), a = [], s, o, i, node, shell;

				for (s in selector) {
					node = selector[s].split(".");

					if (node[0] !== "") {
						o = {};
						shell = o;

						for (i = 0; i < node.length-1; ++i) {
							o = o[node[i]] = {};
						}

						if (arguments[1]) {
							o = o[node[i]] = arguments[1];
						} else {
							o = o[node[i]] = {};
						}

						a.push(shell);
					}
				}

				return a;
			},

			// Create selector from node string
			stringToSelector: function() {
				var a = [], n = this.stringToArray(arguments[0]), i, x;

				for (i in n) {
					var s = n[i].split(".");
					var node = env;

					for (x in s) {
						if (typeof node[s[x]] !== "undefined") {
							node = node[s[x]];
						}
					}

					if (node !== env) {
						a.push(node);
					}
				}

				return a;
			},

			// Create array from node string
			stringToArray: function() {
				return arguments[0].replace(/ /g, "").split("@").slice(1);
			},

			// Wrapper engine. Used for fetching stored wrappers in runtime.
			wrapper: {
				cache: {
				},

				get: function(o) {
					var wrapper, core = env.__core__, node = [core.instance].concat(o.node.replace(/@/g, "").split(".")), n, i;

					for (i in node) {
						if (!n) {
							n = node[i];
						} else {
							n = n + "__" + node[i];
						}
						if (typeof core.wrapper.cache[n] === "function") {
							wrapper = core.wrapper.cache[n];
						}
					}
					return wrapper;
				}
			},

			// Construct user function(s)
			functionConstructor: function(o) {

				var self = this;
				var core = env.__core__;

				switch(o.func) {

					// If function is an onReady function and it's the first node selector, load it into jQuery ready - else, load it straight after the window object.
					case "onReady":
						if (o.loop === "0" && typeof o.method !== "undefined") {

							if (typeof window.jQuery === "function") {

								window.jQuery(window[core.settings.jQuery.ready]).ready(function() {

									// Call method with its parent object as reference
									o.method.call(window[self.instance][o.node]);
								});

							} else {

								this.onload.push(o.method);

								window.onload = function() {
									for (o in self.onload) {

										// Call method with its parent object as reference
										self.onload[o].call(window[self.instance][o.node]);
									}
								}
							}
						}
						break;

					// Construct function as ordinary
					default:
						return function() {

							if (typeof this[o.func] === "function") {

								// Set up selector
								this[o.func].selector = this[o.func].$ = core.selector;

								// Set up selector (for new methods, if the current method is used as a constructor)
								this[o.func].prototype.selector = this[o.func].prototype.$ = core.selector;

								// Set up node
								this[o.func].node = core.clone(core.node);

								// This line is for legacy purposes only (where the selector is called from the global object)
								window[core.instance].$ = window[core.instance].selector = core.selector;
							}

							// Execute user function in correct environment
							if (typeof o.wrapper === "function") {
								var self = this;
								var args = arguments;

								// Execute user function inside wrappers (if available)
								return o.wrapper.call({
									call: function() {

										// Apply method with its parent object as reference
										return o.method.apply(self, args);
									}
								});
							} else {
								// Execute user function as ordinary (if there are no wrappers defined for this object)
								return o.method.apply(this, arguments);
							}
						};

						break;
				}

			},

			// Error handling
			error: function() {
				var core = env.__core__;

				if (core.settings.error.show === true) {
					throw new Error(arguments[0]);
				}
				return
			}
		};

		// Make the global object a reference to the instance function and return it
		/** @constructor */
		return new (window[arguments[0]] = function() {

			var extended, core = env.__core__;

			// Extend core object with instance object internally
			// Declare user functions and variables
			extended = core.extend({to: env, from: {

				// Default node and selector values
				__core__: {
					node: {
						getString: "",
						getArray: []
					},
					selector: []
				},

				// Extend selected node(s) with given object/function
				extend: function() {
					var shell, s = [], node;

					// Error on invalid node selector
					if (typeof core.node.getArray[0] === "undefined") {
						return core.error("inception.js: Trying to extend with invalid node selector.");
					}

					// Error on false input object
					if (typeof arguments[0] === "undefined") {
						return core.error("inception.js: Trying to extend with invalid input object.");
					}

					// Create shell object of selector node(s)
					shell = core.stringToObject(core.node.getString, arguments[0]);

					// Match shell with node array
					node = core.node.getArray;

					// Iterate over shell and extend each node
					for (var i in shell) {
						core.extend({to: this, from: shell[i], construct: true, node: node[i], loop: i});
						s.push(shell[i]);
					}

					// Extend up to the global object
					window[core.instance] = core.extend({to: window[core.instance], from: this});

					// Return inception object
					return env;
				},

				// Create a new instance and extend with a copy of selected objects
				clone: function() {

					var name = [], arg = arguments[0], i;

					if (arg) {
						name.push(arg);
					} else {
						name = core.node.getArray;
					}

					for (i in name) {
						// Create a new instance
						new inception(name[i]);

						// Extend with core object
						core.extend({to: window[name[i]], from: core.clone(env)});

						// Extend with inner object
						core.extend({to: window[name[i]](), from: core.clone(env)});
					}

					return env;
				},

				// Crate a wrapper that sticks to a specified node, and then wraps the calling function with itself.
				wrap: function() {

					var a, i;

					if (typeof arguments[0] === "function") {

						a = core.node.getString.replace(/\./g, "__").replace(/ /g, "").split("@").slice(1);

						if (a.length === 0) {

							// Set wrapper cache
							core.wrapper.cache[core.instance] = arguments[0];
						}

						for (i in a) {

							// Set wrapper cache
							core.wrapper.cache[core.instance + "__" + a[i]] = arguments[0];

							// Extend to core object
							core.extend({to: window[core.instance].__core__.wrapper, from: core.wrapper});
						}
					}

					return env;
				},

				// Used to read and set new environment settings
				settings: function() {
					var core = env.__core__, settings = arguments[0];

					return core.extend({to: core.settings, from: settings});
				},

				// a DOM helper, to easily create new elements through jQuery. This actually is more of a jQuery plugin, but it's often useful - so I included it.
				append: function() {
					var core = env.__core__, o = arguments[0], jQuery = window.jQuery;

					// Faster than jQueries append, but lets you pass through css, bind and attribute objects to jQuery.
					if (typeof window.jQuery === "function") {
						return core.$.each(function() {

							if (o.element) {
								var obj = document.createElement(o.element);
								this.appendChild(obj);
							}

							if (o.css) {
								jQuery(obj).css(o.css);
							}

							if (o.attr) {
								jQuery(obj).attr(o.attr);
							}

							if (o.bind) {
								for (var k in o.bind) {
									jQuery(obj).bind(k, o.bind[k]);
								}
							}
						});
					}

					return env;
				}
			}});

			// Extend up to the global object
			window[core.instance] = core.extend({to: window[core.instance], from: extended});

			// Append correct selector
			if (typeof arguments[0] === "string" && arguments[0].indexOf("@") !== -1) {

				// Set selector to an inception selector
				core.$ = core.selector = core.stringToSelector(arguments[0]);

				// Save original selector string
				core.node.getString = arguments[0];
				core.node.getArray = core.stringToArray(arguments[0]);

			} else if (typeof window.jQuery === "function") {

				// Set selector to a jQuery selector (if it's not an inception selector and if jQuery is present)
				core.$ = core.selector = window.jQuery(arguments[0]);
			} else {

				// Clear all old selectors
				core.node.getString = "";
				core.node.getArray = "";
				core.$ = core.selector = [];
			}

			// Return extended core object
			return extended;
		});
	});

})(window);
<commit_msg>Added support for native querySelector. Waiting for web to drop IE7 before removing jQuery support.<commit_after>/*
	Copyright (c) 2010-2012 Filip Moberg, (filip@mcsquare.se)

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	Author:		Filip Moberg
	Name:		inception.js
	Version:	1.2
	Codename:	Di Caprio
	Released:	2012-01-03
	Comments:	This version was so awesome, it deserved TWO new version numbers. Totally rebuilt from scratch - inception revisited.
*/

// Sandbox the environment
/** @param {...undefined} undefined */
(function(window, undefined) {

	// Declare environment variables
	var document = window.document, navigator = window.navigator, location = window.location;

	// Create function in window object
	/** @constructor */
	window.inception = (function inception(oo) {

		var env = this;
		var self = this;
		var core = env.__core__;

		// Make sure core function is instantiated
		if (this === window) {
			return new inception(arguments[0]);
		}

		// Declare core object (with core functions)
		this.__core__ = {

			settings: {
				jQuery: {
					ready: "document"
				},
				error: {
					show: true
				}
			},

			onload: [],

			instance: arguments[0],

			// Extend a primary object with a secondary
			extend: function(o) {

				// If set to true, the returned object will be a copy instead of reference
				if (o.clone === true) {
					o.from = this.clone(o.from);
				}

				for (var n in o.from) {
					if (o.construct === true && typeof o.from[n] === "function" && n !== "wrapper") {

						// Make a clone so the use of multiple selectors won't construct the same function twice
						o.from = this.clone(o.from);
						var core = env.__core__, node = [core.instance].concat(o.node.replace(/@/g, "").split(".")), wrapper = node[0], cache;
						o.wrapper = [];

						cache = core.wrapper.cache[core.instance];

						if (typeof cache === "function") {
							o.wrapper.push(cache);
						}

						for (var i=1; i < node.length; ++i) {
							wrapper = wrapper + "__" + node[i];
							cache = core.wrapper.cache[wrapper];
							if (typeof cache === "function") {
								o.wrapper.push(cache);
							}
						}

						for (var i=o.wrapper.length; i >= 0; --i) {

							// Construct the function
							o.from[n] = this.functionConstructor({method: o.from[n], func: n, node: o.node, loop: o.loop, wrapper: o.wrapper[i]});
						}
					}

					if (typeof o.from[n] === "object" && n !== "selector" && n !== "$") {

						if (typeof o.to[n] === "undefined") {
							if (o.from[n] === null) {
								o.to[n] = null;
							} else if (o.from[n].constructor.toString().indexOf("Array") !== -1) {
								o.to[n] = [];
							} else {
								o.to[n] = {};
							}
						}

						this.extend({to: o.to[n], from: o.from[n], construct: o.construct, node: o.node, loop: o.loop});
					} else {
						o.to[n] = o.from[n];
					}
				}

				return o.to;
			},

			// Create deep copy of target object
			clone: function() {
				return this.extend({to: {}, from: arguments[0]});
			},

			// Count child objects
			count : function(o) {

				var c = 0, i;

				for (i in o) {
					if (o.hasOwnProperty(o)) {
						++c;
					}
				}

				return c;
			},

			// Create object from node string
			stringToObject: function() {

				var selector = arguments[0].replace(/ /g, "").split("@").slice(1), a = [], s, o, i, node, shell;

				for (s in selector) {
					node = selector[s].split(".");

					if (node[0] !== "") {
						o = {};
						shell = o;

						for (i = 0; i < node.length-1; ++i) {
							o = o[node[i]] = {};
						}

						if (arguments[1]) {
							o = o[node[i]] = arguments[1];
						} else {
							o = o[node[i]] = {};
						}

						a.push(shell);
					}
				}

				return a;
			},

			// Create selector from node string
			stringToSelector: function() {
				var a = [], n = this.stringToArray(arguments[0]), i, x;

				for (i in n) {
					var s = n[i].split(".");
					var node = env;

					for (x in s) {
						if (typeof node[s[x]] !== "undefined") {
							node = node[s[x]];
						}
					}

					if (node !== env) {
						a.push(node);
					}
				}

				return a;
			},

			// Create array from node string
			stringToArray: function() {
				return arguments[0].replace(/ /g, "").split("@").slice(1);
			},

			// Wrapper engine. Used for fetching stored wrappers in runtime.
			wrapper: {
				cache: {
				},

				get: function(o) {
					var wrapper, core = env.__core__, node = [core.instance].concat(o.node.replace(/@/g, "").split(".")), n, i;

					for (i in node) {
						if (!n) {
							n = node[i];
						} else {
							n = n + "__" + node[i];
						}
						if (typeof core.wrapper.cache[n] === "function") {
							wrapper = core.wrapper.cache[n];
						}
					}
					return wrapper;
				}
			},

			// Construct user function(s)
			functionConstructor: function(o) {

				var self = this;
				var core = env.__core__;

				switch(o.func) {

					// If function is an onReady function and it's the first node selector, load it into jQuery ready - else, load it straight after the window object.
					case "onReady":
						if (o.loop === "0" && typeof o.method !== "undefined") {

							if (typeof window.jQuery === "function") {

								window.jQuery(window[core.settings.jQuery.ready]).ready(function() {

									// Call method with its parent object as reference
									o.method.call(window[self.instance][o.node]);
								});

							} else {

								this.onload.push(o.method);

								window.onload = function() {
									for (o in self.onload) {

										// Call method with its parent object as reference
										self.onload[o].call(window[self.instance][o.node]);
									}
								}
							}
						}
						break;

					// Construct function as ordinary
					default:
						return function() {

							if (typeof this[o.func] === "function") {

								// Set up selector
								this[o.func].selector = this[o.func].$ = core.selector;

								// Set up selector (for new methods, if the current method is used as a constructor)
								this[o.func].prototype.selector = this[o.func].prototype.$ = core.selector;

								// Set up node
								this[o.func].node = core.clone(core.node);

								// This line is for legacy purposes only (where the selector is called from the global object)
								window[core.instance].$ = window[core.instance].selector = core.selector;
							}

							// Execute user function in correct environment
							if (typeof o.wrapper === "function") {
								var self = this;
								var args = arguments;

								// Execute user function inside wrappers (if available)
								return o.wrapper.call({
									call: function() {

										// Apply method with its parent object as reference
										return o.method.apply(self, args);
									}
								});
							} else {
								// Execute user function as ordinary (if there are no wrappers defined for this object)
								return o.method.apply(this, arguments);
							}
						};

						break;
				}

			},

			// Error handling
			error: function() {
				var core = env.__core__;

				if (core.settings.error.show === true) {
					throw new Error(arguments[0]);
				}
				return
			}
		};

		// Make the global object a reference to the instance function and return it
		/** @constructor */
		return new (window[arguments[0]] = function() {

			var extended, core = env.__core__;

			// Extend core object with instance object internally
			// Declare user functions and variables
			extended = core.extend({to: env, from: {

				// Default node and selector values
				__core__: {
					node: {
						getString: "",
						getArray: []
					},
					selector: []
				},

				// Extend selected node(s) with given object/function
				extend: function() {
					var shell, s = [], node;

					// Error on invalid node selector
					if (typeof core.node.getArray[0] === "undefined") {
						return core.error("inception.js: Trying to extend with invalid node selector.");
					}

					// Error on false input object
					if (typeof arguments[0] === "undefined") {
						return core.error("inception.js: Trying to extend with invalid input object.");
					}

					// Create shell object of selector node(s)
					shell = core.stringToObject(core.node.getString, arguments[0]);

					// Match shell with node array
					node = core.node.getArray;

					// Iterate over shell and extend each node
					for (var i in shell) {
						core.extend({to: this, from: shell[i], construct: true, node: node[i], loop: i});
						s.push(shell[i]);
					}

					// Extend up to the global object
					window[core.instance] = core.extend({to: window[core.instance], from: this});

					// Return inception object
					return env;
				},

				// Create a new instance and extend with a copy of selected objects
				clone: function() {

					var name = [], arg = arguments[0], i;

					if (arg) {
						name.push(arg);
					} else {
						name = core.node.getArray;
					}

					for (i in name) {
						// Create a new instance
						new inception(name[i]);

						// Extend with core object
						core.extend({to: window[name[i]], from: core.clone(env)});

						// Extend with inner object
						core.extend({to: window[name[i]](), from: core.clone(env)});
					}

					return env;
				},

				// Crate a wrapper that sticks to a specified node, and then wraps the calling function with itself.
				wrap: function() {

					var a, i;

					if (typeof arguments[0] === "function") {

						a = core.node.getString.replace(/\./g, "__").replace(/ /g, "").split("@").slice(1);

						if (a.length === 0) {

							// Set wrapper cache
							core.wrapper.cache[core.instance] = arguments[0];
						}

						for (i in a) {

							// Set wrapper cache
							core.wrapper.cache[core.instance + "__" + a[i]] = arguments[0];

							// Extend to core object
							core.extend({to: window[core.instance].__core__.wrapper, from: core.wrapper});
						}
					}

					return env;
				},

				// Used to read and set new environment settings
				settings: function() {
					var core = env.__core__, settings = arguments[0];

					return core.extend({to: core.settings, from: settings});
				},

				// a DOM helper, to easily create new elements through jQuery. This actually is more of a jQuery plugin, but it's often useful - so I included it.
				append: function() {
					var core = env.__core__, o = arguments[0], jQuery = window.jQuery;

					// Faster than jQueries append, but lets you pass through css, bind and attribute objects to jQuery.
					if (typeof window.jQuery === "function") {
						return core.$.each(function() {

							if (o.element) {
								var obj = document.createElement(o.element);
								this.appendChild(obj);
							}

							if (o.css) {
								jQuery(obj).css(o.css);
							}

							if (o.attr) {
								jQuery(obj).attr(o.attr);
							}

							if (o.bind) {
								for (var k in o.bind) {
									jQuery(obj).bind(k, o.bind[k]);
								}
							}
						});
					}

					return env;
				}
			}});

			// Extend up to the global object
			window[core.instance] = core.extend({to: window[core.instance], from: extended});

			// Append correct selector
			if (typeof arguments[0] === "string" && arguments[0].indexOf("@") !== -1) {

				// Set selector to an inception selector
				core.$ = core.selector = core.stringToSelector(arguments[0]);

				// Save original selector string
				core.node.getString = arguments[0];
				core.node.getArray = core.stringToArray(arguments[0]);

			} else if (typeof window.jQuery === "function") {

				// Set selector to a jQuery selector (if it's not an inception selector and if jQuery is present)
				core.$ = core.selector = window.jQuery(arguments[0]);
			} else if (arguments[0]) {

				// Use native javascript CSS selector
				core.$ = core.selector = document.querySelectorAll(arguments[0]);
			} else {

				// Clear all old selectors
				core.node.getString = "";
				core.node.getArray = "";
				core.$ = core.selector = [];
			}

			// Return extended core object
			return extended;
		});
	});

})(window);
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var util = require('util');
var _ = require('@sailshq/lodash');
var Promise = require('bluebird');
var normalize = require('../normalize');

// Alias "catch" as "fail", for backwards compatibility with projects
// that were created using Q
//
// TODO: change this so it doesn't modify the global
Promise.prototype.fail = Promise.prototype.catch;

/**
 * Deferred Object
 *
 * Used for building up a Query
 */
var Deferred = module.exports = function(context, method, wlQueryInfo) {

  if (!context) {
    throw new Error('Must supply a context to a new Deferred object. Usage: new Deferred(context, fn, wlQueryInfo)');
  }
  if (!method) {
    throw new Error('Must supply a method to a new Deferred object. Usage: new Deferred(context, fn, wlQueryInfo)');
  }

  if (!wlQueryInfo) {
    throw new Error('Must supply a third arg (`wlQueryInfo`) to a new Deferred object. Usage: new Deferred(context, fn, wlQueryInfo)');
  }
  if (!_.isObject(wlQueryInfo)) {
    throw new Error('Third arg (`wlQueryInfo`) must be a valid dictionary. Usage: new Deferred(context, fn, wlQueryInfo)');
  }

  this._context = context;
  this._method = method;

  // Make sure `_wlQueryInfo` is always a dictionary.
  this._wlQueryInfo = wlQueryInfo || {};

  // Make sure `_wlQueryInfo.criteria` is always a dictionary
  this._wlQueryInfo.criteria = this._wlQueryInfo.criteria || {};

  // Attach `_wlQueryInfo.using` and set it equal to the model identity.
  // TODO

  // Make sure `._wlQueryInfo.values` is `null`, rather than simply undefined or any other falsey thing..
  // (This is just for backwards compatibility.  Could be removed if proven that it's safe.)
  this._wlQueryInfo.values = this._wlQueryInfo.values || null;

  // Initialize `_deferred` to `null`.
  // (this is used for promises)
  this._deferred = null;

  return this;
};

/**
 * Populate all associations of a collection.
 *
 * @return this
 * @chainable
 */
Deferred.prototype.populateAll = function(criteria) {
  var self = this;
  this._context.associations.forEach(function(association) {
    self.populate(association.alias, criteria);
  });
  return this;
};

/**
 * Add a `joins` clause to the criteria object.
 *
 * Used for populating associations.
 *
 * @param {String|Array} key, the key to populate or array of string keys
 * @return this
 * @chainable
 */

Deferred.prototype.populate = function(keyName, criteria) {
  var self = this;

  // Adds support for arrays into keyName so that a list of
  // populates can be passed
  if (_.isArray(keyName)) {
    _.each(keyName, function(populate) {
      self.populate(populate, criteria);
    });
    return this;
  }

  this._wlQueryInfo.criteria.populates = this._wlQueryInfo.criteria.populates || {};
  this._wlQueryInfo.criteria.populates[keyName] = criteria || {};

  return this;
};

/**
 * Add projections to the parent
 *
 * @param {Array} attributes to select
 * @return this
 */

Deferred.prototype.select = function(attributes) {
  if(!_.isArray(attributes)) {
    attributes = [attributes];
  }

  var select = this._wlQueryInfo.criteria.select || [];
  select = select.concat(attributes);
  this._wlQueryInfo.criteria.select = _.uniq(select);

  return this;
};

Deferred.prototype.omit = function(attributes) {
  if(!_.isArray(attributes)) {
    attributes = [attributes];
  }

  var omit = this._wlQueryInfo.criteria.omit || [];
  omit = omit.concat(attributes);
  this._wlQueryInfo.criteria.omit = _.uniq(omit);

  return this;
};

/**
 * Add a Where clause to the criteria object
 *
 * @param {Object} criteria to append
 * @return this
 */

Deferred.prototype.where = function(criteria) {

  if (!criteria) {
    return this;
  }

  if (!_.has(this._wlQueryInfo, 'criteria')) {
    this._wlQueryInfo.criteria = {};
  }

  var where = this._wlQueryInfo.criteria.where || {};

  // Merge with existing WHERE clause
  this._wlQueryInfo.criteria.where = _.merge({}, where, criteria);

  return this;
};

/**
 * Add a Limit clause to the criteria object
 *
 * @param {Integer} number to limit
 * @return this
 */

Deferred.prototype.limit = function(limit) {
  this._wlQueryInfo.criteria.limit = limit;

  return this;
};

/**
 * Add a Skip clause to the criteria object
 *
 * @param {Integer} number to skip
 * @return this
 */

Deferred.prototype.skip = function(skip) {
  this._wlQueryInfo.criteria.skip = skip;

  return this;
};

/**
 * Add a Paginate clause to the criteria object
 *
 * This is syntatical sugar that calls skip and
 * limit from a single function.
 *
 * @param {Object} page and limit
 * @return this
 */
Deferred.prototype.paginate = function(options) {
  var defaultLimit = 10;

  if (_.isUndefined(options)) {
    options = { page: 0, limit: defaultLimit };
  }

  var page = options.page || 0;
  var limit = options.limit || defaultLimit;
  var skip = 0;

  if (page > 0 && limit === 0) {
    skip = page - 1;
  }

  if (page > 0 && limit > 0) {
    skip = (page * limit) - limit;
  }

  this
  .skip(skip)
  .limit(limit);

  return this;
};

/**
 * Add a Sort clause to the criteria object
 *
 * @param {String|Object} key and order
 * @return this
 */

Deferred.prototype.sort = function(criteria) {

  if (!criteria) {
    return this;
  }

  // Normalize criteria
  criteria = normalize.criteria({ sort: criteria });

  var sort = this._wlQueryInfo.criteria.sort || {};

  _.each(criteria.sort, function(val, key) {
    sort[key] = criteria.sort[key];
  });

  this._wlQueryInfo.criteria.sort = sort;

  return this;
};

/**
 * Add a Sum clause to the criteria object
 *
 * @param {Array|Arguments} Keys to sum over
 * @return this
 */
Deferred.prototype.sum = function(attrName) {
  this._wlQueryInfo.numericAttrName = attrName;
  return this;
};

/**
 * Add an Average clause to the criteria object
 *
 * @param {Array|Arguments} Keys to average over
 * @return this
 */
Deferred.prototype.avg = function(attrName) {
  this._wlQueryInfo.numericAttrName = attrName;
  return this;
};

/**
 * Add values to be used in update or create query
 *
 * @param {Object, Array} values
 * @return this
 */

Deferred.prototype.set = function(values) {
  this._wlQueryInfo.values = values;

  return this;
};

/**
 * Pass metadata down to the adapter that won't be processed or touched by Waterline
 */

Deferred.prototype.meta = function(data) {
  this._meta = data;
  return this;
};

/**
 * Pass an active connection down to the query.
 */

Deferred.prototype.usingConnection = function(leasedConnection) {
  this._meta = this._meta || {};
  this._meta.leasedConnection = leasedConnection;
  return this;
};

/**
 * Execute a Query using the method passed into the
 * constuctor.
 *
 * @param {Function} callback
 * @return callback with parameters (err, results)
 */

Deferred.prototype.exec = function(cb) {
  if (_.isUndefined(cb)) {
    console.log(
      'Error: No callback supplied. Please define a callback function when executing a query.  '+
      'See http://sailsjs.com/docs/reference/waterline-orm/queries/exec for help.'
    );
    return;
  }

  var isValidCb = _.isFunction(cb) || (_.isObject(cb) && !_.isArray(cb));
  if (!isValidCb) {
    console.log(
      'Error: Sorry, `.exec()` doesn\'t know how to handle a callback like that:\n'+
      util.inspect(cb, {depth: null})+'\n'+
      'Instead, please provide a callback function when executing a query.  '+
      'See http://sailsjs.com/docs/reference/waterline-orm/queries/exec for help.'
    );
    return;
  }

  // Otherwise, the provided callback function is pretty cool, and all is right and well.

  // Normalize callback/switchback
  cb = normalize.callback(cb);

  // Build up the arguments based on the method
  var args;
  var query = this._wlQueryInfo;

  // Deterine what arguments to send based on the method
  switch (this._wlQueryInfo.method) {
    case 'join':
    case 'find':
    case 'findOne':
      args = [query.criteria, cb, this._meta];
      break;

    case 'create':
    case 'createEach':
      args = [query.values, cb, this._meta];
      break;

    case 'update':
      args = [query.criteria, query.values, cb, this._meta];
      break;

    case 'destroy':
      args = [query.criteria, cb, this._meta];
      break;

    case 'avg':
    case 'sum':
      args = [query.numericAttrName, query.criteria, {}, cb, this._meta];
      break;

    case 'count':
      args = [query.criteria, {}, cb, this._meta];
      break;

    case 'addToCollection':
    case 'removeFromCollection':
    case 'replaceCollection':
      args = [query.targetRecordIds, query.collectionAttrName, query.associatedIds, cb, this._meta];
      break;

    default:
      args = [query.criteria, cb, this._meta];
  }

  // Pass control to the adapter with the appropriate arguments.
  this._method.apply(this._context, args);
};

/**
 * Executes a Query, and returns a promise
 */

Deferred.prototype.toPromise = function() {
  if (!this._deferred) {
    this._deferred = Promise.promisify(this.exec).bind(this)();
  }
  return this._deferred;
};

/**
 * Executes a Query, and returns a promise that applies cb/ec to the
 * result/error.
 */

Deferred.prototype.then = function(cb, ec) {
  return this.toPromise().then(cb, ec);
};

/**
 * Applies results to function fn.apply, and returns a promise
 */

Deferred.prototype.spread = function(cb) {
  return this.toPromise().spread(cb);
};

/**
 * returns a promise and gets resolved with error
 */

Deferred.prototype.catch = function(cb) {
  return this.toPromise().catch(cb);
};

/**
 * Alias "catch" as "fail"
 */
Deferred.prototype.fail = Deferred.prototype.catch;
<commit_msg>fix up args in deferred<commit_after>/**
 * Module dependencies
 */

var util = require('util');
var _ = require('@sailshq/lodash');
var Promise = require('bluebird');
var normalize = require('../normalize');

// Alias "catch" as "fail", for backwards compatibility with projects
// that were created using Q
//
// TODO: change this so it doesn't modify the global
Promise.prototype.fail = Promise.prototype.catch;

/**
 * Deferred Object
 *
 * Used for building up a Query
 */
var Deferred = module.exports = function(context, method, wlQueryInfo) {

  if (!context) {
    throw new Error('Must supply a context to a new Deferred object. Usage: new Deferred(context, fn, wlQueryInfo)');
  }
  if (!method) {
    throw new Error('Must supply a method to a new Deferred object. Usage: new Deferred(context, fn, wlQueryInfo)');
  }

  if (!wlQueryInfo) {
    throw new Error('Must supply a third arg (`wlQueryInfo`) to a new Deferred object. Usage: new Deferred(context, fn, wlQueryInfo)');
  }
  if (!_.isObject(wlQueryInfo)) {
    throw new Error('Third arg (`wlQueryInfo`) must be a valid dictionary. Usage: new Deferred(context, fn, wlQueryInfo)');
  }

  this._context = context;
  this._method = method;

  // Make sure `_wlQueryInfo` is always a dictionary.
  this._wlQueryInfo = wlQueryInfo || {};

  // Make sure `_wlQueryInfo.criteria` is always a dictionary
  this._wlQueryInfo.criteria = this._wlQueryInfo.criteria || {};

  // Attach `_wlQueryInfo.using` and set it equal to the model identity.
  // TODO

  // Make sure `._wlQueryInfo.values` is `null`, rather than simply undefined or any other falsey thing..
  // (This is just for backwards compatibility.  Could be removed if proven that it's safe.)
  this._wlQueryInfo.values = this._wlQueryInfo.values || null;

  // Initialize `_deferred` to `null`.
  // (this is used for promises)
  this._deferred = null;

  return this;
};

/**
 * Populate all associations of a collection.
 *
 * @return this
 * @chainable
 */
Deferred.prototype.populateAll = function(criteria) {
  var self = this;
  this._context.associations.forEach(function(association) {
    self.populate(association.alias, criteria);
  });
  return this;
};

/**
 * Add a `joins` clause to the criteria object.
 *
 * Used for populating associations.
 *
 * @param {String|Array} key, the key to populate or array of string keys
 * @return this
 * @chainable
 */

Deferred.prototype.populate = function(keyName, criteria) {
  var self = this;

  // Adds support for arrays into keyName so that a list of
  // populates can be passed
  if (_.isArray(keyName)) {
    _.each(keyName, function(populate) {
      self.populate(populate, criteria);
    });
    return this;
  }

  this._wlQueryInfo.criteria.populates = this._wlQueryInfo.criteria.populates || {};
  this._wlQueryInfo.criteria.populates[keyName] = criteria || {};

  return this;
};

/**
 * Add projections to the parent
 *
 * @param {Array} attributes to select
 * @return this
 */

Deferred.prototype.select = function(attributes) {
  if(!_.isArray(attributes)) {
    attributes = [attributes];
  }

  var select = this._wlQueryInfo.criteria.select || [];
  select = select.concat(attributes);
  this._wlQueryInfo.criteria.select = _.uniq(select);

  return this;
};

Deferred.prototype.omit = function(attributes) {
  if(!_.isArray(attributes)) {
    attributes = [attributes];
  }

  var omit = this._wlQueryInfo.criteria.omit || [];
  omit = omit.concat(attributes);
  this._wlQueryInfo.criteria.omit = _.uniq(omit);

  return this;
};

/**
 * Add a Where clause to the criteria object
 *
 * @param {Object} criteria to append
 * @return this
 */

Deferred.prototype.where = function(criteria) {

  if (!criteria) {
    return this;
  }

  if (!_.has(this._wlQueryInfo, 'criteria')) {
    this._wlQueryInfo.criteria = {};
  }

  var where = this._wlQueryInfo.criteria.where || {};

  // Merge with existing WHERE clause
  this._wlQueryInfo.criteria.where = _.merge({}, where, criteria);

  return this;
};

/**
 * Add a Limit clause to the criteria object
 *
 * @param {Integer} number to limit
 * @return this
 */

Deferred.prototype.limit = function(limit) {
  this._wlQueryInfo.criteria.limit = limit;

  return this;
};

/**
 * Add a Skip clause to the criteria object
 *
 * @param {Integer} number to skip
 * @return this
 */

Deferred.prototype.skip = function(skip) {
  this._wlQueryInfo.criteria.skip = skip;

  return this;
};

/**
 * Add a Paginate clause to the criteria object
 *
 * This is syntatical sugar that calls skip and
 * limit from a single function.
 *
 * @param {Object} page and limit
 * @return this
 */
Deferred.prototype.paginate = function(options) {
  var defaultLimit = 10;

  if (_.isUndefined(options)) {
    options = { page: 0, limit: defaultLimit };
  }

  var page = options.page || 0;
  var limit = options.limit || defaultLimit;
  var skip = 0;

  if (page > 0 && limit === 0) {
    skip = page - 1;
  }

  if (page > 0 && limit > 0) {
    skip = (page * limit) - limit;
  }

  this
  .skip(skip)
  .limit(limit);

  return this;
};

/**
 * Add a Sort clause to the criteria object
 *
 * @param {String|Object} key and order
 * @return this
 */

Deferred.prototype.sort = function(criteria) {

  if (!criteria) {
    return this;
  }

  // Normalize criteria
  criteria = normalize.criteria({ sort: criteria });

  var sort = this._wlQueryInfo.criteria.sort || {};

  _.each(criteria.sort, function(val, key) {
    sort[key] = criteria.sort[key];
  });

  this._wlQueryInfo.criteria.sort = sort;

  return this;
};

/**
 * Add a Sum clause to the criteria object
 *
 * @param {Array|Arguments} Keys to sum over
 * @return this
 */
Deferred.prototype.sum = function(attrName) {
  this._wlQueryInfo.numericAttrName = attrName;
  return this;
};

/**
 * Add an Average clause to the criteria object
 *
 * @param {Array|Arguments} Keys to average over
 * @return this
 */
Deferred.prototype.avg = function(attrName) {
  this._wlQueryInfo.numericAttrName = attrName;
  return this;
};

/**
 * Add values to be used in update or create query
 *
 * @param {Object, Array} values
 * @return this
 */

Deferred.prototype.set = function(values) {
  this._wlQueryInfo.values = values;

  return this;
};

/**
 * Pass metadata down to the adapter that won't be processed or touched by Waterline
 */

Deferred.prototype.meta = function(data) {
  this._meta = data;
  return this;
};

/**
 * Pass an active connection down to the query.
 */

Deferred.prototype.usingConnection = function(leasedConnection) {
  this._meta = this._meta || {};
  this._meta.leasedConnection = leasedConnection;
  return this;
};

/**
 * Execute a Query using the method passed into the
 * constuctor.
 *
 * @param {Function} callback
 * @return callback with parameters (err, results)
 */

Deferred.prototype.exec = function(cb) {
  if (_.isUndefined(cb)) {
    console.log(
      'Error: No callback supplied. Please define a callback function when executing a query.  '+
      'See http://sailsjs.com/docs/reference/waterline-orm/queries/exec for help.'
    );
    return;
  }

  var isValidCb = _.isFunction(cb) || (_.isObject(cb) && !_.isArray(cb));
  if (!isValidCb) {
    console.log(
      'Error: Sorry, `.exec()` doesn\'t know how to handle a callback like that:\n'+
      util.inspect(cb, {depth: null})+'\n'+
      'Instead, please provide a callback function when executing a query.  '+
      'See http://sailsjs.com/docs/reference/waterline-orm/queries/exec for help.'
    );
    return;
  }

  // Otherwise, the provided callback function is pretty cool, and all is right and well.

  // Normalize callback/switchback
  cb = normalize.callback(cb);

  // Build up the arguments based on the method
  var args;
  var query = this._wlQueryInfo;

  // Deterine what arguments to send based on the method
  switch (query.method) {
    case 'join':
    case 'find':
    case 'findOne':
      args = [query.criteria, cb, this._meta];
      break;

    case 'create':
    case 'createEach':
      args = [query.newRecords, cb, this._meta];
      break;

    case 'update':
      args = [query.criteria, query.valuesToUpdate, cb, this._meta];
      break;

    case 'destroy':
      args = [query.criteria, cb, this._meta];
      break;

    case 'avg':
    case 'sum':
      args = [query.numericAttrName, query.criteria, {}, cb, this._meta];
      break;

    case 'count':
      args = [query.criteria, {}, cb, this._meta];
      break;

    case 'addToCollection':
    case 'removeFromCollection':
    case 'replaceCollection':
      args = [query.targetRecordIds, query.collectionAttrName, query.associatedIds, cb, this._meta];
      break;

    default:
      args = [query.criteria, cb, this._meta];
  }

  // Pass control to the adapter with the appropriate arguments.
  this._method.apply(this._context, args);
};

/**
 * Executes a Query, and returns a promise
 */

Deferred.prototype.toPromise = function() {
  if (!this._deferred) {
    this._deferred = Promise.promisify(this.exec).bind(this)();
  }
  return this._deferred;
};

/**
 * Executes a Query, and returns a promise that applies cb/ec to the
 * result/error.
 */

Deferred.prototype.then = function(cb, ec) {
  return this.toPromise().then(cb, ec);
};

/**
 * Applies results to function fn.apply, and returns a promise
 */

Deferred.prototype.spread = function(cb) {
  return this.toPromise().spread(cb);
};

/**
 * returns a promise and gets resolved with error
 */

Deferred.prototype.catch = function(cb) {
  return this.toPromise().catch(cb);
};

/**
 * Alias "catch" as "fail"
 */
Deferred.prototype.fail = Deferred.prototype.catch;
<|endoftext|>