<commit_before>// Aliases for major page elements
var el = {
	number: document.getElementById('number'),
	name: document.getElementById('name'),
	bg: document.getElementById('background'),
	location: document.getElementById('location')
};

// Pick rand team from team array in data.js
var teamNum = teams[parseInt(Math.random() * teams.length)];
// Put team number on page
el.number.innerHTML = '' + teamNum + '';

try {
	// Create request to get data from TBA
	var req = new XMLHttpRequest();
	// Get data for team
	req.open('GET', 'https://www.thebluealliance.com/api/v2/team/frc' + teamNum + '?X-TBA-App-Id=erikboesen:frcnewtab:v1.0');
	// Send empty data for conclusion
	req.send();
	// When the data is ready
	req.onreadystatechange = function() {
		if (req.readyState == 4 && req.status == 200) {
			// Parse the data into JSON to get it ready to be used
			team = JSON.parse(req.responseText);
			// Set team name on page
			el.name.innerHTML = (team.website && team.website !== 'Coming Soon') ? '' + team.nickname + '' : team.nickname;
			el.location.innerHTML = team.location;
		}
	};
} catch (e) {}

// Source it to a random photo in the bg folder.
var src = 'bg/' + (Math.floor(Math.random() * 10) + 1) + '.jpg';

// Make a new request to get list of team media from TBA
var mediaReq = new XMLHttpRequest();
// Set function to be executed when the data is ready
mediaReq.onreadystatechange = function() {
	if (mediaReq.readyState == 4 && mediaReq.status == 200) {
		// Parse data for processing
		var media = [];
		try {
			media = JSON.parse(mediaReq.responseText);
		} catch (e) {}
        console.log(media.length);
		if (media.length > 0) {
			var target;
			// Go through every piece of media
			for (i = 0; i < media.length; i++) {
				// Find media that's an image
				if (media[i].type === 'imgur' || media[i].type === 'cdphotothread') {
					// Set target to that image and break loop.
					target = i;
					break;
				}
			}
			// Check where the media is sourced from. Use this to build a link to the image.
			if (target !== null) {
                console.log('targeted ', media[target].type);
				switch (media[target].type) {
					case 'imgur':
						src = 'http://i.imgur.com/' + media[target].foreign_key + '.png';
						break;
					case 'cdphotothread':
						src = 'https://www.chiefdelphi.com/media/img/' + media[target].details.image_partial;
						break;
				}
			}
		}
        // Log URL of background image
        console.log(src);
        // Put the image into the background (see below).
        renderImage();
	}
};

// Get data
mediaReq.open('GET', 'https://www.thebluealliance.com/api/v2/team/frc' + teamNum + '/media?X-TBA-App-Id=erikboesen:frcnewtab:v1.0');
mediaReq.send();

function renderImage() {
    // Create image. This will be used to check if the image is smaller than the window.
    var img = new Image();
    // Give it the proper source.
    img.src = src;
    // When the source is done loading,
    img.onload = function() {
    	// Check if the image is smaller than the window.
    	if (img.naturalWidth >= window.innerWidth) {
    		// If it is, blur the background image.
    		el.bg.style['-webkit-filter'] = 'none';
    	}
    };

    // Set the src of the real background image.
    el.bg.style.backgroundImage = 'url(' + src + ')';
}

// TODO: This process could probably be way more efficient. Find a way to improve.
<commit_msg>Low contrast for background. Just a test. Looks nice for now<commit_after>// Aliases for major page elements
var el = {
	number: document.getElementById('number'),
	name: document.getElementById('name'),
	bg: document.getElementById('background'),
	location: document.getElementById('location')
};

// Pick rand team from team array in data.js
var teamNum = teams[parseInt(Math.random() * teams.length)];
// Put team number on page
el.number.innerHTML = '' + teamNum + '';

try {
	// Create request to get data from TBA
	var req = new XMLHttpRequest();
	// Get data for team
	req.open('GET', 'https://www.thebluealliance.com/api/v2/team/frc' + teamNum + '?X-TBA-App-Id=erikboesen:frcnewtab:v1.0');
	// Send empty data for conclusion
	req.send();
	// When the data is ready
	req.onreadystatechange = function() {
		if (req.readyState == 4 && req.status == 200) {
			// Parse the data into JSON to get it ready to be used
			team = JSON.parse(req.responseText);
			// Set team name on page
			el.name.innerHTML = (team.website && team.website !== 'Coming Soon') ? '' + team.nickname + '' : team.nickname;
			el.location.innerHTML = team.location;
		}
	};
} catch (e) {}

// Source it to a random photo in the bg folder.
var src = 'bg/' + (Math.floor(Math.random() * 10) + 1) + '.jpg';

// Make a new request to get list of team media from TBA
var mediaReq = new XMLHttpRequest();
// Set function to be executed when the data is ready
mediaReq.onreadystatechange = function() {
	if (mediaReq.readyState == 4 && mediaReq.status == 200) {
		// Parse data for processing
		var media = [];
		try {
			media = JSON.parse(mediaReq.responseText);
		} catch (e) {}
        console.log(media.length);
		if (media.length > 0) {
			var target;
			// Go through every piece of media
			for (i = 0; i < media.length; i++) {
				// Find media that's an image
				if (media[i].type === 'imgur' || media[i].type === 'cdphotothread') {
					// Set target to that image and break loop.
					target = i;
					break;
				}
			}
			// Check where the media is sourced from. Use this to build a link to the image.
			if (target !== null) {
                console.log('targeted ', media[target].type);
				switch (media[target].type) {
					case 'imgur':
						src = 'http://i.imgur.com/' + media[target].foreign_key + '.png';
						break;
					case 'cdphotothread':
						src = 'https://www.chiefdelphi.com/media/img/' + media[target].details.image_partial;
						break;
				}
			}
		}
        // Log URL of background image
        console.log(src);
        // Put the image into the background (see below).
        renderImage();
	}
};

// Get data
mediaReq.open('GET', 'https://www.thebluealliance.com/api/v2/team/frc' + teamNum + '/media?X-TBA-App-Id=erikboesen:frcnewtab:v1.0');
mediaReq.send();

function renderImage() {
    // Create image. This will be used to check if the image is smaller than the window.
    var img = new Image();
    // Give it the proper source.
    img.src = src;
    // When the source is done loading,
    img.onload = function() {
    	// Check if the image is smaller than the window.
    	if (img.naturalWidth >= window.innerWidth) {
    		// If it is, blur the background image.
    		el.bg.style['-webkit-filter'] = 'contrast(0.7)';
    	}
    };

    // Set the src of the real background image.
    el.bg.style.backgroundImage = 'url(' + src + ')';
}

// TODO: This process could probably be way more efficient. Find a way to improve.
<|endoftext|>


<commit_before>// A script that uses Cheerio to scrape course evaluation information from the Registrar
// At the moment this script does not save the data anywhere

// Load external dependencies
var http = require('https')
var cheerio = require('cheerio')
var prompt = require('prompt')

// Load config variables from the .env file
require('dotenv').config()

// Load internal modules
var courseModel = require('../models/course.js')
require('../models/semester.js')
require('../controllers/database.js')

// Load a request from the server and call the function externalCallback
var loadPage = function (term, courseID, externalCallback) {
  // Define the HTTP request options
  var options = {
    host: 'registrar.princeton.edu',
    path: '/course-offerings/course_details.xml?' + 'term=' + term + '&courseid=' + courseID
  }

  // Make the request
  var req = http.request(options, function (res) {
    var str = ''

    // Append received data to already received data
    res.on('data', function (chunk) {
      str += chunk
    })

    // Handle data once it has all been received
    res.on('end', function () {
      externalCallback(str)
    })

    res.on('error', function (err) {
      console.log(err)
    })
  })
  req.end()
}

var extractSingle = function ($, container, title) {
  var inside
  var lines = container.first().contents().filter(function () {
    if ($(this).is('strong')) {
      inside = $(this).text().indexOf(title) > -1
    }
    return (this.nodeType === 3 && inside)
  }).text().split('\n')
  for (var lineIndex in lines) {
    var line = lines[lineIndex].trim()
    if (line.length > 1 && line.substring(line.length - 2) === '..') {
      line = line.substring(0, line.length - 1)
    }
    if (line.length > 0) {
      return line
    }
  }
}

// Return the course evaluation data for the given semester/courseID to the function callback
var getCourseListingData = function (semester, courseID, callback) {
  loadPage(semester, courseID, function (data) {
    console.log('\tRecieved data for course %s in semester %s.', courseID, semester)

            // Prepare to Extract Data From Page
    var $ = cheerio.load(data)
    var results = {}
    var detailsContainer = $('#timetable')

            // Get Distrubution Area
    const regex = /\((LA|SA|HA|EM|EC|QR|STN|STL)\)/
    let m
    if ((m = regex.exec(detailsContainer.text())) !== null) {
      results.distribution = m[0].substring(1, m[0].length - 1)
    }

    var attributes = detailsContainer.find('em').first().text()

            // Get PDF Status
    results.pdf = {
      required: (attributes.indexOf('P/D/F Only') > -1),
      permitted: (attributes.indexOf('P/D/F') > -1)
    }

      // Get Audit Status
    results.audit = (attributes.indexOf('Audit') > -1)

      // Get Assignments
    var assignments = extractSingle($, detailsContainer, 'Reading/Writing assignments')
    if (typeof (assignments) !== 'undefined') {
      results.assignments = assignments
    }

            // Get Grading Components
    var insideGrading
    var gradingComponentsRaw = detailsContainer.first().contents().filter(function () {
      if ($(this).is('strong, b')) {
        insideGrading = $(this).text().indexOf('Requirements/Grading') > -1
      }
      return (this.nodeType === 3 && insideGrading)
    }).text()
    var gradingComponentLines = gradingComponentsRaw.split('\n')
    results.grading = []
    for (var gradingComponentLinesIndex in gradingComponentLines) {
      var thisGradingComponentLine = gradingComponentLines[gradingComponentLinesIndex].trim()
      if (thisGradingComponentLine.length > 0) {
        var thisGradingComponent = thisGradingComponentLine.split('-')
        results.grading.push({
          component: thisGradingComponent[0].trim(),
          weight: parseInt(thisGradingComponent[1].trim())
        })
      }
    }

            // Get Prerequisites
    var prerequisites = extractSingle($, detailsContainer, 'Prerequisites and Restrictions')
    if (typeof (prerequisites) !== 'undefined') {
      results.prerequisites = prerequisites
    }

            // Get Equivalent Courses
    var equivalentcourses = extractSingle($, detailsContainer, 'Equivalent Courses')
    if (typeof (equivalentcourses) !== 'undefined') {
      results.equivalentcourses = equivalentcourses
    }

            // Get Other Information
    var otherinformation = extractSingle($, detailsContainer, 'Other information')
    if (typeof (otherinformation) !== 'undefined') {
      results.otherinformation = otherinformation
    }

            // Get Other Requirements
    var otherrequirements = extractSingle($, detailsContainer, 'Other Requirements')
    if (typeof (otherrequirements) !== 'undefined') {
      results.otherrequirements = otherrequirements
    }

            // Get Website
    var website = detailsContainer.find('strong:contains(Website)').next('a').attr('href')
    if (typeof (website) !== 'undefined') {
      results.website = website
    }

    callback(results)
  })
}

// Find an array of courses and populate the courses with the course evaluation information from the Registrar. Save the data to the database
courseModel.find({audit:{$exists:false}, semester: 1182}, function (error, courses) {
  if (error) {
    console.log(error)
  }

  // Check that the user is aware of the number of requests they are about to send
  console.log('You are about to request the extended course details for %d courses.', courses.length)
  prompt.start()
  prompt.get({name: 'confirmation', description: 'Are you sure you want to do this? (y/n)'}, function (err, result) {
    if (err) {
      console.log(err)
    }
    if (result.confirmation === 'y') {
      var coursesPendingProcessing = courses.length
      var courseIndex = 0

      // Every 200ms, request the details for another course
      // (We must stagger our requests to avoid overloading the Registrar's server)
      var interval = setInterval(function () {
        var thisCourse = courses[courseIndex++]

            // If there are no more courses, cease sending requests
        if (typeof (thisCourse) === 'undefined') {
          clearInterval(interval)
          return
        }

        console.log('Processing course %s in semester %d. (Course %d of %d).', thisCourse.courseID, thisCourse.semester._id, courseIndex, courses.length)

        // Fetch the evaluation data
        getCourseListingData(thisCourse.semester._id, thisCourse.courseID, function (courseData) {
          for (var index in courseData) {
            thisCourse[index] = courseData[index]
          }

          thisCourse.save(function (error) {
            if (error) {
              console.log(error)
            }
            coursesPendingProcessing--
            // Quit if there are no more courses pending processing
            if (coursesPendingProcessing <= 1) {
              console.log('Fetched and saved all the requested extended course details.')
              process.exit(0)
            }
          })
        })
      }, 100)
    } else {
      process.exit(0)
    }
  })
})
<commit_msg>Fixing spacing<commit_after>// A script that uses Cheerio to scrape course evaluation information from the Registrar
// At the moment this script does not save the data anywhere

// Load external dependencies
var http = require('https')
var cheerio = require('cheerio')
var prompt = require('prompt')

// Load config variables from the .env file
require('dotenv').config()

// Load internal modules
var courseModel = require('../models/course.js')
require('../models/semester.js')
require('../controllers/database.js')

// Load a request from the server and call the function externalCallback
var loadPage = function (term, courseID, externalCallback) {
  // Define the HTTP request options
  var options = {
    host: 'registrar.princeton.edu',
    path: '/course-offerings/course_details.xml?' + 'term=' + term + '&courseid=' + courseID
  }

  // Make the request
  var req = http.request(options, function (res) {
    var str = ''

    // Append received data to already received data
    res.on('data', function (chunk) {
      str += chunk
    })

    // Handle data once it has all been received
    res.on('end', function () {
      externalCallback(str)
    })

    res.on('error', function (err) {
      console.log(err)
    })
  })
  req.end()
}

var extractSingle = function ($, container, title) {
  var inside
  var lines = container.first().contents().filter(function () {
    if ($(this).is('strong')) {
      inside = $(this).text().indexOf(title) > -1
    }
    return (this.nodeType === 3 && inside)
  }).text().split('\n')
  for (var lineIndex in lines) {
    var line = lines[lineIndex].trim()
    if (line.length > 1 && line.substring(line.length - 2) === '..') {
      line = line.substring(0, line.length - 1)
    }
    if (line.length > 0) {
      return line
    }
  }
}

// Return the course evaluation data for the given semester/courseID to the function callback
var getCourseListingData = function (semester, courseID, callback) {
  loadPage(semester, courseID, function (data) {
    console.log('\tRecieved data for course %s in semester %s.', courseID, semester)

    // Prepare to Extract Data From Page
    var $ = cheerio.load(data)
    var results = {}
    var detailsContainer = $('#timetable')

    // Get Distrubution Area
    const regex = /\((LA|SA|HA|EM|EC|QR|STN|STL)\)/
    let m
    if ((m = regex.exec(detailsContainer.text())) !== null) {
      results.distribution = m[0].substring(1, m[0].length - 1)
    }

    var attributes = detailsContainer.find('em').first().text()

    // Get PDF Status
    results.pdf = {
      required: (attributes.indexOf('P/D/F Only') > -1),
      permitted: (attributes.indexOf('P/D/F') > -1)
    }

    // Get Audit Status
    results.audit = (attributes.indexOf('Audit') > -1)

    // Get Assignments
    var assignments = extractSingle($, detailsContainer, 'Reading/Writing assignments')
    if (typeof (assignments) !== 'undefined') {
      results.assignments = assignments
    }

    // Get Grading Components
    var insideGrading
    var gradingComponentsRaw = detailsContainer.first().contents().filter(function () {
      if ($(this).is('strong, b')) {
        insideGrading = $(this).text().indexOf('Requirements/Grading') > -1
      }
      return (this.nodeType === 3 && insideGrading)
    }).text()
    var gradingComponentLines = gradingComponentsRaw.split('\n')
    results.grading = []
    for (var gradingComponentLinesIndex in gradingComponentLines) {
      var thisGradingComponentLine = gradingComponentLines[gradingComponentLinesIndex].trim()
      if (thisGradingComponentLine.length > 0) {
        var thisGradingComponent = thisGradingComponentLine.split('-')
        results.grading.push({
          component: thisGradingComponent[0].trim(),
          weight: parseInt(thisGradingComponent[1].trim())
        })
      }
    }

    // Get Prerequisites
    var prerequisites = extractSingle($, detailsContainer, 'Prerequisites and Restrictions')
    if (typeof (prerequisites) !== 'undefined') {
      results.prerequisites = prerequisites
    }

    // Get Equivalent Courses
    var equivalentcourses = extractSingle($, detailsContainer, 'Equivalent Courses')
    if (typeof (equivalentcourses) !== 'undefined') {
      results.equivalentcourses = equivalentcourses
    }

    // Get Other Information
    var otherinformation = extractSingle($, detailsContainer, 'Other information')
    if (typeof (otherinformation) !== 'undefined') {
      results.otherinformation = otherinformation
    }

    // Get Other Requirements
    var otherrequirements = extractSingle($, detailsContainer, 'Other Requirements')
    if (typeof (otherrequirements) !== 'undefined') {
      results.otherrequirements = otherrequirements
    }

    // Get Website
    var website = detailsContainer.find('strong:contains(Website)').next('a').attr('href')
    if (typeof (website) !== 'undefined') {
      results.website = website
    }

    callback(results)
  })
}

// Find an array of courses and populate the courses with the course evaluation information from the Registrar. Save the data to the database
courseModel.find({audit: {$exists: false}, semester: 1182}, function (error, courses) {
  if (error) {
    console.log(error)
  }

  // Check that the user is aware of the number of requests they are about to send
  console.log('You are about to request the extended course details for %d courses.', courses.length)
  prompt.start()
  prompt.get({name: 'confirmation', description: 'Are you sure you want to do this? (y/n)'}, function (err, result) {
    if (err) {
      console.log(err)
    }
    if (result.confirmation === 'y') {
      var coursesPendingProcessing = courses.length
      var courseIndex = 0

      // Every 200ms, request the details for another course
      // (We must stagger our requests to avoid overloading the Registrar's server)
      var interval = setInterval(function () {
        var thisCourse = courses[courseIndex++]

        // If there are no more courses, cease sending requests
        if (typeof (thisCourse) === 'undefined') {
          clearInterval(interval)
          return
        }

        console.log('Processing course %s in semester %d. (Course %d of %d).', thisCourse.courseID, thisCourse.semester._id, courseIndex, courses.length)

        // Fetch the evaluation data
        getCourseListingData(thisCourse.semester._id, thisCourse.courseID, function (courseData) {
          for (var index in courseData) {
            thisCourse[index] = courseData[index]
          }

          thisCourse.save(function (error) {
            if (error) {
              console.log(error)
            }
            coursesPendingProcessing--
            // Quit if there are no more courses pending processing
            if (coursesPendingProcessing <= 1) {
              console.log('Fetched and saved all the requested extended course details.')
              process.exit(0)
            }
          })
        })
      }, 100)
    } else {
      process.exit(0)
    }
  })
})
<|endoftext|>


<commit_before>var fs = require("fs");
var chai = require("chai");
var expect = chai.expect;

describe("API", function() {
  var apiPath = "./api";

  describe("v1", function() {
    var versionPath = apiPath + "/1";

    it("shouldn't exist", function() {
      var exists = fs.existsSync(versionPath);
      expect(exists).to.be.false;
    });
  });

  describe("v2", function() {
    var versionPath = apiPath + "/2";

    it("shouldn't exist", function() {
      var exists = fs.existsSync(versionPath);
      expect(exists).to.be.false;
    });
  });

  describe("v3", function() {
    var versionPath = apiPath + "/3";

    it("shouldn't exist", function() {
      var exists = fs.existsSync(versionPath);
      expect(exists).to.be.false;
    });
  });

  describe("v4", function() {
    var versionPath = apiPath + "/4";

    describe("sets.json", function() {
      var setsPath = versionPath + "/sets.json";
      var sets = JSON.parse(fs.readFileSync(setsPath, "utf8"));

      it("should be an array", function() {
        expect(sets).to.be.an.array;
      });

      it("should have between 8 and 10 sets", function() {
        expect(sets).to.have.length.within(8, 10);
      });

      sets.forEach(function(set) {
        describe(set.name, function() {
          describe("name", function() {
            var name = set.name;

            it("should be a string", function() {
              expect(name).to.be.a.string;
            });

            it("should have a nonzero length", function() {
              expect(name).to.not.have.length(0);
            });
          });

          describe("block", function() {
            var block = set.block;

            it("should be a string", function() {
              expect(block).to.be.a.string;
            });

            it("should have a nonzero length", function() {
              expect(block).to.not.have.length(0);
            });

            it("should be the same as the previous set's block or equal to this set's name", function() {
              var validNames = new Set([set.name]);
              if (sets.indexOf(set) > 0) {
                validNames.add(sets[sets.indexOf(set) - 1].block);
              }

              expect(block).to.be.oneOf([...validNames]);
            });
          });

          describe("code", function() {
            var code = set.code;

            it("should be a string", function() {
              expect(code).to.be.a.string;
            });

            it("should be three characters", function() {
              expect(code).to.have.length(3);
            });

            it("should be all caps", function() {
              expect(code).to.equal(code.toUpperCase());
            });
          });

          describe("symbol", function() {
            var symbol = set.symbol;

            it("should be absent", function() {
              expect(symbol).to.be.undefined;
            });
          });

          describe("enter date", function() {
            var enterDate = set.enter_date;

            it("should be a string", function() {
              expect(enterDate).to.be.a.string;
            });

            it("should be an ISO 8601 datetime", function() {
              expect(Date.parse(enterDate)).to.be.a.number;
            });

            it("should represent midnight", function() {
              expect(enterDate).to.contain("00:00:00.00");
            });
          });

          describe("exit date", function() {
            var exitDate = set.exit_date;

            it("should be a string or null", function() {
              expect(exitDate || "").to.be.a.string;
            });

            it("should be an ISO 8601 datetime if present", function() {
              expect(Date.parse(exitDate || "1970-01-01T00:00:00.000Z")).to.be.a.number;
            });

            it("should represent midnight if present", function() {
              expect(exitDate || "1970-01-01T00:00:00.000Z").to.contain("00:00:00.00");
            });
          });

          describe("rough exit date", function() {
            var roughExitDate = set.rough_exit_date;

            it("should be a string", function() {
              expect(roughExitDate).to.be.a.string;
            });

            it("should be QX 20XX or late 20XX", function() {
              expect(roughExitDate).to.match(/Q\d 20\d\d/);
            });
          });
        });
      });
    });
  });
});
<commit_msg>Fix Travis CI tests<commit_after>var fs = require("fs");
var chai = require("chai");
var expect = chai.expect;

describe("API", function() {
  var apiPath = "./api";

  describe("v1", function() {
    var versionPath = apiPath + "/1";

    it("shouldn't exist", function() {
      var exists = fs.existsSync(versionPath);
      expect(exists).to.be.false;
    });
  });

  describe("v2", function() {
    var versionPath = apiPath + "/2";

    it("shouldn't exist", function() {
      var exists = fs.existsSync(versionPath);
      expect(exists).to.be.false;
    });
  });

  describe("v3", function() {
    var versionPath = apiPath + "/3";

    it("shouldn't exist", function() {
      var exists = fs.existsSync(versionPath);
      expect(exists).to.be.false;
    });
  });

  describe("v4", function() {
    var versionPath = apiPath + "/4";

    describe("sets.json", function() {
      var setsPath = versionPath + "/sets.json";
      var sets = JSON.parse(fs.readFileSync(setsPath, "utf8"));

      it("should be an array", function() {
        expect(sets).to.be.an('array');
      });

      it("should have between 8 and 10 sets", function() {
        expect(sets).to.have.length.within(8, 10);
      });

      sets.forEach(function(set) {
        describe(set.name, function() {
          describe("name", function() {
            var name = set.name;

            it("should be a string", function() {
              expect(name).to.be.a.string;
            });

            it("should have a nonzero length", function() {
              expect(name).to.not.have.length(0);
            });
          });

          describe("block", function() {
            var block = set.block;

            it("should be a string", function() {
              expect(block).to.be.a.string;
            });

            it("should have a nonzero length", function() {
              expect(block).to.not.have.length(0);
            });

            it("should be the same as the previous set's block or equal to this set's name", function() {
              var validNames = new Set([set.name]);
              if (sets.indexOf(set) > 0) {
                validNames.add(sets[sets.indexOf(set) - 1].block);
              }

              expect(block).to.be.oneOf([...validNames]);
            });
          });

          describe("code", function() {
            var code = set.code;

            it("should be a string", function() {
              expect(code).to.be.a.string;
            });

            it("should be three characters", function() {
              expect(code).to.have.length(3);
            });

            it("should be all caps", function() {
              expect(code).to.equal(code.toUpperCase());
            });
          });

          describe("symbol", function() {
            var symbol = set.symbol;

            it("should be absent", function() {
              expect(symbol).to.be.undefined;
            });
          });

          describe("enter date", function() {
            var enterDate = set.enter_date;

            it("should be a string", function() {
              expect(enterDate).to.be.a.string;
            });

            it("should be an ISO 8601 datetime", function() {
              expect(Date.parse(enterDate)).to.be.a('number');
            });

            it("should represent midnight", function() {
              expect(enterDate).to.contain("00:00:00.00");
            });
          });

          describe("exit date", function() {
            var exitDate = set.exit_date;

            it("should be a string or null", function() {
              expect(exitDate || "").to.be.a.string;
            });

            it("should be an ISO 8601 datetime if present", function() {
              expect(Date.parse(exitDate || "1970-01-01T00:00:00.000Z")).to.be.a('number');
            });

            it("should represent midnight if present", function() {
              expect(exitDate || "1970-01-01T00:00:00.000Z").to.contain("00:00:00.00");
            });
          });

          describe("rough exit date", function() {
            var roughExitDate = set.rough_exit_date;

            it("should be a string", function() {
              expect(roughExitDate).to.be.a.string;
            });

            it("should be QX 20XX or late 20XX", function() {
              expect(roughExitDate).to.match(/Q\d 20\d\d/);
            });
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>$(document).ready(function(){
  $("#contact-form").submit(function(event){
    event.preventDefault();
    var userInfo = {
      first: $("#firstname").val(),
      last: $("#lastname").val(),
      email: $("#email").val(),
      message: $("#message").val()
    }
    //Use jQuery to collect the values from the fields and create a
    //JSON object containing them. Then, log the result to the console

    // Secondary Objective: Use the AJAX methods built into jQuery to send
    // The form data to http://x.mirman.org:9999. Write a callback to handle
    // the response.
  })
});
<commit_msg>4loor in Progress<commit_after>
//Use jQuery to collect the values from the fields and create a
//JSON object containing them. Then, log the result to the console

// Secondary Objective: Use the AJAX methods built into jQuery to send
// The form data to http://x.mirman.org:9999. Write a callback to handle
// the response.

function sendData() {
  $.ajax({
    url: 'x.mirman.org:1031/contact',
    type: 'POST',
    contentType: 'json',
    data: {
      $(document).on("submit", function(event) {
        event.preventDefault();
        console.log( $("#firstname").serialize())
        console.log( $("#lastname").serialize())
        console.log( $("#email").serialize())
        console.log( $("#message").serialize())
      });
    },
    dataType: 'json'
  });
  alert("json posted!");
};

/*
var userInfo = {
first: $("#firstname").serialize(),
last: $("#lastname").serialize(),
email: $("#email").serialize(),
message: $("#message").serialize()
*/
<|endoftext|>


<commit_before>/**
 * Created by Evgenii on 16.01.2017.
 */
Vue.config.debug = true;
Vue.http.headers.common['X-CSRF-TOKEN'] = document.getElementById('token').getAttribute('value');

var productVue = new Vue({

    el: "#productVue",

    data: {
        token: document.getElementById('token').getAttribute('value'),
        translate:  {},
        filterEvent: true,
        xapactEvent: true,
        paramEvent: true,
        fileEvent: true,
        product:{
            id: document.getElementById("form-data").id.value,
            images: [],
            meta_description: null,
            meta_title: null,
            title: null,
            slug: null
        },
        productsList:{
            products:{},
            pagination:{
                currentPage: {},
                lastPage: {},
                pageToGet: 1
            }
        },
        relOptions:{
            category:0,
            paginate: 20,
            search: '',
            selected: []
        },
        relatedProducts: null,
        selectedProductsIds: [],
        countryList: null
    },

    created: function () {
        if(this.product.id){
            this.$http.get('/dashboard/products/' + this.product.id + '/edit').then(function (response) {
                this.product = response.body;});
        }

        this.$http.get('/dashboard/helpers/translate').then(function (response) {
            this.translate = response;});
        this.getRelatedProducts();
    },

    computed: {
        stringImagesIds: function(){
            var images = [];
            for(var i = 0, len = this.product.images.length; i < len; i++ ){
                images[i] = this.product.images[i].id;
            }
            return images.join(',');
        },

        coountTitle: function () {
            if(this.product.id){
                return this.product.meta_title.length
            }else{
                return 0;
            }
        },

        coountDescription: function () {
            if(this.product.id){
                return this.product.meta_description.length
            }else{
                return 0;
            }
        },
    },

    methods: {

        makeSlug: function () {
            this.product.slug = this.prepareSlug()
        },

        prepareSlug: function () {
            var answer = '',
                title = this.product.title,
                translate = this.translate;

            for (var i in title) {
                if (translate.hasOwnProperty(title[i])) {
                    if (translate[title[i]] !== undefined) {
                        answer += translate[title[i]];
                    }
                } else {
                    answer += title[i];
                }
            }

            return answer.toLocaleLowerCase()
                .replace(/[^a-z0-9-]/, '-')
                .replace(/-{2,}/g, '-')
                .replace(/^[\s\uFEFF\xA0-]+|[\s\uFEFF\xA0-]+$/g, '')
                .replace(/\s/ig, '-');
        },

        getFields: function(){
            var vue = this;
            if(vue.filterEvent){
                vue.filterEvent = false;
                $("#filters").addClass('loading');
                this.$http.get('/dashboard/filters/'+ vue.product.id + '?category_id=' + vue.product.category_id )
                    .then(function (response) {
                        $("#filters .inner").html(response.body);
                        $("#filters").removeClass('loading');
                        $('.selectize').selectize({
                            create: true,
                            createOnBlur: true,
                            sortField: 'text'
                        });
                    }, function (error) {
                        $("#filters .inner").html(error.body);
                        $("#filters").removeClass('loading');
                });
            }
        },

        getFieldsClik: function(){
            var vue = this;
            $("#filters").addClass('loading');
            this.$http.get('/dashboard/filters/'+ vue.product.id + '?category_id=' + vue.product.category_id )
                .then(function (response) {
                    $("#filters .inner").html(response.body);
                    $("#filters").removeClass('loading');
                    $('.selectize').selectize({
                        create: true,
                        createOnBlur: true,
                        sortField: 'text'
                    });
                }, function (error) {
                    $("#filters .inner").html(error.body);
                    $("#filters").removeClass('loading');
                });
        },

        getXapacts: function () {
            var vue = this;
            if(vue.xapactEvent){
                vue.xapactEvent = false;
                $("#characters").addClass('loading');
                this.$http.get('/dashboard/characteristics/'+ vue.product.id + '?category_id=' + vue.product.category_id )
                    .then(function (response) {
                        $("#characters .inner").html(response.body);
                        $("#characters").removeClass('loading');
                        $('.selectize_x').selectize({
                            create: true,
                            createOnBlur: true,
                            sortField: 'text'
                        });
                    }, function (error) {
                        $("#characters .inner").html(error.body);
                        $("#characters").removeClass('loading');
                    });
             }
        },

        getXapactsClik: function(){
            var vue = this;
            $("#characters").addClass('loading');
            this.$http.get('/dashboard/characteristics/'+ vue.product.id + '?category_id=' + vue.product.category_id )
                .then(function (response) {
                    $("#characters .inner").html(response.body);
                    $("#characters").removeClass('loading');
                    $('.selectize_x').selectize({
                        create: true,
                        createOnBlur: true,
                        sortField: 'text'
                    });
                }, function (error) {
                    $("#characters .inner").html(error.body);
                    $("#characters").removeClass('loading');
                });
        },

        getParam: function () {
            var vue = this;
            if (vue.paramEvent) {
                vue.paramEvent = false;
                $("#params").addClass('loading');
                this.$http.get('/dashboard/parameters/list?id='+ vue.product.id )
                    .then(function (response) {
                        $("#params .inner").html(response.body);
                        $("#params").removeClass('loading');
                    }, function (error) {
                        $("#params .inner").html(error.body);
                        $("#params").removeClass('loading');
                    });

            }
        },

        getParamClik: function () {
            var vue = this;
            $("#params").addClass('loading');
            this.$http.get('/dashboard/parameters/list?id='+ vue.product.id )
                .then(function (response) {
                    $("#params .inner").html(response.body);
                    $("#params").removeClass('loading');
                }, function (error) {
                    $("#params .inner").html(error.body);
                    $("#params").removeClass('loading');
                });
        },

        setAsThumbnail: function(image) {
            var vue = this;
            for(var img in vue.product.images){
                vue.product.images[img].is_thumb = false;
            }
            vue.product.images[vue.product.images.indexOf(image)].is_thumb = true;

            this.$http.post('/dashboard/set-thumbnail/' + image.id, {_token: vue.token, productId : vue.product.id} )
                .then(function (response) {});
        },

        removeImage: function (image) {
            var vue = this;
            this.$http.post('/dashboard/remove-image/' + image.id, {_token: vue.token} )
                .then(function (response) {
                    var index = vue.product.images.indexOf(image);
                    if (index > -1)
                        vue.product.images.splice(index, 1);
                });
        },

        loadImage: function (event) {
            var vue = this;
            var uploadInput = event.target;
            for(var property in uploadInput.files) {
                if(!isNaN(property)){
                    var data = new FormData();
                    //console.log(uploadInput[0].files[property]);
                    data.append('file', uploadInput.files[property]);
                    data.append('product_id', this.product.id);
                    data.append('is_certificate', event.target.id == 'cerf' ? 1 : 0);
                    this.$http.post('/dashboard/upload-image', data )
                        .then(function (image) {
                            vue.product.images.push(image.body);
                            if(vue.product.images.length == 1){
                                vue.setAsThumbnail(image);
                            }
                        });
                }
            }
            uploadInput.value = null;
        },

        loadVideo: function(){
            var vue = this;
            bootbox.prompt("Введите HTML код видео", function(result) {
                if (result ) {
                    vue.product.video = result;
                }
            });

        },

        removeVideo: function(){
            this.product.video = null;
        },

        getPdfList: function(){
            var vue = this;
            if(vue.fileEvent){
                vue.fileEvent = false;
                this.$http.get('/dashboard/pdf?id=' + vue.product.id )
                    .then(function (response) {
                        $("#filesup").html(response.body);
                    });
            }
        },

        updatePdfList: function(){
            var vue = this;
            this.$http.get('/dashboard/pdf?id=' + vue.product.id )
                .then(function (response) {
                    $("#filesup").html(response.body);
                });
        },

        loadPDF: function(event){
            var vue = this;
            var uploadInput = event.target;
            for(var property in uploadInput.files) {
                if(!isNaN(property)){
                    var data = new FormData();
                    data.append('file', uploadInput.files[property]);
                    data.append('productID', vue.product.id);
                    data.append('categoryID', vue.product.category_id);
                    data.append('brandID', vue.product.brand_id);

                    this.$http.post('/dashboard/upload-pdf', data )
                        .then(function () {
                            vue.updatePdfList();
                        });
                }
            }
        },

        getProducts: function () {
            var vue = this;
            var options = {
                params: {
                    categoryId: vue.relOptions.category,
                    paginate: vue.relOptions.search,
                    search: vue.relOptions.search,
                    selected: vue.getSelectedProductsIds(),
                    page: vue.productsList.pagination.pageToGet,
                    _: Date.now()
                }
            };
            this.$http.get('/dashboard/product-actions/getProducts', options)
                .then(function (response) {
                    vue.productsList.products = response.body.data;
                    vue.productsList.pagination.currentPage = response.body.current_page;
                    vue.productsList.pagination.lastPage = response.body.last_page;
                    if(vue.productsList.pagination.lastPage < vue.productsList.pagination.pageToGet) {
                        vue.productsList.pagination.pageToGet = vue.productsList.pagination.lastPage;
                        vue.getProducts()
                    }
                });
        },

        getRelatedProducts: function(){
            var vue = this;
            this.$http.post('/dashboard/product-actions/getRelatedProducts', {productId: this.product.id})
                .then(function (response) {
                    vue.relOptions.selected = response.body;
                    vue.selectedProductsIds = this.getSelectedProductsIds();
                });
        },

        syncProducts: function(){
            this.selectedProductsIds = this.getSelectedProductsIds();
            var body = {
                ids: this.getSelectedProductsIds(),
                productId: this.product.id
            };
            this.$http.post('/dashboard/product-actions/syncRelated', body)
        },

        getSelectedProductsIds: function(){
            var productsIds = [];
            this.relOptions.selected.forEach(function(product){
                productsIds.push(product.id);
            });
            return productsIds;
        },

        addProduct: function(relProduct, index){
            this.productsList.products.splice(index, 1);
            this.relOptions.selected.push(relProduct);
            this.syncProducts();
            this.getProducts();
        },

        removeProduct: function(relProduct, index){
            this.relOptions.selected.splice(index, 1);
            this.productsList.products.push(relProduct);
            this.syncProducts();
            this.getProducts();
        },

        nextPage: function(){
            if(this.productsList.pagination.currentPage != this.productsList.pagination.lastPage){
                this.productsList.pagination.pageToGet = this.productsList.pagination.currentPage + 1;
                this.getProducts();
            }
        },

        prevPage: function(){
            if(this.productsList.pagination.currentPage != 1) {
                this.productsList.pagination.pageToGet = this.productsList.pagination.currentPage - 1;
                this.getProducts();
            }
        },

        updateCountry: function () {
            this.$http.post('/dashboard/country/get')
                .then(function (response) {
                    this.countryList = response.body;
                });
        }

    }

});<commit_msg>17.02.17.2<commit_after>/**
 * Created by Evgenii on 16.01.2017.
 */
Vue.config.debug = true;
Vue.http.headers.common['X-CSRF-TOKEN'] = document.getElementById('token').getAttribute('value');

var productVue = new Vue({

    el: "#productVue",

    data: {
        token: document.getElementById('token').getAttribute('value'),
        translate:  {},
        filterEvent: true,
        xapactEvent: true,
        paramEvent: true,
        fileEvent: true,
        product:{
            id: document.getElementById("form-data").id.value,
            images: [],
            meta_description: '',
            meta_title: '',
            title: '',
            slug: ''
        },
        productsList:{
            products:{},
            pagination:{
                currentPage: {},
                lastPage: {},
                pageToGet: 1
            }
        },
        relOptions:{
            category:0,
            paginate: 20,
            search: '',
            selected: []
        },
        relatedProducts: null,
        selectedProductsIds: [],
        countryList: null
    },

    created: function () {
        if(this.product.id){
            this.$http.get('/dashboard/products/' + this.product.id + '/edit').then(function (response) {
                this.product = response.body;});
        }

        this.$http.get('/dashboard/helpers/translate').then(function (response) {
            this.translate = response;});
        this.getRelatedProducts();
    },

    computed: {
        stringImagesIds: function(){
            var images = [];
            for(var i = 0, len = this.product.images.length; i < len; i++ ){
                images[i] = this.product.images[i].id;
            }
            return images.join(',');
        },

        coountTitle: function () {
            if(this.product.id){
                return this.product.meta_title.length
            }else{
                return 0;
            }
        },

        coountDescription: function () {
            if(this.product.id){
                return this.product.meta_description.length
            }else{
                return 0;
            }
        },
    },

    methods: {

        makeSlug: function () {
            this.product.slug = this.prepareSlug()
        },

        prepareSlug: function () {
            var answer = '',
                title = this.product.title,
                translate = this.translate;

            for (var i in title) {
                if (translate.hasOwnProperty(title[i])) {
                    if (translate[title[i]] !== undefined) {
                        answer += translate[title[i]];
                    }
                } else {
                    answer += title[i];
                }
            }

            return answer.toLocaleLowerCase()
                .replace(/[^a-z0-9-]/, '-')
                .replace(/-{2,}/g, '-')
                .replace(/^[\s\uFEFF\xA0-]+|[\s\uFEFF\xA0-]+$/g, '')
                .replace(/\s/ig, '-');
        },

        getFields: function(){
            var vue = this;
            if(vue.filterEvent){
                vue.filterEvent = false;
                $("#filters").addClass('loading');
                this.$http.get('/dashboard/filters/'+ vue.product.id + '?category_id=' + vue.product.category_id )
                    .then(function (response) {
                        $("#filters .inner").html(response.body);
                        $("#filters").removeClass('loading');
                        $('.selectize').selectize({
                            create: true,
                            createOnBlur: true,
                            sortField: 'text'
                        });
                    }, function (error) {
                        $("#filters .inner").html(error.body);
                        $("#filters").removeClass('loading');
                });
            }
        },

        getFieldsClik: function(){
            var vue = this;
            $("#filters").addClass('loading');
            this.$http.get('/dashboard/filters/'+ vue.product.id + '?category_id=' + vue.product.category_id )
                .then(function (response) {
                    $("#filters .inner").html(response.body);
                    $("#filters").removeClass('loading');
                    $('.selectize').selectize({
                        create: true,
                        createOnBlur: true,
                        sortField: 'text'
                    });
                }, function (error) {
                    $("#filters .inner").html(error.body);
                    $("#filters").removeClass('loading');
                });
        },

        getXapacts: function () {
            var vue = this;
            if(vue.xapactEvent){
                vue.xapactEvent = false;
                $("#characters").addClass('loading');
                this.$http.get('/dashboard/characteristics/'+ vue.product.id + '?category_id=' + vue.product.category_id )
                    .then(function (response) {
                        $("#characters .inner").html(response.body);
                        $("#characters").removeClass('loading');
                        $('.selectize_x').selectize({
                            create: true,
                            createOnBlur: true,
                            sortField: 'text'
                        });
                    }, function (error) {
                        $("#characters .inner").html(error.body);
                        $("#characters").removeClass('loading');
                    });
             }
        },

        getXapactsClik: function(){
            var vue = this;
            $("#characters").addClass('loading');
            this.$http.get('/dashboard/characteristics/'+ vue.product.id + '?category_id=' + vue.product.category_id )
                .then(function (response) {
                    $("#characters .inner").html(response.body);
                    $("#characters").removeClass('loading');
                    $('.selectize_x').selectize({
                        create: true,
                        createOnBlur: true,
                        sortField: 'text'
                    });
                }, function (error) {
                    $("#characters .inner").html(error.body);
                    $("#characters").removeClass('loading');
                });
        },

        getParam: function () {
            var vue = this;
            if (vue.paramEvent) {
                vue.paramEvent = false;
                $("#params").addClass('loading');
                this.$http.get('/dashboard/parameters/list?id='+ vue.product.id )
                    .then(function (response) {
                        $("#params .inner").html(response.body);
                        $("#params").removeClass('loading');
                    }, function (error) {
                        $("#params .inner").html(error.body);
                        $("#params").removeClass('loading');
                    });

            }
        },

        getParamClik: function () {
            var vue = this;
            $("#params").addClass('loading');
            this.$http.get('/dashboard/parameters/list?id='+ vue.product.id )
                .then(function (response) {
                    $("#params .inner").html(response.body);
                    $("#params").removeClass('loading');
                }, function (error) {
                    $("#params .inner").html(error.body);
                    $("#params").removeClass('loading');
                });
        },

        setAsThumbnail: function(image) {
            var vue = this;
            for(var img in vue.product.images){
                vue.product.images[img].is_thumb = false;
            }
            vue.product.images[vue.product.images.indexOf(image)].is_thumb = true;

            this.$http.post('/dashboard/set-thumbnail/' + image.id, {_token: vue.token, productId : vue.product.id} )
                .then(function (response) {});
        },

        removeImage: function (image) {
            var vue = this;
            this.$http.post('/dashboard/remove-image/' + image.id, {_token: vue.token} )
                .then(function (response) {
                    var index = vue.product.images.indexOf(image);
                    if (index > -1)
                        vue.product.images.splice(index, 1);
                });
        },

        loadImage: function (event) {
            var vue = this;
            var uploadInput = event.target;
            for(var property in uploadInput.files) {
                if(!isNaN(property)){
                    var data = new FormData();
                    //console.log(uploadInput[0].files[property]);
                    data.append('file', uploadInput.files[property]);
                    data.append('product_id', this.product.id);
                    data.append('is_certificate', event.target.id == 'cerf' ? 1 : 0);
                    this.$http.post('/dashboard/upload-image', data )
                        .then(function (image) {
                            vue.product.images.push(image.body);
                            if(vue.product.images.length == 1){
                                vue.setAsThumbnail(image);
                            }
                        });
                }
            }
            uploadInput.value = null;
        },

        loadVideo: function(){
            var vue = this;
            bootbox.prompt("Введите HTML код видео", function(result) {
                if (result ) {
                    vue.product.video = result;
                }
            });

        },

        removeVideo: function(){
            this.product.video = null;
        },

        getPdfList: function(){
            var vue = this;
            if(vue.fileEvent){
                vue.fileEvent = false;
                this.$http.get('/dashboard/pdf?id=' + vue.product.id )
                    .then(function (response) {
                        $("#filesup").html(response.body);
                    });
            }
        },

        updatePdfList: function(){
            var vue = this;
            this.$http.get('/dashboard/pdf?id=' + vue.product.id )
                .then(function (response) {
                    $("#filesup").html(response.body);
                });
        },

        loadPDF: function(event){
            var vue = this;
            var uploadInput = event.target;
            for(var property in uploadInput.files) {
                if(!isNaN(property)){
                    var data = new FormData();
                    data.append('file', uploadInput.files[property]);
                    data.append('productID', vue.product.id);
                    data.append('categoryID', vue.product.category_id);
                    data.append('brandID', vue.product.brand_id);

                    this.$http.post('/dashboard/upload-pdf', data )
                        .then(function () {
                            vue.updatePdfList();
                        });
                }
            }
        },

        getProducts: function () {
            var vue = this;
            var options = {
                params: {
                    categoryId: vue.relOptions.category,
                    paginate: vue.relOptions.search,
                    search: vue.relOptions.search,
                    selected: vue.getSelectedProductsIds(),
                    page: vue.productsList.pagination.pageToGet,
                    _: Date.now()
                }
            };
            this.$http.get('/dashboard/product-actions/getProducts', options)
                .then(function (response) {
                    vue.productsList.products = response.body.data;
                    vue.productsList.pagination.currentPage = response.body.current_page;
                    vue.productsList.pagination.lastPage = response.body.last_page;
                    if(vue.productsList.pagination.lastPage < vue.productsList.pagination.pageToGet) {
                        vue.productsList.pagination.pageToGet = vue.productsList.pagination.lastPage;
                        vue.getProducts()
                    }
                });
        },

        getRelatedProducts: function(){
            var vue = this;
            this.$http.post('/dashboard/product-actions/getRelatedProducts', {productId: this.product.id})
                .then(function (response) {
                    vue.relOptions.selected = response.body;
                    vue.selectedProductsIds = this.getSelectedProductsIds();
                });
        },

        syncProducts: function(){
            this.selectedProductsIds = this.getSelectedProductsIds();
            var body = {
                ids: this.getSelectedProductsIds(),
                productId: this.product.id
            };
            this.$http.post('/dashboard/product-actions/syncRelated', body)
        },

        getSelectedProductsIds: function(){
            var productsIds = [];
            this.relOptions.selected.forEach(function(product){
                productsIds.push(product.id);
            });
            return productsIds;
        },

        addProduct: function(relProduct, index){
            this.productsList.products.splice(index, 1);
            this.relOptions.selected.push(relProduct);
            this.syncProducts();
            this.getProducts();
        },

        removeProduct: function(relProduct, index){
            this.relOptions.selected.splice(index, 1);
            this.productsList.products.push(relProduct);
            this.syncProducts();
            this.getProducts();
        },

        nextPage: function(){
            if(this.productsList.pagination.currentPage != this.productsList.pagination.lastPage){
                this.productsList.pagination.pageToGet = this.productsList.pagination.currentPage + 1;
                this.getProducts();
            }
        },

        prevPage: function(){
            if(this.productsList.pagination.currentPage != 1) {
                this.productsList.pagination.pageToGet = this.productsList.pagination.currentPage - 1;
                this.getProducts();
            }
        },

        updateCountry: function () {
            this.$http.post('/dashboard/country/get')
                .then(function (response) {
                    this.countryList = response.body;
                });
        }

    }

});<|endoftext|>


<commit_before>describe("Create, add, get, getBy", function() {

  beforeEach(function() {
  });

  it("Expect People to have objects", function() {
    omg.create('People');
    omg.add('People', {name: 'Link'});
    expect(omg.get('People')[0].name).toBe('Link');
  });

  it("Return value from any key", function() {
    omg.add('People', [{name: 'Zelda'}, {name: 'Navi'}]);
    var matches = omg.getBy('People', 'name', 'Link');
    expect(matches[0].name).toBe('Link');
  });

});

describe("Flush", function() {

  it("Should remove all items from local storage", function(){
    omg.create('People');
    omg.add('People', {name: 'Flush Me!'});
    omg.flush();
    var people = omg.get('People');
    expect(people).toBe(false);
  });

});
<commit_msg>Fix whitespace in tests<commit_after>describe("Create, add, get, getBy", function() {

  beforeEach(function() {
  });

  it("Expect People to have objects", function() {
    omg.create('People');
    omg.add('People', {name: 'Link'});
    expect(omg.get('People')[0].name).toBe('Link');
  });

  it("Return value from any key", function() {
    omg.add('People', [{name: 'Zelda'}, {name: 'Navi'}]);
    var matches = omg.getBy('People', 'name', 'Link');
    expect(matches[0].name).toBe('Link');
  });
});

describe("Flush", function() {
  it("Should remove all items from local storage", function(){
    omg.create('People');
    omg.add('People', {name: 'Flush Me!'});
    omg.flush();
    var people = omg.get('People');
    expect(people).toBe(false);
  });
});
<|endoftext|>


<commit_before>require(["jquery", "jquery.gridster"], function($, gridster) {
  var g = $("#notebook-panels");
  var scrollWidth = 15;
  var w = ($(document.body).width() - scrollWidth) * (3.0 / 12);
  var m = 10;
  var nbCols = 2;
  var b = (w - (2 * nbCols)*10)/2

  var ul = $("#notebook-panels .gridster > ul");

  var site = $("#site");
  var nb = $("#notebook");
  var sb = $("#sidebar");
  var hh = $("#header").height();
  function sticky_relocate() {
    if (nb.is(":visible")) {
      var t = nb.offset().top;
      if (t < 0) {
        sb.css("top", (Math.abs(t)+hh)+"px");
      } else if (t < hh) {
        sb.css("top", (hh-t)+"px");
      } else {
        sb.css("top", "20px");
      }
    }
  }

  site.scroll(sticky_relocate);

  ul.gridster({
    max_cols: nbCols,
    widget_margins: [m, m],
    widget_base_dimensions: [b, 250],
    max_sizex: 2,
    helper: 'clone',
    resize: {
      enabled: true
    }
  });
});

require(["jquery", "underscore", "base/js/events", "knockout"], function($, _, events, ko) {
  // http://lions-mark.com/jquery/scrollTo/
  $.fn.scrollTo = function( target, options, callback ){
    if(typeof options == 'function' && arguments.length == 2){ callback = options; options = target; }
    var settings = $.extend({
      scrollTarget  : target,
      offsetTop     : 50,
      duration      : 500,
      easing        : 'swing'
    }, options);
    return this.each(function(){
      var scrollPane = $(this);
      var scrollTarget = (typeof settings.scrollTarget == "number") ? settings.scrollTarget : $(settings.scrollTarget);
      var scrollY = (typeof scrollTarget == "number") ? scrollTarget : scrollTarget.offset().top + scrollPane.scrollTop() - parseInt(settings.offsetTop);
      scrollPane.animate({scrollTop : scrollY }, parseInt(settings.duration), settings.easing, function(){
        if (typeof callback == 'function') { callback.call(this); }
      });
    });
  };

  var td = $("#termDefinitions");
  if (!td.find("table").length) {
    function viewModel() {
      var self = this;
      self.definitions = {};
      self.definitions.data = ko.observableArray([]);
      self.clearDefinitions = function() {
        self.definitions.data.remove(function(e) { return true });
      };
      self.addDefinition = function(def) {
        self.definitions.data.remove(function(e) { return e.name == def.name;});
        self.definitions.data.push(def);
      };
      self.hightlightCell = function() {
        var cell = $("div.cell[data-cell-id='"+this.cell+"']");
        cell.addClass("alert alert-info");

        $('#site').scrollTo(cell, { duration: 300, offsetTop: 200 });

        setTimeout(function() {
          cell.removeClass("alert alert-info")
        }, 800);
      };
    };
    var model = new viewModel();

    var tbl = $('
'+
      '
'+
      '
Name	Type
'+
      '
'+
      '
'+
      '
'+
      '            	'+
      '            	'+
      '
'+
      '
'+
      '
')

    ko.applyBindings(model, tbl.get(0));
    td.append(tbl);

    events.on('kernel_ready.Kernel', function(e, c) {
      var kernel = c.kernel;
      console.log("kernel", kernel);

      // make sure definitions are reset on kernel restart
      model.clearDefinitions();

      kernel.events.on("new.Definition", function(e, c) {
        console.log("new def", c);
        if (c.term || c.type) {
          model.addDefinition({name: c.term || c.type, type: c.tpe, cell: c.cell});
        }
      });
    });
  }
});
<commit_msg>Clear sidebar on kernel reset<commit_after>require(["jquery", "jquery.gridster"], function($, gridster) {
  var g = $("#notebook-panels");
  var scrollWidth = 15;
  var w = ($(document.body).width() - scrollWidth) * (3.0 / 12);
  var m = 10;
  var nbCols = 2;
  var b = (w - (2 * nbCols)*10)/2

  var ul = $("#notebook-panels .gridster > ul");

  var site = $("#site");
  var nb = $("#notebook");
  var sb = $("#sidebar");
  var hh = $("#header").height();
  function sticky_relocate() {
    if (nb.is(":visible")) {
      var t = nb.offset().top;
      if (t < 0) {
        sb.css("top", (Math.abs(t)+hh)+"px");
      } else if (t < hh) {
        sb.css("top", (hh-t)+"px");
      } else {
        sb.css("top", "20px");
      }
    }
  }

  site.scroll(sticky_relocate);

  ul.gridster({
    max_cols: nbCols,
    widget_margins: [m, m],
    widget_base_dimensions: [b, 250],
    max_sizex: 2,
    helper: 'clone',
    resize: {
      enabled: true
    }
  });
});

require(["jquery", "underscore", "base/js/events", "knockout"], function($, _, events, ko) {
  // http://lions-mark.com/jquery/scrollTo/
  $.fn.scrollTo = function( target, options, callback ){
    if(typeof options == 'function' && arguments.length == 2){ callback = options; options = target; }
    var settings = $.extend({
      scrollTarget  : target,
      offsetTop     : 50,
      duration      : 500,
      easing        : 'swing'
    }, options);
    return this.each(function(){
      var scrollPane = $(this);
      var scrollTarget = (typeof settings.scrollTarget == "number") ? settings.scrollTarget : $(settings.scrollTarget);
      var scrollY = (typeof scrollTarget == "number") ? scrollTarget : scrollTarget.offset().top + scrollPane.scrollTop() - parseInt(settings.offsetTop);
      scrollPane.animate({scrollTop : scrollY }, parseInt(settings.duration), settings.easing, function(){
        if (typeof callback == 'function') { callback.call(this); }
      });
    });
  };

  var td = $("#termDefinitions");
  if (!td.find("table").length) {
    function viewModel() {
      var self = this;
      self.definitions = {};
      self.definitions.data = ko.observableArray([]);
      self.clearDefinitions = function() {
        self.definitions.data.remove(function(e) { return true });
      };
      self.addDefinition = function(def) {
        self.definitions.data.remove(function(e) { return e.name == def.name;});
        self.definitions.data.push(def);
      };
      self.hightlightCell = function() {
        var cell = $("div.cell[data-cell-id='"+this.cell+"']");
        cell.addClass("alert alert-info");

        $('#site').scrollTo(cell, { duration: 300, offsetTop: 200 });

        setTimeout(function() {
          cell.removeClass("alert alert-info")
        }, 800);
      };
    };
    var model = new viewModel();

    var tbl = $('
'+
      '
'+
      '
Name	Type
'+
      '
'+
      '
'+
      '
'+
      '            	'+
      '            	'+
      '
'+
      '
'+
      '
')

    ko.applyBindings(model, tbl.get(0));
    td.append(tbl);

    events.on('kernel_restarting.Kernel', function(e, c) {
      // clear sidebar on kernel restart
      // reset term definitions
      model.clearDefinitions();
      // clear old progressbar & link to spark UI
      $('#spark-ui-link-container, #all-jobs-progress-bar').html('');
    });

    events.on('kernel_ready.Kernel', function(e, c) {
      var kernel = c.kernel;
      console.log("kernel", kernel);

      kernel.events.on("new.Definition", function(e, c) {
        console.log("new def", c);
        if (c.term || c.type) {
          model.addDefinition({name: c.term || c.type, type: c.tpe, cell: c.cell});
        }
      });
    });
  }
});
<|endoftext|>


<commit_before>/* Copyright (c) 2006 Patrick Fitzgerald */

/* Modified on 2009-02-04 by Jits, based on: http://groups.google.com/group/barelyfitz/browse_thread/thread/03e8b0672238391a */

function tabberObj(argsObj)
{ if ( window.location.hash && window.location.hash.match( /^#/ ) ) { var el = document.getElementById(window.location.hash.substr(2)); if (el) { el.className = "tabbertab tabbertabdefault" } }
var arg;this.div=null;this.classMain="tabber";this.classMainLive="tabberlive";this.classTab="tabbertab";this.classTabDefault="tabbertabdefault";this.classNav="tabbernav";this.classTabHide="tabbertabhide";this.classNavActive="tabberactive";this.titleElements=['h2','h3','h4','h5','h6'];this.titleElementsStripHTML=true;this.removeTitle=true;this.addLinkId=false;this.linkIdFormat='<tabberid>nav<tabnumberone>';for(arg in argsObj){this[arg]=argsObj[arg];}
this.REclassMain=new RegExp('\\b'+this.classMain+'\\b','gi');this.REclassMainLive=new RegExp('\\b'+this.classMainLive+'\\b','gi');this.REclassTab=new RegExp('\\b'+this.classTab+'\\b','gi');this.REclassTabDefault=new RegExp('\\b'+this.classTabDefault+'\\b','gi');this.REclassTabHide=new RegExp('\\b'+this.classTabHide+'\\b','gi');this.tabs=new Array();if(this.div){this.init(this.div);this.div=null;}}
tabberObj.prototype.init=function(e)
{var
childNodes,i,i2,t,defaultTab=0,DOM_ul,DOM_li,DOM_a,aId,headingElement;if(!document.getElementsByTagName){return false;}
  if(e.id){this.id=e.id;}
this.tabs.length=0;childNodes=e.childNodes;for(i=0;i<childNodes.length;i++){if(childNodes[i].className&&childNodes[i].className.match(this.REclassTab)){t=new Object();t.div=childNodes[i];this.tabs[this.tabs.length]=t;if(childNodes[i].className.match(this.REclassTabDefault)){defaultTab=this.tabs.length-1;}}}
  DOM_ul=document.createElement("ul");
  DOM_ul.className=this.classNav;
  row_max = 8;
  row_length = this.tabs.length % row_max;
  if(row_length == 0){row_length = row_max}
  first_child = e.firstChild;
  for(i=0;i<this.tabs.length;i++){
    t=this.tabs[i];
   t.headingText=t.div.title;
   if(this.removeTitle){t.div.title='';}
   if(!t.headingText){for(i2=0;i2<this.titleElements.length;i2++){headingElement=t.div.getElementsByTagName(this.titleElements[i2])[0];if(headingElement){t.headingText=headingElement.innerHTML;if(this.titleElementsStripHTML){t.headingText.replace(/
/gi," ");t.headingText=t.headingText.replace(/<[^>]+>/g,"");}
break;}}}
   if(!t.headingText){t.headingText=i+1;}
   DOM_li=document.createElement("li");
   t.li=DOM_li;
   DOM_a=document.createElement("a");
   DOM_a.appendChild(document.createTextNode(t.headingText));
   DOM_a.href="javascript:void(null);";
   DOM_a.title=t.headingText;
   DOM_a.onclick=this.navClick;
   DOM_a.tabber=this;
   DOM_a.tabberIndex=i;
   if(this.addLinkId&&this.linkIdFormat){aId=this.linkIdFormat;aId=aId.replace(/<tabberid>/gi,this.id);aId=aId.replace(/<tabnumberzero>/gi,i);aId=aId.replace(/<tabnumberone>/gi,i+1);aId=aId.replace(/<tabtitle>/gi,t.headingText.replace(/[^a-zA-Z0-9\-]/gi,''));DOM_a.id=aId;}
   DOM_li.appendChild(DOM_a);
   DOM_ul.appendChild(DOM_li);
   row_length--;
   if(row_length == 0){
     e.insertBefore(DOM_ul,first_child);
     DOM_ul=document.createElement("ul");
     DOM_ul.className=this.classNav;
     row_length = row_max;}

}
   if(DOM_ul.childElementCount != 0){e.insertBefore(DOM_ul,first_child)}
   e.className=e.className.replace(this.REclassMain,this.classMainLive);this.tabShow(defaultTab);if(typeof this.onLoad=='function'){this.onLoad({tabber:this});}
return this;};

tabberObj.prototype.navClick=function(event)
{var
rVal,a,self,tabberIndex,onClickArgs;a=this;if(!a.tabber){return false;}
self=a.tabber;tabberIndex=a.tabberIndex;a.blur();if(typeof self.onClick=='function'){onClickArgs={'tabber':self,'index':tabberIndex,'event':event};if(!event){onClickArgs.event=window.event;}
rVal=self.onClick(onClickArgs);if(rVal===false){return false;}}
self.tabShow(tabberIndex);return false;};tabberObj.prototype.tabHideAll=function()
{var i;for(i=0;i<this.tabs.length;i++){this.tabHide(i);}};tabberObj.prototype.tabHide=function(tabberIndex)
{var div;if(!this.tabs[tabberIndex]){return false;}
div=this.tabs[tabberIndex].div;if(!div.className.match(this.REclassTabHide)){div.className+=' '+this.classTabHide;}
this.navClearActive(tabberIndex);return this;};tabberObj.prototype.tabShow=function(tabberIndex)
{var div;if(!this.tabs[tabberIndex]){return false;}
this.tabHideAll();div=this.tabs[tabberIndex].div;div.className=div.className.replace(this.REclassTabHide,'');this.navSetActive(tabberIndex);if(typeof this.onTabDisplay=='function'){this.onTabDisplay({'tabber':this,'index':tabberIndex});}
return this;};tabberObj.prototype.navSetActive=function(tabberIndex)
{this.tabs[tabberIndex].li.className=this.classNavActive;return this;};tabberObj.prototype.navClearActive=function(tabberIndex)
{this.tabs[tabberIndex].li.className='';return this;};function tabberAutomatic(tabberArgs)
{var
tempObj,divs,i;if(!tabberArgs){tabberArgs={};}
tempObj=new tabberObj(tabberArgs);divs=document.getElementsByTagName("div");for(i=0;i<divs.length;i++){if(divs[i].className&&divs[i].className.match(tempObj.REclassMain)){tabberArgs.div=divs[i];divs[i].tabber=new tabberObj(tabberArgs);}}
return this;}
function tabberAutomaticOnLoad(tabberArgs)
{var oldOnLoad;if(!tabberArgs){tabberArgs={};}
oldOnLoad=window.onload;if(typeof window.onload!='function'){window.onload=function(){tabberAutomatic(tabberArgs);};}else{window.onload=function(){oldOnLoad();tabberAutomatic(tabberArgs);};}}
if(typeof tabberOptions=='undefined'){tabberAutomaticOnLoad();}else{if(!tabberOptions['manualStartup']){tabberAutomaticOnLoad(tabberOptions);}}<commit_msg>increased max tabs per row to 11<commit_after>/* Copyright (c) 2006 Patrick Fitzgerald */

/* Modified on 2009-02-04 by Jits, based on: http://groups.google.com/group/barelyfitz/browse_thread/thread/03e8b0672238391a */

function tabberObj(argsObj)
{ if ( window.location.hash && window.location.hash.match( /^#/ ) ) { var el = document.getElementById(window.location.hash.substr(2)); if (el) { el.className = "tabbertab tabbertabdefault" } }
var arg;this.div=null;this.classMain="tabber";this.classMainLive="tabberlive";this.classTab="tabbertab";this.classTabDefault="tabbertabdefault";this.classNav="tabbernav";this.classTabHide="tabbertabhide";this.classNavActive="tabberactive";this.titleElements=['h2','h3','h4','h5','h6'];this.titleElementsStripHTML=true;this.removeTitle=true;this.addLinkId=false;this.linkIdFormat='<tabberid>nav<tabnumberone>';for(arg in argsObj){this[arg]=argsObj[arg];}
this.REclassMain=new RegExp('\\b'+this.classMain+'\\b','gi');this.REclassMainLive=new RegExp('\\b'+this.classMainLive+'\\b','gi');this.REclassTab=new RegExp('\\b'+this.classTab+'\\b','gi');this.REclassTabDefault=new RegExp('\\b'+this.classTabDefault+'\\b','gi');this.REclassTabHide=new RegExp('\\b'+this.classTabHide+'\\b','gi');this.tabs=new Array();if(this.div){this.init(this.div);this.div=null;}}
tabberObj.prototype.init=function(e)
{var
childNodes,i,i2,t,defaultTab=0,DOM_ul,DOM_li,DOM_a,aId,headingElement;if(!document.getElementsByTagName){return false;}
  if(e.id){this.id=e.id;}
this.tabs.length=0;childNodes=e.childNodes;for(i=0;i<childNodes.length;i++){if(childNodes[i].className&&childNodes[i].className.match(this.REclassTab)){t=new Object();t.div=childNodes[i];this.tabs[this.tabs.length]=t;if(childNodes[i].className.match(this.REclassTabDefault)){defaultTab=this.tabs.length-1;}}}
  DOM_ul=document.createElement("ul");
  DOM_ul.className=this.classNav;
  row_max = 11;
  row_length = this.tabs.length % row_max;
  if(row_length == 0){row_length = row_max}
  first_child = e.firstChild;
  for(i=0;i<this.tabs.length;i++){
    t=this.tabs[i];
   t.headingText=t.div.title;
   if(this.removeTitle){t.div.title='';}
   if(!t.headingText){for(i2=0;i2<this.titleElements.length;i2++){headingElement=t.div.getElementsByTagName(this.titleElements[i2])[0];if(headingElement){t.headingText=headingElement.innerHTML;if(this.titleElementsStripHTML){t.headingText.replace(/
/gi," ");t.headingText=t.headingText.replace(/<[^>]+>/g,"");}
break;}}}
   if(!t.headingText){t.headingText=i+1;}
   DOM_li=document.createElement("li");
   t.li=DOM_li;
   DOM_a=document.createElement("a");
   DOM_a.appendChild(document.createTextNode(t.headingText));
   DOM_a.href="javascript:void(null);";
   DOM_a.title=t.headingText;
   DOM_a.onclick=this.navClick;
   DOM_a.tabber=this;
   DOM_a.tabberIndex=i;
   if(this.addLinkId&&this.linkIdFormat){aId=this.linkIdFormat;aId=aId.replace(/<tabberid>/gi,this.id);aId=aId.replace(/<tabnumberzero>/gi,i);aId=aId.replace(/<tabnumberone>/gi,i+1);aId=aId.replace(/<tabtitle>/gi,t.headingText.replace(/[^a-zA-Z0-9\-]/gi,''));DOM_a.id=aId;}
   DOM_li.appendChild(DOM_a);
   DOM_ul.appendChild(DOM_li);
   row_length--;
   if(row_length == 0){
     e.insertBefore(DOM_ul,first_child);
     DOM_ul=document.createElement("ul");
     DOM_ul.className=this.classNav;
     row_length = row_max;}

}
   if(DOM_ul.childElementCount != 0){e.insertBefore(DOM_ul,first_child)}
   e.className=e.className.replace(this.REclassMain,this.classMainLive);this.tabShow(defaultTab);if(typeof this.onLoad=='function'){this.onLoad({tabber:this});}
return this;};

tabberObj.prototype.navClick=function(event)
{var
rVal,a,self,tabberIndex,onClickArgs;a=this;if(!a.tabber){return false;}
self=a.tabber;tabberIndex=a.tabberIndex;a.blur();if(typeof self.onClick=='function'){onClickArgs={'tabber':self,'index':tabberIndex,'event':event};if(!event){onClickArgs.event=window.event;}
rVal=self.onClick(onClickArgs);if(rVal===false){return false;}}
self.tabShow(tabberIndex);return false;};tabberObj.prototype.tabHideAll=function()
{var i;for(i=0;i<this.tabs.length;i++){this.tabHide(i);}};tabberObj.prototype.tabHide=function(tabberIndex)
{var div;if(!this.tabs[tabberIndex]){return false;}
div=this.tabs[tabberIndex].div;if(!div.className.match(this.REclassTabHide)){div.className+=' '+this.classTabHide;}
this.navClearActive(tabberIndex);return this;};tabberObj.prototype.tabShow=function(tabberIndex)
{var div;if(!this.tabs[tabberIndex]){return false;}
this.tabHideAll();div=this.tabs[tabberIndex].div;div.className=div.className.replace(this.REclassTabHide,'');this.navSetActive(tabberIndex);if(typeof this.onTabDisplay=='function'){this.onTabDisplay({'tabber':this,'index':tabberIndex});}
return this;};tabberObj.prototype.navSetActive=function(tabberIndex)
{this.tabs[tabberIndex].li.className=this.classNavActive;return this;};tabberObj.prototype.navClearActive=function(tabberIndex)
{this.tabs[tabberIndex].li.className='';return this;};function tabberAutomatic(tabberArgs)
{var
tempObj,divs,i;if(!tabberArgs){tabberArgs={};}
tempObj=new tabberObj(tabberArgs);divs=document.getElementsByTagName("div");for(i=0;i<divs.length;i++){if(divs[i].className&&divs[i].className.match(tempObj.REclassMain)){tabberArgs.div=divs[i];divs[i].tabber=new tabberObj(tabberArgs);}}
return this;}
function tabberAutomaticOnLoad(tabberArgs)
{var oldOnLoad;if(!tabberArgs){tabberArgs={};}
oldOnLoad=window.onload;if(typeof window.onload!='function'){window.onload=function(){tabberAutomatic(tabberArgs);};}else{window.onload=function(){oldOnLoad();tabberAutomatic(tabberArgs);};}}
if(typeof tabberOptions=='undefined'){tabberAutomaticOnLoad();}else{if(!tabberOptions['manualStartup']){tabberAutomaticOnLoad(tabberOptions);}}<|endoftext|>


<commit_before>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.StartQueryBuilderView = Backbone.View.extend({
    el: "#developer-playground",

    template: _.template($('#playground-template').html()),

    events: {
        'change .form-control#entity': 'changeParam',
        'click .btn' : 'alert'

        // set up event to listen for submit button click, show mapview, tableview on click
        // query builder view should move to header on click (is this a separate view?)
        // 'onclick .submit-button': '(listView.$el.append(itemView.el;)'
    },

    initialize: function () {
        this.mapview = new DeveloperPlayground.MapView();
        // this.tableview = new DeveloperPlayground.TableView();
        this.render();
    },

    render: function() {
        this.$el.html(this.template());
        // this.mapview.render();
        // this.$("#table-view").append(this.tableview.render().el);
        return this;
    },

    alert: function(){
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        if($parameterSelect.val() == "bbox") {
            this.mapview.render();
        } else if($parameterSelect.val() == "hello") {
            alert($parameterSelect.val());
        } else if ($parameterSelect.val() == "name") { alert("add text input functionality");
        } else {
            alert("nope");
        }
    },

    changeParam: function() {
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var selectValues = {
            "stops": {
                "bbox": "",
                "hello": "world",
            },
            "operator": {
                "name": "",
            }
        };

        $parameterSelect.empty().append(function() {
            var output = '';
            $.each(selectValues[$entitySelect.val()], function(key, value) {
                output += '<option>' + key + '</option>';
            });
            return output;
        });
    }
});<commit_msg>clean up submit function<commit_after>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.StartQueryBuilderView = Backbone.View.extend({
    el: "#developer-playground",

    template: _.template($('#playground-template').html()),

    events: {
        'change .form-control#entity': 'changeParam',
        'click .btn' : 'submit'
    },

    initialize: function () {
        this.mapview = new DeveloperPlayground.MapView();
        // this.tableview = new DeveloperPlayground.TableView();
        this.render();
    },

    render: function() {
        this.$el.html(this.template());
        // this.mapview.render();
        // this.$("#table-view").append(this.tableview.render().el);
        return this;
    },

    submit: function(){
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        if($parameterSelect.val() == "bbox") {
            this.mapview.render();
        } else if($parameterSelect.val() == "hello") {
            alert($parameterSelect.val());
        } else if ($parameterSelect.val() == "name") { alert("add text input functionality");
        } else {
            alert("nope");
        }
    },

    changeParam: function() {
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var selectValues = {
            "stops": {
                "bbox": "",
                "hello": "world",
            },
            "operator": {
                "name": "",
            }
        };

        $parameterSelect.empty().append(function() {
            var output = '';
            $.each(selectValues[$entitySelect.val()], function(key, value) {
                output += '<option>' + key + '</option>';
            });
            return output;
        });
    }
});<|endoftext|>


<commit_before>jest.autoMockOff();

describe('Arrow Functions', () => {

  xit('can replace traditional functions', () => {

    let fnMultiply, arrowMultiply;

    //Write two functions that take two params and return their product
    //For 'fnMultiply', set it equal to a regular function
    //For 'fnMultiply', set it equal to an arrow function

    expect(fnMultiply(5, 5)).toBe(arrowMultiply(5, 5));

  });

  xit('can replace traditional functions #2', () => {

    let nums = [2, 5, 10];

    //Replace the 'function' in this 'map' call with an arrow function.
    //Hint: you shouldn'd have any braces or 'return' after you are done
    let squares = nums.map(function(num){
      return num*num;
    });

    expect(squares.shift()).toBe(4);
    expect(squares.shift()).toBe(25);
    expect(squares.shift()).toBe(100);

  });

  xit('binds `this` to the eval scope, not the runtime scope', () => {

    //Change the person object. One of the functions should become an arrow to allow for 'this' to retain context correctly

    let person = {
      name: 'Aaron',
      greetFriends: function(friends){
        friends.forEach(function(friend){
          console.log(this.name + ' greets to ' + friend);
        });
      }
    };

    let friendsArray = ['Naomi', 'Jojo', 'Ryan', 'Owen'];

    expect(()=> person.greetFriends(friendsArray)).not.toThrow();

  });

  xit('can make array filter chains more managable', () => {

    let data = [
      {type: 'Widget', name: 'Sprocket',      price: 10.00, qty: 3},
      {type: 'Widget', name: 'Bracket',       price: 1.00, qty: 5},
      {type: 'Widget', name: 'Brace',         price: 2.50, qty: 1},
      {type: 'Widget', name: 'Sprocket',      price: 4.00, qty: 2},
      {type: 'Food', name: 'Gouda',           price: 8.75, qty: 4},
      {type: 'Food', name: 'Bacon',           price: 3.50, qty: 3},
      {type: 'CD', name: 'Queen Best Hits',   price: 5.50, qty: 5},
      {type: 'CD', name: 'Brittney Best Hits',price: 6.25, qty: 3},
      {type: 'CD', name: 'JT Best Hits',      price: 2.25, qty: 6},
    ];

    //REPLACE ALL REGULAR FUNCTION WITH ARROW FUNCTIONS

    let shoppingList = data
      .filter(function(d){
        return d.type != 'Widget';
      }) //Remove Widgets
      .filter(function(d){
        return d.price < 5;
      }) //Find only remaining items with price < 5
      .sort(function(d){
        return d.qty * -1;
      }) //Sort by price, desc
      .map(function(d){
        return d.name;
      });//Pull just the name from each item

    expect(shoppingList.shift()).toBe('Bacon');
    expect(shoppingList.shift()).toBe('JT Best Hits');

  });

});<commit_msg>Fixing typeo<commit_after>jest.autoMockOff();

describe('Arrow Functions', () => {

  xit('can replace traditional functions', () => {

    let fnMultiply, arrowMultiply;

    //Write two functions that take two params and return their product
    //For 'fnMultiply', set it equal to a regular function
    //For 'arrowMultiply', set it equal to an arrow function

    expect(fnMultiply(5, 5)).toBe(arrowMultiply(5, 5));

  });

  xit('can replace traditional functions #2', () => {

    let nums = [2, 5, 10];

    //Replace the 'function' in this 'map' call with an arrow function.
    //Hint: you shouldn't have any braces or 'return' after you are done
    let squares = nums.map(function(num){
      return num*num;
    });

    expect(squares.shift()).toBe(4);
    expect(squares.shift()).toBe(25);
    expect(squares.shift()).toBe(100);

  });

  xit('binds `this` to the eval scope, not the runtime scope', () => {

    //Change the person object. One of the functions should become an arrow to allow for 'this' to retain context correctly

    let person = {
      name: 'Aaron',
      greetFriends: function(friends){
        friends.forEach(function(friend){
          console.log(this.name + ' greets to ' + friend);
        });
      }
    };

    let friendsArray = ['Naomi', 'Jojo', 'Ryan', 'Owen'];

    expect(()=> person.greetFriends(friendsArray)).not.toThrow();

  });

  xit('can make array filter chains more managable', () => {

    let data = [
      {type: 'Widget', name: 'Sprocket',      price: 10.00, qty: 3},
      {type: 'Widget', name: 'Bracket',       price: 1.00, qty: 5},
      {type: 'Widget', name: 'Brace',         price: 2.50, qty: 1},
      {type: 'Widget', name: 'Sprocket',      price: 4.00, qty: 2},
      {type: 'Food', name: 'Gouda',           price: 8.75, qty: 4},
      {type: 'Food', name: 'Bacon',           price: 3.50, qty: 3},
      {type: 'CD', name: 'Queen Best Hits',   price: 5.50, qty: 5},
      {type: 'CD', name: 'Brittney Best Hits',price: 6.25, qty: 3},
      {type: 'CD', name: 'JT Best Hits',      price: 2.25, qty: 6},
    ];

    //REPLACE ALL REGULAR FUNCTION WITH ARROW FUNCTIONS

    let shoppingList = data
      .filter(function(d){
        return d.type != 'Widget';
      }) //Remove Widgets
      .filter(function(d){
        return d.price < 5;
      }) //Find only remaining items with price < 5
      .sort(function(d){
        return d.qty * -1;
      }) //Sort by price, desc
      .map(function(d){
        return d.name;
      });//Pull just the name from each item

    expect(shoppingList.shift()).toBe('Bacon');
    expect(shoppingList.shift()).toBe('JT Best Hits');

  });

});<|endoftext|>