<commit_before>'use strict';

var expect = require("expect.js");
var async = require('async');
var fs = require('fs');
var _ = require('lodash');
var StaticUtils = require('../src/StaticUtils');

var repos = ["project1","project2"];

var boscoMock = function() {

  return {
      log: function(msg) { this._log = this._log || []; this._log.push(msg) },
      error: function(msg) { this._error = this._error || []; this._error.push(msg) },
      warn: function(msg) { this._warn = this._warn || []; this._warn.push(msg) },
      options: {
          environment:'test'
      },
      getRepoPath: function(repo) {
          return __dirname + "/TestOrganisation/" + repo
      },
      exists: function(file) {
          return fs.existsSync(file);
      },
      config: {
          get: function(key) {
              return key;
          }
      }
  }

}

describe("Bosco Static Asset Handling", function() {

    this.timeout(5000);
    this.slow(5000);

    it('should load static assets in un-minified cdn mode, deduping where necessary', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: false,
            tagFilter: null,
            watchBuilds: false,
            reloadOnly: false
        }

        var localBosco = boscoMock()
        var utils = StaticUtils(localBosco);

        utils.getStaticAssets(options, function(err, assets) {

            expect(localBosco._warn).to.contain("Skipping duplicate file: project1/js/bottom1.js <> project2/js/bottom2dupe.js");
            expect(localBosco._warn).to.contain("Duplicate library with different version: project1/js/jquery-1.11.0-min.js <> project2/js/jquery-1.12.0-min.js");

            expect(assets).to.have.keys('test/html/top.js.html',
                                    'test/html/bottom.js.html',
                                    'test/html/top.css.html',
                                    'project1/js/top1.js',
                                    'project2/js/bottom2.js',
                                    'project2/js/top2.js',
                                    'project2/css/top2.scss');
            done();

        });

    });

     it('should load static assets in minified cdn mode, deduping where necessary', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: true,
            tagFilter: null,
            watchBuilds: false,
            reloadOnly: false
        }
        var localBosco = boscoMock()
        var utils = StaticUtils(localBosco);

        utils.getStaticAssets(options, function(err, assets) {

            expect(localBosco._warn).to.contain("Skipping duplicate file: project1/js/bottom1.js <> project2/js/bottom2dupe.js");
            expect(localBosco._warn).to.contain("Duplicate library with different version: project1/js/jquery-1.11.0-min.js <> project2/js/jquery-1.12.0-min.js");

            expect(assets).to.have.keys('test/html/top.js.html',
                                      'test/html/bottom.js.html',
                                      'test/html/top.css.html',
                                      'test/js/top.js.map',
                                      'test/js/top.9788b8bac1.js',
                                      'test/js/bottom.js.map',
                                      'test/js/bottom.8007be235b.js',
                                      'test/css/top.ca7986a9bb.css',
                                      'test/manifest/top.js.txt',
                                      'test/manifest/bottom.js.txt',
                                      'test/manifest/top.css.txt' );
            done();

        });

    });

   it('should load static assets in minified cdn mode, filtering by tag if specified', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: true,
            tagFilter: 'top',
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/html/top.js.html',
                                      'test/html/top.css.html',
                                      'test/js/top.js.map',
                                      'test/js/top.5892df4693.js',
                                      'test/css/top.ca7986a9bb.css',
                                      'test/manifest/top.js.txt',
                                      'test/manifest/top.css.txt' );
            done();

        });

    });

  it('should not parse sass templates when not minifying as this is done in cdn command to allow live reload', function(done) {

        var options = {
            repos: ["project2"],
            minify: false,
            tagFilter: 'top',
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('project2/css/top2.scss');
            expect(assets['project2/css/top2.scss'].content.toString()).to.not.contain('#main {\n  width: 5em; }\n')
            done();

        });

    });

   it('should parse sass templates when minifying', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: true,
            tagFilter: 'top',
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/css/top.ca7986a9bb.css');
            expect(assets['test/css/top.ca7986a9bb.css'].content.toString()).to.contain('#main {\n  width: 5em; }\n')
            done();

        });

    });

  it('should create a manifest when minified that will have all of the files', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: true,
            tagFilter: 'top',
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/manifest/top.js.txt');
            expect(assets['test/manifest/top.js.txt'].content.toString()).to.contain('project1/public/js/top1.js');
            expect(assets['test/manifest/top.js.txt'].content.toString()).to.contain('project2/public/js/top2.js');
            expect(assets['test/manifest/top.js.txt'].content.toString()).to.contain('project2/public/js/jquery-1.12.0-min.js');
            done();

        });

    });

});

describe("Bosco Static Asset Handling - Custom Building", function() {

  this.timeout(5000);
  this.slow(5000);

  it('should execute bespoke build commands and use output', function(done) {

        var options = {
            repos: ["project3"],
            minify: true,
            tagFilter: null,
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/html/compiled.js.html',
                                    'test/html/compiled.css.html',
                                    'test/js/compiled.js.map',
                                    'test/js/compiled.12915d7076.js',
                                    'test/css/compiled.09414dff4c.css',
                                    'test/manifest/compiled.js.txt',
                                    'test/manifest/compiled.css.txt');

            done();

        });

    });

  it('should execute bespoke build commands and use output, and execute the watch command in watch mode', function(done) {

        var options = {
            repos: ["project3"],
            minify: true,
            tagFilter: null,
            watchBuilds: true,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/html/compiled.js.html',
                                    'test/html/compiled.css.html',
                                    'test/js/compiled.js.map',
                                    'test/js/compiled.12915d7076.js',
                                    'test/css/compiled.09414dff4c.css',
                                    'test/manifest/compiled.js.txt',
                                    'test/manifest/compiled.css.txt');
            done();

        });

    });

it('should execute bespoke build commands and use output, and execute the watch command in watch mode and not minified', function(done) {

        this.timeout(5000);

        var options = {
            repos: ["project3"],
            minify: false,
            tagFilter: null,
            watchBuilds: true,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/html/compiled.js.html',
                                  'test/html/compiled.css.html',
                                  'project3/js/compiled.js',
                                  'project3/css/compiled.css');
            done();

        });

    });

});<commit_msg>Added test for source map<commit_after>'use strict';

var expect = require("expect.js");
var async = require('async');
var fs = require('fs');
var _ = require('lodash');
var StaticUtils = require('../src/StaticUtils');

var repos = ["project1","project2"];

var boscoMock = function() {

  return {
      log: function(msg) { this._log = this._log || []; this._log.push(msg) },
      error: function(msg) { this._error = this._error || []; this._error.push(msg) },
      warn: function(msg) { this._warn = this._warn || []; this._warn.push(msg) },
      options: {
          environment:'test'
      },
      getRepoPath: function(repo) {
          return __dirname + "/TestOrganisation/" + repo
      },
      exists: function(file) {
          return fs.existsSync(file);
      },
      config: {
          get: function(key) {
              return key;
          }
      }
  }

}

describe("Bosco Static Asset Handling", function() {

    this.timeout(5000);
    this.slow(5000);

    it('should load static assets in un-minified cdn mode, deduping where necessary', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: false,
            tagFilter: null,
            watchBuilds: false,
            reloadOnly: false
        }

        var localBosco = boscoMock()
        var utils = StaticUtils(localBosco);

        utils.getStaticAssets(options, function(err, assets) {

            expect(localBosco._warn).to.contain("Skipping duplicate file: project1/js/bottom1.js <> project2/js/bottom2dupe.js");
            expect(localBosco._warn).to.contain("Duplicate library with different version: project1/js/jquery-1.11.0-min.js <> project2/js/jquery-1.12.0-min.js");

            expect(assets).to.have.keys('test/html/top.js.html',
                                    'test/html/bottom.js.html',
                                    'test/html/top.css.html',
                                    'project1/js/top1.js',
                                    'project2/js/bottom2.js',
                                    'project2/js/top2.js',
                                    'project2/css/top2.scss');
            done();

        });

    });

     it('should load static assets in minified cdn mode, deduping where necessary', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: true,
            tagFilter: null,
            watchBuilds: false,
            reloadOnly: false
        }
        var localBosco = boscoMock()
        var utils = StaticUtils(localBosco);

        utils.getStaticAssets(options, function(err, assets) {

            expect(localBosco._warn).to.contain("Skipping duplicate file: project1/js/bottom1.js <> project2/js/bottom2dupe.js");
            expect(localBosco._warn).to.contain("Duplicate library with different version: project1/js/jquery-1.11.0-min.js <> project2/js/jquery-1.12.0-min.js");

            expect(assets).to.have.keys('test/html/top.js.html',
                                      'test/html/bottom.js.html',
                                      'test/html/top.css.html',
                                      'test/js/top.js.map',
                                      'test/js/top.9788b8bac1.js',
                                      'test/js/bottom.js.map',
                                      'test/js/bottom.8007be235b.js',
                                      'test/css/top.ca7986a9bb.css',
                                      'test/manifest/top.js.txt',
                                      'test/manifest/bottom.js.txt',
                                      'test/manifest/top.css.txt' );
            done();

        });

    });

   it('should load static assets in minified cdn mode, filtering by tag if specified', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: true,
            tagFilter: 'top',
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/html/top.js.html',
                                      'test/html/top.css.html',
                                      'test/js/top.js.map',
                                      'test/js/top.5892df4693.js',
                                      'test/css/top.ca7986a9bb.css',
                                      'test/manifest/top.js.txt',
                                      'test/manifest/top.css.txt' );
            done();

        });

    });

  it('should not parse sass templates when not minifying as this is done in cdn command to allow live reload', function(done) {

        var options = {
            repos: ["project2"],
            minify: false,
            tagFilter: 'top',
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('project2/css/top2.scss');
            expect(assets['project2/css/top2.scss'].content.toString()).to.not.contain('#main {\n  width: 5em; }\n')
            done();

        });

    });

   it('should parse sass templates when minifying', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: true,
            tagFilter: 'top',
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/css/top.ca7986a9bb.css');
            expect(assets['test/css/top.ca7986a9bb.css'].content.toString()).to.contain('#main {\n  width: 5em; }\n')
            done();

        });

    });

  it('should create a manifest when minified that will have all of the files', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: true,
            tagFilter: 'top',
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/manifest/top.js.txt');
            expect(assets['test/manifest/top.js.txt'].content.toString()).to.contain('project1/public/js/top1.js');
            expect(assets['test/manifest/top.js.txt'].content.toString()).to.contain('project2/public/js/top2.js');
            expect(assets['test/manifest/top.js.txt'].content.toString()).to.contain('project2/public/js/jquery-1.12.0-min.js');
            done();

        });

    });

  it('should create a source map when minifying javascript', function(done) {

        var options = {
            repos: ["project1","project2"],
            minify: true,
            tagFilter: 'top',
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/js/top.js.map');
            expect(assets['test/js/top.5892df4693.js'].content.toString()).to.contain('//# sourceMappingURL=top.js.map');
            done();

        });

    });

});

describe("Bosco Static Asset Handling - Custom Building", function() {

  this.timeout(5000);
  this.slow(5000);

  it('should execute bespoke build commands and use output', function(done) {

        var options = {
            repos: ["project3"],
            minify: true,
            tagFilter: null,
            watchBuilds: false,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/html/compiled.js.html',
                                    'test/html/compiled.css.html',
                                    'test/js/compiled.js.map',
                                    'test/js/compiled.12915d7076.js',
                                    'test/css/compiled.09414dff4c.css',
                                    'test/manifest/compiled.js.txt',
                                    'test/manifest/compiled.css.txt');

            done();

        });

    });

  it('should execute bespoke build commands and use output, and execute the watch command in watch mode', function(done) {

        var options = {
            repos: ["project3"],
            minify: true,
            tagFilter: null,
            watchBuilds: true,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/html/compiled.js.html',
                                    'test/html/compiled.css.html',
                                    'test/js/compiled.js.map',
                                    'test/js/compiled.12915d7076.js',
                                    'test/css/compiled.09414dff4c.css',
                                    'test/manifest/compiled.js.txt',
                                    'test/manifest/compiled.css.txt');
            done();

        });

    });

it('should execute bespoke build commands and use output, and execute the watch command in watch mode and not minified', function(done) {

        this.timeout(5000);

        var options = {
            repos: ["project3"],
            minify: false,
            tagFilter: null,
            watchBuilds: true,
            reloadOnly: false
        }

        var utils = StaticUtils(boscoMock());

        utils.getStaticAssets(options, function(err, assets) {

            expect(assets).to.have.keys('test/html/compiled.js.html',
                                  'test/html/compiled.css.html',
                                  'project3/js/compiled.js',
                                  'project3/css/compiled.css');
            done();

        });

    });

});<|endoftext|>


<commit_before>firebase.auth().onAuthStateChanged(function(user) {

	var uploaded = false;
  // redirect if the user is signed in
  var finished = function	() {
  	location.reload();
  }

  $('#file').change(function (e) {
  	var file = this.files[0];
  	if (!file && file.name.substring(file.name.length - 4) != ".csv") {
  		alert("Please upload a valid csv file");
  	} else {
  		uploaded = true;
  	}
  });

  if (user) {
  	console.log("signed in");

  	var companyRef = firebase.database().ref('/Companies');
		var companies = {};
		companyRef.once('value', function(snapshot) {
			companies = snapshot.val();
		});

  	$(document).ready(function() {
			$('#email').val(user.email);

			$('#add-btn').click(function() {
				if (uploaded) {
					upload();
				} else {
					// re-initialize so we get upto date information
					console.log("button clicked");
					var products = $('#products').val().split('\n');
					var company = $('#company').val();
					var department = $('#department').val();

					// check to see if company already exists
					var exists = false;
					var companyId = "";
					var companyObj = {
						companyName: company,
						departments: "",
						products: "",
					}

					for (var key in companies) {
						if (companies[key].companyName == company) {
							console.log("similar company found");
							exists = true;
							companyId = key;
							break;
						}
					}

					if (!exists) {
						// no need to check everything is new, just create everything
						companyId = firebase.database().ref().child('/Companies').push().key;
						var departmentId = firebase.database().ref().child('/Departments/' + companyId).push().key;
						var departmentObj = {}
						departmentObj[departmentId] = department;
						var updates = {};
						var productObj = {};
						for (var i = 1; i <= products.length; i++) {
							if (products[i-1] != "") {
								var name = "product" + i;
								productObj[name] = products[i - 1];
							}
						}
						updates['/Companies/' + companyId] = companyObj;
						updates['/Departments/' + companyId] = departmentObj;
						updates['/Products/' + departmentId] = productObj;
						firebase.database().ref().update(updates);
						finished();
					} else {
						// need to check for existing departments and products
						var departmentRef = firebase.database().ref('/Departments/' + companyId);
						departmentRef.once('value', function(snapshot) {
							var departments = snapshot.val();
							var found = false;
							var departmentId = ""
							// check to see if there is an existing key for the department
							for (var key in departments) {
								if (departments[key] == department) {
									found = true;
									departmentId = key;
									break;
								}
							}

							var updates = {};
							var departmentObj = {};
							var productObj = {};

							if (!found) {
								// if department doesn't exist, make it and add it to Companies
								// Departments and it's Products
								departmentId = firebase.database().ref().child('/Departments/' + companyId).push().key;
								departmentObj[departmentId] = department;
								for (var i = 1; i <= products.length; i++) {
									if (products[i-1] != "") {
										var name = "product" + i;
										productObj[name] = products[i - 1];
									}
								}
								firebase.database().ref('/Departments').child(companyId).update(departmentObj);
								firebase.database().ref('/Products').child(departmentId).update(productObj);
								finished();
							} else {
								// department exists, we have to check existing products
								var departmentRef = firebase.database().ref('/Products/' + departmentId);
								departmentRef.once('value', function(snapshot) {
									existingProducts = snapshot.val();
									var count = 0;
									for (var key in existingProducts) {
										count++;
									}
									for (var i = 1; i <= products.length; i++) {
										if (products[i-1] != "") {
											var name = "product" + (count + i);
											productObj[name] = products[i - 1];
										}
									}
									console.log("adding new products")
									firebase.database().ref('/Products').child(departmentId).update(productObj);
									finished();
								});
							}
						}); // end check for department
					}
				}
			}); // end add button click
		}); // end document ready
  } else {
  	console.log("not signed in");
  	window.location = "/";
	}

	var upload = function() {
		var company = $('#company').val();
			if (company == "") {
				alert("Please enter the company name to add csv file to");
				$('#file').val('');
				return false;
			}
			var companyObj = {
				companyName: company,
				departments: "",
				products: "",
			}

			//var selectedFile = this.files[0];

			// check if submitted valid file
			/*if (file && (file.name.substring(file.name.length - 4) == '.png' ||
				file.substring(file.name.length - 4) == '.jpg')) {
		    	selectedFile.convertToBase64(function(base64){
		           console.log(base64);
		    	})
			} else {
				alert("Please upload a valid .PNG or .JPG file");
			}*/

			var file = this.files[0];
			console.log(file);
			// check if valid file
			if (file && file.name.substring(file.name.length - 4) == ".csv") {
				Papa.parse(file, {
					complete: function(results) {
						var data = results.data;
						console.log(results.data)
						var obj = {};
						var departmentList = [];
						for (var i = 0; i < data.length; i++) {
							// todo, what to do in the event if given iproper format
							if (data[i].length == 2) {
								console.log(data[i][0], data[i][1]);
								if (typeof obj[data[i][0]] === 'undefined') {
									obj[data[i][0]] = [];
									departmentList.push(data[i][0]);
								}
								obj[data[i][0]].push(data[i][1]);
							}
						}
						console.log(obj);
						console.log(departmentList);
						var exists = false;
						var companyId = ""
						// note companies are from existing pre-load from other page
						for (var key in companies) {
							if (companies[key].companyName == company) {
								console.log("similar company found");
								exists = true;
								companyId = key;
								break;
							}
						}

						if (!exists) {
							console.log("company doesn't exist");
							// no need to check everything is new, just create everything
							companyId = firebase.database().ref().child('/Companies').push().key;
							var keyList = [];
							var departmentObj = {}

							for (var i = 0; i < departmentList.length; i++) {
								var departmentKey = firebase.database().ref().child('/Departments/' + companyId).push().key;
								// later used to allow easier mapping between department and products
								keyList.push(departmentKey);
								departmentObj[departmentKey] = departmentList[i];
							}
							console.log(keyList);

							// need list of products with department key to object of products
							var updates = {};
							var productObj = {};

							// create our mapping for our department to product
							/**
							ex:
							productObj = {
								'department_id': {
									'product1': "fish",
									'product2': "grain",
								}
							}
							*/
							for (var i = 0; i < departmentList.length; i++) {
								// keyList has the same ordering as departmentList
								productObj[keyList[i]] = {};
								for (var j = 0; j < obj[departmentList[i]].length; j++) {
									var products = obj[departmentList[i]];
									if (products[j] != "") {
										var name = "product" + (j + 1);
										console.log(name, products)
										console.log(productObj);
										productObj[keyList[i]][name] = products[j];
									}
								}
							}

							updates['/Companies/' + companyId] = companyObj;
							updates['/Departments/' + companyId] = departmentObj;
							for (var key in productObj) {
								updates['/Products/' + key] = productObj[key];
							}
							firebase.database().ref().update(updates);
							//finished();
						} else {
							console.log("company exists");
							// company exists, check if each department exists
							var departmentRef = firebase.database().ref('/Departments/' + companyId);
							departmentRef.once('value', function(snapshot) {
								var departments = snapshot.val();
								console.log("object", obj);
								var departmentIdNameMapping = {};
								for (var departmentName in obj) {
									var found = false;
									var departmentId = ""
									var keyList = [];
									var departmentObj = {};
									var productObj = {};

									// check to see if there is an existing key for the department
									for (var key in departments) {
										if (departments[key] == departmentName) {
											found = true;
											departmentId = key;
											departmentIdNameMapping[departmentId] = departmentName;
											break;
										}
									}
									if (!found) {
										console.log(departmentName, "doesn't exist");
										departmentId = firebase.database().ref().child('/Departments/' + companyId).push().key;
										departmentObj[departmentId] = departmentName;
										console.log(key);
										// adding the product to the associated department
										//productObj[departmentId] = {};
										for (var j = 0; j < obj[departmentName].length; j++) {
											var products = obj[departmentName];
											if (products[j] != "") {
												var name = "product" + (j + 1);
												productObj[name] = products[j];
											}
										}
										firebase.database().ref('/Departments').child(companyId).update(departmentObj);
										firebase.database().ref('/Products').child(departmentId).update(productObj);
									} else {
										console.log(departmentName, "exist");
										var departmentRef = firebase.database().ref('/Products/' + departmentId);
										departmentRef.once('value', function(snapshot) {
											snapKey = snapshot.key;
											existingProducts = snapshot.val();
											var count = 0;
											for (var key in existingProducts) {
												count++;
											}
											console.log("products", existingProducts);
											console.log("key", snapKey);
											var mappedDepartmentName = departmentIdNameMapping[snapKey];
											for (var i = 0; i < obj[mappedDepartmentName].length; i++) {
												var products = obj[mappedDepartmentName];
												if (products[i] != "") {
													var name = "product" + (count + i + 1);
													productObj[name] = obj[mappedDepartmentName][i];
												}
											}
											firebase.database().ref('/Products').child(snapKey).update(productObj);
										});
									}
								} // end for loop forthrough all departments
							}); // end check for department
						}
					}
				});
			} else {
				alert("Please upload a valid CSV file.")
			}
	}
}); // end auth listener<commit_msg>finished integration<commit_after>firebase.auth().onAuthStateChanged(function(user) {

	var uploaded = false;
  // redirect if the user is signed in
  var finished = function	() {
  	location.reload();
  }

  $('#file').change(function (e) {
  	var file = this.files[0];
  	if (!file && file.name.substring(file.name.length - 4) != ".csv") {
  		alert("Please upload a valid csv file");
  	} else {
  		uploaded = true;
  	}
  });

  if (user) {
  	console.log("signed in");

  	var companyRef = firebase.database().ref('/Companies');
		var companies = {};
		companyRef.once('value', function(snapshot) {
			companies = snapshot.val();
		});

  	$(document).ready(function() {
			$('#email').val(user.email);

			$('#add-btn').click(function() {
				if (uploaded) {
					upload();
				} else {
					// re-initialize so we get upto date information
					individualSubmit();
				}
			}); // end add button click
		}); // end document ready
  } else {
  	console.log("not signed in");
  	window.location = "/";
	}

	var individualSubmit = function() {
		console.log("button clicked");
		var products = $('#products').val().split('\n');
		var company = $('#company').val();
		var department = $('#department').val();

		// check to see if company already exists
		var exists = false;
		var companyId = "";
		var companyObj = {
			companyName: company,
			departments: "",
			products: "",
		}

		for (var key in companies) {
			if (companies[key].companyName == company) {
				console.log("similar company found");
				exists = true;
				companyId = key;
				break;
			}
		}

		if (!exists) {
			// no need to check everything is new, just create everything
			companyId = firebase.database().ref().child('/Companies').push().key;
			var departmentId = firebase.database().ref().child('/Departments/' + companyId).push().key;
			var departmentObj = {}
			departmentObj[departmentId] = department;
			var updates = {};
			var productObj = {};
			for (var i = 1; i <= products.length; i++) {
				if (products[i-1] != "") {
					var name = "product" + i;
					productObj[name] = products[i - 1];
				}
			}
			updates['/Companies/' + companyId] = companyObj;
			updates['/Departments/' + companyId] = departmentObj;
			updates['/Products/' + departmentId] = productObj;
			firebase.database().ref().update(updates);
			finished();
		} else {
			// need to check for existing departments and products
			var departmentRef = firebase.database().ref('/Departments/' + companyId);
			departmentRef.once('value', function(snapshot) {
				var departments = snapshot.val();
				var found = false;
				var departmentId = ""
				// check to see if there is an existing key for the department
				for (var key in departments) {
					if (departments[key] == department) {
						found = true;
						departmentId = key;
						break;
					}
				}

				var updates = {};
				var departmentObj = {};
				var productObj = {};

				if (!found) {
					// if department doesn't exist, make it and add it to Companies
					// Departments and it's Products
					departmentId = firebase.database().ref().child('/Departments/' + companyId).push().key;
					departmentObj[departmentId] = department;
					for (var i = 1; i <= products.length; i++) {
						if (products[i-1] != "") {
							var name = "product" + i;
							productObj[name] = products[i - 1];
						}
					}
					firebase.database().ref('/Departments').child(companyId).update(departmentObj);
					firebase.database().ref('/Products').child(departmentId).update(productObj);
					finished();
				} else {
					// department exists, we have to check existing products
					var departmentRef = firebase.database().ref('/Products/' + departmentId);
					departmentRef.once('value', function(snapshot) {
						existingProducts = snapshot.val();
						var count = 0;
						for (var key in existingProducts) {
							count++;
						}
						for (var i = 1; i <= products.length; i++) {
							if (products[i-1] != "") {
								var name = "product" + (count + i);
								productObj[name] = products[i - 1];
							}
						}
						console.log("adding new products")
						firebase.database().ref('/Products').child(departmentId).update(productObj);
						finished();
					});
				}
			}); // end check for department
		}
	}

	var upload = function() {
		var company = $('#company').val();
			if (company == "") {
				alert("Please enter the company name to add csv file to");
				$('#file').val('');
				return false;
			}
			var companyObj = {
				companyName: company,
				departments: "",
				products: "",
			}

			var file = this.files[0];
			console.log(file);
			// check if valid file
			if (file && file.name.substring(file.name.length - 4) == ".csv") {
				Papa.parse(file, {
					complete: function(results) {
						var data = results.data;
						console.log(results.data)
						var obj = {};
						var departmentList = [];
						for (var i = 0; i < data.length; i++) {
							// todo, what to do in the event if given iproper format
							if (data[i].length == 2) {
								console.log(data[i][0], data[i][1]);
								if (typeof obj[data[i][0]] === 'undefined') {
									obj[data[i][0]] = [];
									departmentList.push(data[i][0]);
								}
								obj[data[i][0]].push(data[i][1]);
							}
						}
						console.log(obj);
						console.log(departmentList);
						var exists = false;
						var companyId = ""
						// note companies are from existing pre-load from other page
						for (var key in companies) {
							if (companies[key].companyName == company) {
								console.log("similar company found");
								exists = true;
								companyId = key;
								break;
							}
						}

						if (!exists) {
							console.log("company doesn't exist");
							// no need to check everything is new, just create everything
							companyId = firebase.database().ref().child('/Companies').push().key;
							var keyList = [];
							var departmentObj = {}

							for (var i = 0; i < departmentList.length; i++) {
								var departmentKey = firebase.database().ref().child('/Departments/' + companyId).push().key;
								// later used to allow easier mapping between department and products
								keyList.push(departmentKey);
								departmentObj[departmentKey] = departmentList[i];
							}
							console.log(keyList);

							// need list of products with department key to object of products
							var updates = {};
							var productObj = {};

							// create our mapping for our department to product
							/**
							ex:
							productObj = {
								'department_id': {
									'product1': "fish",
									'product2': "grain",
								}
							}
							*/
							for (var i = 0; i < departmentList.length; i++) {
								// keyList has the same ordering as departmentList
								productObj[keyList[i]] = {};
								for (var j = 0; j < obj[departmentList[i]].length; j++) {
									var products = obj[departmentList[i]];
									if (products[j] != "") {
										var name = "product" + (j + 1);
										console.log(name, products)
										console.log(productObj);
										productObj[keyList[i]][name] = products[j];
									}
								}
							}

							updates['/Companies/' + companyId] = companyObj;
							updates['/Departments/' + companyId] = departmentObj;
							for (var key in productObj) {
								updates['/Products/' + key] = productObj[key];
							}
							firebase.database().ref().update(updates);
							//finished();
						} else {
							console.log("company exists");
							// company exists, check if each department exists
							var departmentRef = firebase.database().ref('/Departments/' + companyId);
							departmentRef.once('value', function(snapshot) {
								var departments = snapshot.val();
								console.log("object", obj);
								var departmentIdNameMapping = {};
								for (var departmentName in obj) {
									var found = false;
									var departmentId = ""
									var keyList = [];
									var departmentObj = {};
									var productObj = {};

									// check to see if there is an existing key for the department
									for (var key in departments) {
										if (departments[key] == departmentName) {
											found = true;
											departmentId = key;
											departmentIdNameMapping[departmentId] = departmentName;
											break;
										}
									}
									if (!found) {
										console.log(departmentName, "doesn't exist");
										departmentId = firebase.database().ref().child('/Departments/' + companyId).push().key;
										departmentObj[departmentId] = departmentName;
										console.log(key);
										// adding the product to the associated department
										//productObj[departmentId] = {};
										for (var j = 0; j < obj[departmentName].length; j++) {
											var products = obj[departmentName];
											if (products[j] != "") {
												var name = "product" + (j + 1);
												productObj[name] = products[j];
											}
										}
										firebase.database().ref('/Departments').child(companyId).update(departmentObj);
										firebase.database().ref('/Products').child(departmentId).update(productObj);
									} else {
										console.log(departmentName, "exist");
										var departmentRef = firebase.database().ref('/Products/' + departmentId);
										departmentRef.once('value', function(snapshot) {
											snapKey = snapshot.key;
											existingProducts = snapshot.val();
											var count = 0;
											for (var key in existingProducts) {
												count++;
											}
											console.log("products", existingProducts);
											console.log("key", snapKey);
											var mappedDepartmentName = departmentIdNameMapping[snapKey];
											for (var i = 0; i < obj[mappedDepartmentName].length; i++) {
												var products = obj[mappedDepartmentName];
												if (products[i] != "") {
													var name = "product" + (count + i + 1);
													productObj[name] = obj[mappedDepartmentName][i];
												}
											}
											firebase.database().ref('/Products').child(snapKey).update(productObj);
										});
									}
								} // end for loop forthrough all departments
							}); // end check for department
						}
					}
				});
			} else {
				alert("Please upload a valid CSV file.")
			}
	}
}); // end auth listener<|endoftext|>


<commit_before>/* eslint-disable no-restricted-syntax, no-invalid-this */
'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isPositive = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isnan = require( '@stdlib/assert/is-nan' );
var kurtosis = require( '@stdlib/math/base/dists/cosine/kurtosis' );
var mean = require( '@stdlib/math/base/dists/cosine/mean' );
var median = require( '@stdlib/math/base/dists/cosine/median' );
var mode = require( '@stdlib/math/base/dists/cosine/mode' );
var skewness = require( '@stdlib/math/base/dists/cosine/skewness' );
var stdev = require( '@stdlib/math/base/dists/cosine/stdev' );
var variance = require( '@stdlib/math/base/dists/cosine/variance' );
var cdf = require( '@stdlib/math/base/dists/cosine/cdf' );
var logcdf = require( '@stdlib/math/base/dists/cosine/logcdf' );
var logpdf = require( '@stdlib/math/base/dists/cosine/logpdf' );
var mgf = require( '@stdlib/math/base/dists/cosine/mgf' );
var pdf = require( '@stdlib/math/base/dists/cosine/pdf' );
var quantile = require( '@stdlib/math/base/dists/cosine/quantile' );

// FUNCTIONS //

/**
* Evaluates the cumulative distribution function (CDF).
*
* @private
* @param {number} x - input value
* @returns {Probability} evaluated CDF
*/
function cosineCDF( x ) {
	return cdf( x, this.mu, this.s );
}

/**
* Evaluates the natural logarithm of the cumulative distribution function (logCDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated logCDF
*/
function cosineLogCDF( x ) {
	return logcdf( x, this.mu, this.s );
}

/**
* Evaluates the natural logarithm of the probability density function (logPDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated logPDF
*/
function cosineLogPDF( x ) {
	return logpdf( x, this.mu, this.s );
}

/**
* Evaluates the moment-generating function (MGF).
*
* @private
* @param {number} t - input value
* @returns {number} evaluated MGF
*/
function cosineMGF( t ) {
	return mgf( t, this.mu, this.s );
}

/**
* Evaluates the probability density function (PDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated PDF
*/
function cosinePDF( x ) {
	return pdf( x, this.mu, this.s );
}

/**
* Evaluates the quantile function.
*
* @private
* @param {Probability} p - input probability
* @returns {number} evaluated quantile function
*/
function cosineQuantile( p ) {
	return quantile( p, this.mu, this.s );
}

// MAIN //

/**
* Cosine distribution constructor.
*
* @constructor
* @param {number} [mu=0.0] - location parameter
* @param {PositiveNumber} [s=1.0] - scale parameter
* @throws {TypeError} `s` must be a positive number
* @returns {Cosine} distribution instance
*
* @example
* var cosine = new Cosine( 1.0, 1.0 );
*
* var y = cosine.cdf( 1.5 );
* // returns ~0.909
*
* var mu = cosine.mean;
* // returns 1.0
*/
function Cosine() {
	var mu;
	var s;
	if ( !(this instanceof Cosine) ) {
		if ( arguments.length === 0 ) {
			return new Cosine();
		}
		return new Cosine( arguments[ 0 ], arguments[ 1 ] );
	}
	if ( arguments.length ) {
		mu = arguments[ 0 ];
		s = arguments[ 1 ];
		if ( !isNumber( mu ) || isnan( mu ) ) {
			throw new TypeError( 'invalid input argument. Location parameter `mu` must be a number primitive. Value: `' + mu + '`' );
		}
		if ( !isPositive( s ) ) {
			throw new TypeError( 'invalid input argument. Scale parameter `s` must be a positive number. Value: `' + s + '`' );
		}
	} else {
		mu = 0.0;
		s = 1.0;
	}
	Object.defineProperty( this, 'mu', {
		'configurable': false,
		'enumerable': true,
		'get': function get() {
			return mu;
		},
		'set': function set( value ) {
			if ( !isNumber( value ) || isnan( value ) ) {
				throw new TypeError( 'invalid value. Must be a number primitive. Value: `' + value + '`' );
			}
			mu = value;
		}
	});
	Object.defineProperty( this, 's', {
		'configurable': false,
		'enumerable': true,
		'get': function get() {
			return s;
		},
		'set': function set( value ) {
			if ( !isPositive( value ) ) {
				throw new TypeError( 'invalid value. Must be a positive number. Value: `' + value + '`' );
			}
			s = value;
		}
	});
	return this;
}

/**
* Cosine distribution excess kurtosis.
*
* @memberof Cosine.prototype
* @name kurtosis
* @type {number}
* @see [kurtosis]{@link https://en.wikipedia.org/wiki/Kurtosis}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.kurtosis;
* // returns ~-0.594
*/
Object.defineProperty( Cosine.prototype, 'kurtosis', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return kurtosis( this.mu, this.s );
	}
});

/**
* Cosine distribution expected value.
*
* @memberof Cosine.prototype
* @name mean
* @type {number}
* @see [expected value]{@link https://en.wikipedia.org/wiki/Expected_value}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.mean;
* // returns 4.0
*/
Object.defineProperty( Cosine.prototype, 'mean', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return mean( this.mu, this.s );
	}
});

/**
* Cosine distribution median.
*
* @memberof Cosine.prototype
* @name median
* @type {number}
* @see [median]{@link https://en.wikipedia.org/wiki/Median}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.median;
* // returns 4.0
*/
Object.defineProperty( Cosine.prototype, 'median', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return median( this.mu, this.s );
	}
});

/**
* Cosine distribution mode.
*
* @memberof Cosine.prototype
* @name mode
* @type {number}
* @see [mode]{@link https://en.wikipedia.org/wiki/Mode_%28statistics%29}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.mode;
* // returns 4.0
*/
Object.defineProperty( Cosine.prototype, 'mode', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return mode( this.mu, this.s );
	}
});

/**
* Cosine distribution skewness.
*
* @memberof Cosine.prototype
* @name skewness
* @type {number}
* @see [skewness]{@link https://en.wikipedia.org/wiki/Skewness}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.skewness;
* // returns 0.0
*/
Object.defineProperty( Cosine.prototype, 'skewness', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return skewness( this.mu, this.s );
	}
});

/**
* Cosine distribution standard deviation.
*
* @memberof Cosine.prototype
* @name stdev
* @type {number}
* @see [standard deviation]{@link https://en.wikipedia.org/wiki/Standard_deviation}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.stdev;
* // returns ~4.338
*/
Object.defineProperty( Cosine.prototype, 'stdev', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return stdev( this.mu, this.s );
	}
});

/**
* Cosine distribution variance.
*
* @memberof Cosine.prototype
* @name variance
* @type {number}
* @see [variance]{@link https://en.wikipedia.org/wiki/Variance}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.variance;
* // returns ~18.819
*/
Object.defineProperty( Cosine.prototype, 'variance', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return variance( this.mu, this.s );
	}
});

/**
* Evaluates the cumulative distribution function (CDF).
*
* @memberof Cosine.prototype
* @name cdf
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated CDF
* @see [cdf]{@link https://en.wikipedia.org/wiki/Cumulative_distribution_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.cdf( 0.5 );
* // returns ~0.165
*/
setReadOnly( Cosine.prototype, 'cdf', cosineCDF );

/**
* Evaluates the natural logarithm of the cumulative distribution function (logCDF).
*
* @memberof Cosine.prototype
* @name logcdf
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated logCDF
* @see [cdf]{@link https://en.wikipedia.org/wiki/Cumulative_distribution_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.logcdf( 0.5 );
* // returns ~-1.802
*/
setReadOnly( Cosine.prototype, 'logcdf', cosineLogCDF );

/**
* Evaluates the natural logarithm of the probability density function (logPDF).
*
* @memberof Cosine.prototype
* @name logpdf
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated logPDF
* @see [pdf]{@link https://en.wikipedia.org/wiki/Probability_density_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.logpdf( 0.8 );
* // returns ~-1.617
*/
setReadOnly( Cosine.prototype, 'logpdf', cosineLogPDF );

/**
* Evaluates the moment-generating function (MGF).
*
* @memberof Cosine.prototype
* @name mgf
* @type {Function}
* @param {number} t - input value
* @returns {number} evaluated MGF
* @see [mgf]{@link https://en.wikipedia.org/wiki/Moment-generating_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.mgf( 0.2 );
* // returns ~1.555
*/
setReadOnly( Cosine.prototype, 'mgf', cosineMGF );

/**
* Evaluates the probability density function (PDF).
*
* @memberof Cosine.prototype
* @name pdf
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated PDF
* @see [pdf]{@link https://en.wikipedia.org/wiki/Probability_density_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.pdf( 0.8 );
* // returns 0.198
*/
setReadOnly( Cosine.prototype, 'pdf', cosinePDF );

/**
* Evaluates the quantile function.
*
* @memberof Cosine.prototype
* @name quantile
* @type {Function}
* @param {Probability} p - input probability
* @returns {number} evaluated quantile function
* @see [quantile function]{@link https://en.wikipedia.org/wiki/Quantile_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.quantile( 0.5 );
* // returns ~2.0
*/
setReadOnly( Cosine.prototype, 'quantile', cosineQuantile );

// EXPORTS //

module.exports = Cosine;
<commit_msg>Re-arrange JSDoc tags<commit_after>/* eslint-disable no-restricted-syntax, no-invalid-this */
'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isPositive = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isnan = require( '@stdlib/assert/is-nan' );
var kurtosis = require( '@stdlib/math/base/dists/cosine/kurtosis' );
var mean = require( '@stdlib/math/base/dists/cosine/mean' );
var median = require( '@stdlib/math/base/dists/cosine/median' );
var mode = require( '@stdlib/math/base/dists/cosine/mode' );
var skewness = require( '@stdlib/math/base/dists/cosine/skewness' );
var stdev = require( '@stdlib/math/base/dists/cosine/stdev' );
var variance = require( '@stdlib/math/base/dists/cosine/variance' );
var cdf = require( '@stdlib/math/base/dists/cosine/cdf' );
var logcdf = require( '@stdlib/math/base/dists/cosine/logcdf' );
var logpdf = require( '@stdlib/math/base/dists/cosine/logpdf' );
var mgf = require( '@stdlib/math/base/dists/cosine/mgf' );
var pdf = require( '@stdlib/math/base/dists/cosine/pdf' );
var quantile = require( '@stdlib/math/base/dists/cosine/quantile' );

// FUNCTIONS //

/**
* Evaluates the cumulative distribution function (CDF).
*
* @private
* @param {number} x - input value
* @returns {Probability} evaluated CDF
*/
function cosineCDF( x ) {
	return cdf( x, this.mu, this.s );
}

/**
* Evaluates the natural logarithm of the cumulative distribution function (logCDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated logCDF
*/
function cosineLogCDF( x ) {
	return logcdf( x, this.mu, this.s );
}

/**
* Evaluates the natural logarithm of the probability density function (logPDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated logPDF
*/
function cosineLogPDF( x ) {
	return logpdf( x, this.mu, this.s );
}

/**
* Evaluates the moment-generating function (MGF).
*
* @private
* @param {number} t - input value
* @returns {number} evaluated MGF
*/
function cosineMGF( t ) {
	return mgf( t, this.mu, this.s );
}

/**
* Evaluates the probability density function (PDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated PDF
*/
function cosinePDF( x ) {
	return pdf( x, this.mu, this.s );
}

/**
* Evaluates the quantile function.
*
* @private
* @param {Probability} p - input probability
* @returns {number} evaluated quantile function
*/
function cosineQuantile( p ) {
	return quantile( p, this.mu, this.s );
}

// MAIN //

/**
* Cosine distribution constructor.
*
* @constructor
* @param {number} [mu=0.0] - location parameter
* @param {PositiveNumber} [s=1.0] - scale parameter
* @throws {TypeError} `s` must be a positive number
* @returns {Cosine} distribution instance
*
* @example
* var cosine = new Cosine( 1.0, 1.0 );
*
* var y = cosine.cdf( 1.5 );
* // returns ~0.909
*
* var mu = cosine.mean;
* // returns 1.0
*/
function Cosine() {
	var mu;
	var s;
	if ( !(this instanceof Cosine) ) {
		if ( arguments.length === 0 ) {
			return new Cosine();
		}
		return new Cosine( arguments[ 0 ], arguments[ 1 ] );
	}
	if ( arguments.length ) {
		mu = arguments[ 0 ];
		s = arguments[ 1 ];
		if ( !isNumber( mu ) || isnan( mu ) ) {
			throw new TypeError( 'invalid input argument. Location parameter `mu` must be a number primitive. Value: `' + mu + '`' );
		}
		if ( !isPositive( s ) ) {
			throw new TypeError( 'invalid input argument. Scale parameter `s` must be a positive number. Value: `' + s + '`' );
		}
	} else {
		mu = 0.0;
		s = 1.0;
	}
	Object.defineProperty( this, 'mu', {
		'configurable': false,
		'enumerable': true,
		'get': function get() {
			return mu;
		},
		'set': function set( value ) {
			if ( !isNumber( value ) || isnan( value ) ) {
				throw new TypeError( 'invalid value. Must be a number primitive. Value: `' + value + '`' );
			}
			mu = value;
		}
	});
	Object.defineProperty( this, 's', {
		'configurable': false,
		'enumerable': true,
		'get': function get() {
			return s;
		},
		'set': function set( value ) {
			if ( !isPositive( value ) ) {
				throw new TypeError( 'invalid value. Must be a positive number. Value: `' + value + '`' );
			}
			s = value;
		}
	});
	return this;
}

/**
* Cosine distribution excess kurtosis.
*
* @name kurtosis
* @memberof Cosine.prototype
* @type {number}
* @see [kurtosis]{@link https://en.wikipedia.org/wiki/Kurtosis}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.kurtosis;
* // returns ~-0.594
*/
Object.defineProperty( Cosine.prototype, 'kurtosis', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return kurtosis( this.mu, this.s );
	}
});

/**
* Cosine distribution expected value.
*
* @name mean
* @memberof Cosine.prototype
* @type {number}
* @see [expected value]{@link https://en.wikipedia.org/wiki/Expected_value}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.mean;
* // returns 4.0
*/
Object.defineProperty( Cosine.prototype, 'mean', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return mean( this.mu, this.s );
	}
});

/**
* Cosine distribution median.
*
* @name median
* @memberof Cosine.prototype
* @type {number}
* @see [median]{@link https://en.wikipedia.org/wiki/Median}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.median;
* // returns 4.0
*/
Object.defineProperty( Cosine.prototype, 'median', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return median( this.mu, this.s );
	}
});

/**
* Cosine distribution mode.
*
* @name mode
* @memberof Cosine.prototype
* @type {number}
* @see [mode]{@link https://en.wikipedia.org/wiki/Mode_%28statistics%29}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.mode;
* // returns 4.0
*/
Object.defineProperty( Cosine.prototype, 'mode', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return mode( this.mu, this.s );
	}
});

/**
* Cosine distribution skewness.
*
* @name skewness
* @memberof Cosine.prototype
* @type {number}
* @see [skewness]{@link https://en.wikipedia.org/wiki/Skewness}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.skewness;
* // returns 0.0
*/
Object.defineProperty( Cosine.prototype, 'skewness', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return skewness( this.mu, this.s );
	}
});

/**
* Cosine distribution standard deviation.
*
* @name stdev
* @memberof Cosine.prototype
* @type {number}
* @see [standard deviation]{@link https://en.wikipedia.org/wiki/Standard_deviation}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.stdev;
* // returns ~4.338
*/
Object.defineProperty( Cosine.prototype, 'stdev', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return stdev( this.mu, this.s );
	}
});

/**
* Cosine distribution variance.
*
* @name variance
* @memberof Cosine.prototype
* @type {number}
* @see [variance]{@link https://en.wikipedia.org/wiki/Variance}
*
* @example
* var cosine = new Cosine( 4.0, 12.0 );
*
* var v = cosine.variance;
* // returns ~18.819
*/
Object.defineProperty( Cosine.prototype, 'variance', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return variance( this.mu, this.s );
	}
});

/**
* Evaluates the cumulative distribution function (CDF).
*
* @name cdf
* @memberof Cosine.prototype
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated CDF
* @see [cdf]{@link https://en.wikipedia.org/wiki/Cumulative_distribution_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.cdf( 0.5 );
* // returns ~0.165
*/
setReadOnly( Cosine.prototype, 'cdf', cosineCDF );

/**
* Evaluates the natural logarithm of the cumulative distribution function (logCDF).
*
* @name logcdf
* @memberof Cosine.prototype
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated logCDF
* @see [cdf]{@link https://en.wikipedia.org/wiki/Cumulative_distribution_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.logcdf( 0.5 );
* // returns ~-1.802
*/
setReadOnly( Cosine.prototype, 'logcdf', cosineLogCDF );

/**
* Evaluates the natural logarithm of the probability density function (logPDF).
*
* @name logpdf
* @memberof Cosine.prototype
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated logPDF
* @see [pdf]{@link https://en.wikipedia.org/wiki/Probability_density_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.logpdf( 0.8 );
* // returns ~-1.617
*/
setReadOnly( Cosine.prototype, 'logpdf', cosineLogPDF );

/**
* Evaluates the moment-generating function (MGF).
*
* @name mgf
* @memberof Cosine.prototype
* @type {Function}
* @param {number} t - input value
* @returns {number} evaluated MGF
* @see [mgf]{@link https://en.wikipedia.org/wiki/Moment-generating_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.mgf( 0.2 );
* // returns ~1.555
*/
setReadOnly( Cosine.prototype, 'mgf', cosineMGF );

/**
* Evaluates the probability density function (PDF).
*
* @name pdf
* @memberof Cosine.prototype
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated PDF
* @see [pdf]{@link https://en.wikipedia.org/wiki/Probability_density_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.pdf( 0.8 );
* // returns 0.198
*/
setReadOnly( Cosine.prototype, 'pdf', cosinePDF );

/**
* Evaluates the quantile function.
*
* @name quantile
* @memberof Cosine.prototype
* @type {Function}
* @param {Probability} p - input probability
* @returns {number} evaluated quantile function
* @see [quantile function]{@link https://en.wikipedia.org/wiki/Quantile_function}
*
* @example
* var cosine = new Cosine( 2.0, 4.0 );
*
* var v = cosine.quantile( 0.5 );
* // returns ~2.0
*/
setReadOnly( Cosine.prototype, 'quantile', cosineQuantile );

// EXPORTS //

module.exports = Cosine;
<|endoftext|>


<commit_before>/*global angular*/

/*
 * An HTTP Plugin for PhoneGap.
 */

var exec = require('cordova/exec');

var http = {
    useBasicAuth: function(username, password, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "useBasicAuth", [username, password]);
    },
    setHeader: function(header, value, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "setHeader", [header, value]);
    },
    enableSSLPinning: function(enable, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "enableSSLPinning", [enable]);
    },
    acceptAllCerts: function(allow, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "acceptAllCerts", [allow]);
    },
    setTimeouts: function(connectionTimeout, readTimeout, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "setTimeouts", [connectionTimeout, readTimeout]);
    },
    head: function(url, params, headers, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "head", [url, params, headers]);
    },
    post: function(url, params, headers, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "post", [url, params, headers]);
    },
    put: function(url, params, headers, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "put", [url, params, headers]);
    },
    delete: function(url, params, headers, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "delete", [url, params, headers]);
    },
    get: function(url, params, headers, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "get", [url, params, headers]);
    },
    uploadFile: function(url, params, headers, filePath, name, success, failure) {
        return exec(success, failure, "CordovaHttpPlugin", "uploadFile", [url, params, headers, filePath, name]);
    },
    downloadFile: function(url, params, headers, filePath, success, failure) {
        /*
         *
         * Licensed to the Apache Software Foundation (ASF) under one
         * or more contributor license agreements.  See the NOTICE file
         * distributed with this work for additional information
         * regarding copyright ownership.  The ASF licenses this file
         * to you under the Apache License, Version 2.0 (the
         * "License"); you may not use this file except in compliance
         * with the License.  You may obtain a copy of the License at
         *
         *   http://www.apache.org/licenses/LICENSE-2.0
         *
         * Unless required by applicable law or agreed to in writing,
         * software distributed under the License is distributed on an
         * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
         * KIND, either express or implied.  See the License for the
         * specific language governing permissions and limitations
         * under the License.
         *
         * Modified by Andrew Stephan for Sync OnSet
         *
        */
        var win = function(result) {
            var entry = new (require('org.apache.cordova.file.FileEntry'))();
            entry.isDirectory = false;
            entry.isFile = true;
            entry.name = result.file.name;
            entry.fullPath = result.file.fullPath;
            success(entry);
        };
        return exec(win, failure, "CordovaHttpPlugin", "downloadFile", [url, params, headers, filePath]);
    }
};

module.exports = http;

if (typeof angular !== "undefined") {
    angular.module('cordovaHTTP', []).factory('cordovaHTTP', function($timeout, $q) {
        function makePromise(fn, args, async) {
            var deferred = $q.defer();

            var success = function(response) {
                if (async) {
                    $timeout(function() {
                        deferred.resolve(response);
                    });
                } else {
                    deferred.resolve(response);
                }
            };

            var fail = function(response) {
                if (async) {
                    $timeout(function() {
                        deferred.reject(response);
                    });
                } else {
                    deferred.reject(response);
                }
            };

            args.push(success);
            args.push(fail);

            fn.apply(http, args);

            return deferred.promise;
        }

        var cordovaHTTP = {
            useBasicAuth: function(username, password) {
                return makePromise(http.useBasicAuth, [username, password]);
            },
            setHeader: function(header, value) {
                return makePromise(http.setHeader, [header, value]);
            },
            enableSSLPinning: function(enable) {
                return makePromise(http.enableSSLPinning, [enable]);
            },
            acceptAllCerts: function(allow) {
                return makePromise(http.acceptAllCerts, [allow]);
            },
            setTimeouts: function(connectionTimeout, readTimeout) {
                return makePromise(http.setTimeouts, [connectionTimeout, readTimeout]);
            },
            head: function(url, params, headers) {
                return makePromise(http.head, [url, params, headers], true);
            },
            post: function(url, params, headers) {
                return makePromise(http.post, [url, params, headers], true);
            },
            put: function(url, params, headers) {
                return makePromise(http.put, [url, params, headers], true);
            },
            delete: function(url, params, headers) {
                return makePromise(http.delete, [url, params, headers], true);
            },
            get: function(url, params, headers) {
                return makePromise(http.get, [url, params, headers], true);
            },
            uploadFile: function(url, params, headers, filePath, name) {
                return makePromise(http.uploadFile, [url, params, headers, filePath, name], true);
            },
            downloadFile: function(url, params, headers, filePath) {
                return makePromise(http.downloadFile, [url, params, headers, filePath], true);
            }
        };
        return cordovaHTTP;
    });
} else {
    window.cordovaHTTP = http;
}
<commit_msg>do not initialize angular until deviceready<commit_after>/*global angular*/

/*
 * An HTTP Plugin for PhoneGap.
 */

var exec = require('cordova/exec');

var http = {
	useBasicAuth: function(username, password, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'useBasicAuth', [username, password]);
	},
	setHeader: function(header, value, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'setHeader', [header, value]);
	},
	enableSSLPinning: function(enable, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'enableSSLPinning', [enable]);
	},
	acceptAllCerts: function(allow, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'acceptAllCerts', [allow]);
	},
	setTimeouts: function(connectionTimeout, readTimeout, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'setTimeouts', [connectionTimeout, readTimeout]);
	},
	head: function(url, params, headers, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'head', [url, params, headers]);
	},
	post: function(url, params, headers, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'post', [url, params, headers]);
	},
	put: function(url, params, headers, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'put', [url, params, headers]);
	},
	delete: function(url, params, headers, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'delete', [url, params, headers]);
	},
	get: function(url, params, headers, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'get', [url, params, headers]);
	},
	uploadFile: function(url, params, headers, filePath, name, success, failure) {
		return exec(success, failure, 'CordovaHttpPlugin', 'uploadFile', [url, params, headers, filePath, name]);
	},
	downloadFile: function(url, params, headers, filePath, success, failure) {
		/*
		 *
		 * Licensed to the Apache Software Foundation (ASF) under one
		 * or more contributor license agreements.  See the NOTICE file
		 * distributed with this work for additional information
		 * regarding copyright ownership.  The ASF licenses this file
		 * to you under the Apache License, Version 2.0 (the
		 * "License"); you may not use this file except in compliance
		 * with the License.  You may obtain a copy of the License at
		 *
		 *   http://www.apache.org/licenses/LICENSE-2.0
		 *
		 * Unless required by applicable law or agreed to in writing,
		 * software distributed under the License is distributed on an
		 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
		 * KIND, either express or implied.  See the License for the
		 * specific language governing permissions and limitations
		 * under the License.
		 *
		 * Modified by Andrew Stephan for Sync OnSet
		 *
		*/
		var win = function(result) {
			var entry = new (require('org.apache.cordova.file.FileEntry'))();
			entry.isDirectory = false;
			entry.isFile = true;
			entry.name = result.file.name;
			entry.fullPath = result.file.fullPath;
			success(entry);
		};
		return exec(win, failure, 'CordovaHttpPlugin', 'downloadFile', [url, params, headers, filePath]);
	}
};

module.exports = http;
window.cordovaHTTP = http;

var configureAngular = function() {
	if (typeof angular !== 'undefined') {
		angular.module('cordovaHTTP', []).factory('cordovaHTTP', function($timeout, $q) {
			function makePromise(fn, args, async) {
				var deferred = $q.defer();

				var success = function(response) {
					if (async) {
						$timeout(function() {
							deferred.resolve(response);
						});
					} else {
						deferred.resolve(response);
					}
				};

				var fail = function(response) {
					if (async) {
						$timeout(function() {
							deferred.reject(response);
						});
					} else {
						deferred.reject(response);
					}
				};

				args.push(success);
				args.push(fail);

				fn.apply(http, args);

				return deferred.promise;
			}

			var cordovaHTTP = {
				useBasicAuth: function(username, password) {
					return makePromise(http.useBasicAuth, [username, password]);
				},
				setHeader: function(header, value) {
					return makePromise(http.setHeader, [header, value]);
				},
				enableSSLPinning: function(enable) {
					return makePromise(http.enableSSLPinning, [enable]);
				},
				acceptAllCerts: function(allow) {
					return makePromise(http.acceptAllCerts, [allow]);
				},
				setTimeouts: function(connectionTimeout, readTimeout) {
					return makePromise(http.setTimeouts, [connectionTimeout, readTimeout]);
				},
				head: function(url, params, headers) {
					return makePromise(http.head, [url, params, headers], true);
				},
				post: function(url, params, headers) {
					return makePromise(http.post, [url, params, headers], true);
				},
				put: function(url, params, headers) {
					return makePromise(http.put, [url, params, headers], true);
				},
				delete: function(url, params, headers) {
					return makePromise(http.delete, [url, params, headers], true);
				},
				get: function(url, params, headers) {
					return makePromise(http.get, [url, params, headers], true);
				},
				uploadFile: function(url, params, headers, filePath, name) {
					return makePromise(http.uploadFile, [url, params, headers, filePath, name], true);
				},
				downloadFile: function(url, params, headers, filePath) {
					return makePromise(http.downloadFile, [url, params, headers, filePath], true);
				}
			};
			return cordovaHTTP;
		});
	}
};

document.addEventListener('deviceready', configureAngular, false);
<|endoftext|>