<commit_before>(function (angular) {
    angular
        .module('advancedFolderPluginWidget')
        .directive("buildFireCarousel", ["$rootScope", '$timeout', function ($rootScope, $timeout) {
            return {
                restrict: 'A',
                link: function (scope, elem, attrs) {
                    $timeout(function () {
                        $rootScope.$broadcast("Carousel:LOADED");
                    }, 0);
                }
            };
        }])
        .directive("viewSwitcher", ["ViewStack", "$rootScope", '$compile', "$templateCache",
            function (ViewStack, $rootScope, $compile, $templateCache) {
                return {
                    restrict: 'AE',
                    link: function (scope, elem, attrs) {
                        var views = 0;
                        manageDisplay();
                        $rootScope.$on('VIEW_CHANGED', function (e, type, view) {
                            if (type === 'PUSH') {
                                var newScope = $rootScope.$new();
                                newScope.currentItemListLayout = "templates/" + view.template + ".html";

                                var _newView = '

';
                                if (view.params && view.params.controller) {
                                    _newView = '

';
                                }
                                var parTpl = $compile(_newView)(newScope);
                                if (view.params && view.params.shouldUpdateTemplate) {
                                    newScope.$on("ITEM_LIST_LAYOUT_CHANGED", function (evt, layout, needDigest) {
                                        newScope.currentItemListLayout = "templates/" + layout + ".html";
                                        if (needDigest) {
                                            newScope.$digest();
                                        }
                                    });
                                }
                                $(elem).append(parTpl);
                                views++;

                            } else if (type === 'POP') {
                                var _elToRemove = $('div[view-switcher]').find('div#folder:last'),
                                    _child = _elToRemove.children("div").eq(0);

                                _child.addClass("ng-leave ng-leave-active");
                                _child.one("webkitTransitionEnd transitionend oTransitionEnd", function (e) {
                                    _elToRemove.remove();
                                    views--;
                                });

                                //$(elem).find('#' + view.template).remove();
                            }
                            else if (type === 'POPALL') {
                                console.log(view);
                                angular.forEach(view, function (value, key) {
                                    $(elem).find('#' + value.template).remove();
                                });
                                views = 0;
                            }
                            manageDisplay();
                        });

                        function manageDisplay() {
                            if (views) {
                                $('body').addClass('no-scroll');
                                $(elem).removeClass("ng-hide");
                            } else {
                                $('body').removeClass('no-scroll');
                                $(elem).addClass("ng-hide");
                            }

                        }

                    }
                };
            }])
        .directive('backImg', ["$filter", "$rootScope", "$window" , function ($filter, $rootScope, $window) {
            return function (scope, element, attrs) {
                attrs.$observe('backImg', function (value) {
                    var img = '';
                    if (value) {
                        img = $filter("cropImage")(value, $window.innerWidth, $window.innerHeight, true);
                        element.attr("style", 'background:url(' + img + ') !important');
                        element.css({
                            'background-size': 'cover'
                        });
                    }
                    else {
                        img = "";
                        element.attr("style", 'background-color:white !important');
                        element.css({
                            'background-size': 'cover'
                        });
                    }
                });
            };
        }]);
})(window.angular);<commit_msg>viewstack issue fixed<commit_after>(function (angular) {
    angular
        .module('advancedFolderPluginWidget')
        .directive("buildFireCarousel", ["$rootScope", '$timeout', function ($rootScope, $timeout) {
            return {
                restrict: 'A',
                link: function (scope, elem, attrs) {
                    $timeout(function () {
                        $rootScope.$broadcast("Carousel:LOADED");
                    }, 0);
                }
            };
        }])
        .directive("viewSwitcher", ["ViewStack", "$rootScope", '$compile', "$templateCache",
            function (ViewStack, $rootScope, $compile, $templateCache) {
                return {
                    restrict: 'AE',
                    link: function (scope, elem, attrs) {
                        var views = 0;
                        manageDisplay();
                        $rootScope.$on('VIEW_CHANGED', function (e, type, view) {
                            if (type === 'PUSH') {
                                var newScope = $rootScope.$new();
                                newScope.currentItemListLayout = "templates/" + view.template + ".html";

                                var _newView = '

';
                                if (view.params && view.params.controller) {
                                    _newView = '

';
                                }
                                var parTpl = $compile(_newView)(newScope);
                                if (view.params && view.params.shouldUpdateTemplate) {
                                    newScope.$on("ITEM_LIST_LAYOUT_CHANGED", function (evt, layout, needDigest) {
                                        newScope.currentItemListLayout = "templates/" + layout + ".html";
                                        if (needDigest) {
                                            newScope.$digest();
                                        }
                                    });
                                }
                                $(elem).append(parTpl);
                                views++;

                            } else if (type === 'POP') {
                                var _elToRemove = $('div[view-switcher]').find('div#folder:last'),
                                    _child = _elToRemove.children("div").eq(0);

                                _child.addClass("ng-leave ng-leave-active");
                                _child.on("webkitTransitionEnd transitionend oTransitionEnd", function (e) {
                                    _elToRemove.remove();
                                    views--;
                                });

                                //$(elem).find('#' + view.template).remove();
                            }
                            else if (type === 'POPALL') {
                                console.log(view);
                                angular.forEach(view, function (value, key) {
                                    $(elem).find('#' + value.template).remove();
                                });
                                views = 0;
                            }
                            manageDisplay();
                        });

                        function manageDisplay() {
                            if (views) {
                                $('body').addClass('no-scroll');
                                $(elem).removeClass("ng-hide");
                            } else {
                                $('body').removeClass('no-scroll');
                                $(elem).addClass("ng-hide");
                            }

                        }

                    }
                };
            }])
        .directive('backImg', ["$filter", "$rootScope", "$window" , function ($filter, $rootScope, $window) {
            return function (scope, element, attrs) {
                attrs.$observe('backImg', function (value) {
                    var img = '';
                    if (value) {
                        img = $filter("cropImage")(value, $window.innerWidth, $window.innerHeight, true);
                        element.attr("style", 'background:url(' + img + ') !important');
                        element.css({
                            'background-size': 'cover'
                        });
                    }
                    else {
                        img = "";
                        element.attr("style", 'background-color:white !important');
                        element.css({
                            'background-size': 'cover'
                        });
                    }
                });
            };
        }]);
})(window.angular);<|endoftext|>


<commit_before>var EOL = require('os').EOL;

module.exports = {
  name: 'ember-cli-mocha',

  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    var addonContext = this;

    return addonContext.addPackageToProject('ember-cli-chai', '^0.3.0').then(function() {
      if ('removePackageFromProject' in addonContext) {
        return addonContext.removePackageFromProject('ember-cli-qunit');
      }
    });
  }
};
<commit_msg>blueprints: Update "ember-cli-chai" to v0.4.0<commit_after>var EOL = require('os').EOL;

module.exports = {
  name: 'ember-cli-mocha',

  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    var addonContext = this;

    return addonContext.addPackageToProject('ember-cli-chai', '^0.4.0').then(function() {
      if ('removePackageFromProject' in addonContext) {
        return addonContext.removePackageFromProject('ember-cli-qunit');
      }
    });
  }
};
<|endoftext|>


<commit_before>"use strict";
let fetch = require('node-fetch');
let Converter = require("csvtojson");
let Promise = require('bluebird');
let _ = require("lodash");
let tr = require('transliteration').transliterate;
let readFile = Promise.promisify(require('fs').readFile);
let writeFile = Promise.promisify(require('fs').writeFile);
let remoteCSVtoJSON = require("./remote-csv-to-json");

const input = {
    judgesPerRegionCSVLinksArray: "./input/all-ukraine-judges-csv-links.json",
    cachedJudges: "./input/all-ukraine-judges.json",
    textsCSV: "https://docs.google.com/spreadsheets/d/1SDFmxJEo3Al4-dTS4PkA_E88bH40keZFfIcoT2mVOO4/pub?gid=0&single=true&output=csv"
};
const output = {
    judges: "../source/judges.json",
    dictionary: "../source/dictionary.json",
    texts: "../source/texts.json"
};
const judgeModel = require("./model/judge");

function isEmptiness (judge) {
    return !judge.declarations || !_.size(judge.declarations);
}

var getIndex = {
    landownerByLands: function landownerByLands(judge) {
        var result = 0;

        if (isEmptiness(judge)) {
            return result;
        }

        return result;
    },

    commonFamilyIncome: function commonFamilyIncome(judge) {

    },

    houseArea: function houseArea(judge) {

    }

};

(function run() {
    return getJudgesSource()
        .then(loadJudges)
        .spread(() => {
            console.log("Done");
            process.exit(0);
        })
        .error(console.log)
        .catch(console.log);
})();

function getJudgesSource() {
    return readFile(input.cachedJudges, 'utf8')
        .then(data => JSON.parse(data))
}

function loadJudges(judges) {
    console.log('loadJudges');
    return Promise.reduce(judges, function (_judges, judgeData) {
        return loadJudge(judgeData)
            .then(function (judge) {
                console.log(judge)
            })
    }, []);
}

function loadJudge(judge) {
    return readFile(`../declarations/${judge.key}.json`, 'utf8')
        .then(data => JSON.parse(data))
        .catch(function (e) {
            throw new Error(e.message);
        })
}
<commit_msg>Working on basic analytics<commit_after>"use strict";
let fetch = require('node-fetch');
let Converter = require("csvtojson");
let Promise = require('bluebird');
let _ = require("lodash");
let tr = require('transliteration').transliterate;
let readFile = Promise.promisify(require('fs').readFile);
let writeFile = Promise.promisify(require('fs').writeFile);
let remoteCSVtoJSON = require("./remote-csv-to-json");

const input = {
    judgesPerRegionCSVLinksArray: "./input/all-ukraine-judges-csv-links.json",
    cachedJudges: "./input/all-ukraine-judges.json",
    textsCSV: "https://docs.google.com/spreadsheets/d/1SDFmxJEo3Al4-dTS4PkA_E88bH40keZFfIcoT2mVOO4/pub?gid=0&single=true&output=csv"
};
const output = {
    judges: "../source/judges.json",
    dictionary: "../source/dictionary.json",
    texts: "../source/texts.json"
};
const judgeModel = require("./model/judge");

function isEmptiness (judge) {
    return !judge.declarations || !_.size(judge.declarations);
}

var getIndex = {
    landownerByLands: function landownerByLands(judge) {
        var result = 0;

        if (isEmptiness(judge)) {
            return result;
        }

        return result;
    },

    commonFamilyIncome: function commonFamilyIncome(judge) {

    },

    houseArea: function houseArea(judge) {

    }

};

(function run() {
    return getJudgesSource()
        .then(loadJudges)
        .spread(() => {
            console.log("Done");
            process.exit(0);
        })
        .error(console.log)
        .catch(console.log);
})();

function getJudgesSource() {
    return readFile(input.cachedJudges, 'utf8')
        .then(data => JSON.parse(data))
}

function loadJudges(judges) {
    console.log('loadJudges');
    return Promise.reduce(judges, function (_judges, judgeData) {
        return loadJudge(judgeData)
            .then(function (judge) {
                console.log(judge)
            })
    }, []);
}

function loadJudge(judge) {
    return readFile(`../judges/${judge.key}.json`, 'utf8')
        .then(data => JSON.parse(data))
        .catch(function (e) {
            throw new Error(e.message);
        })
}
<|endoftext|>


<commit_before>
var models = require('../models');
var data = require("../data.json");

exports.addAssignment = function(req, res) {

	// Your code goes here%
	var newAssignment = {name: req.query.name,
					 type: req.query.type,
					 score: req.query.score,
					 total: req.query.total};

	data["assignments"].push(newAssignment);

	console.log(newAssignment);
	// instead of rendering add screen, rendered data screen
	res.render('editCourse',data);

};

exports.view = function(req, res){

	console.log(data);
	res.render('editCourse',data);
};

exports.addSyllabusFields_ajax = function(req, res) {
	allFields = req.body;
	console.log("CALLING THE RIGHT FUNCTION");
	console.log(allFields);

	//Get the course ID number
	var id = "";
	for(var key in allFields) {
		if(key.match("courseId")) {
			id = allFields[key];
		}
	}

	//Find the corresponding course in the database, add the assignment types to it
	models.Course
		.findOne({"_id": id})
		.populate("syllabus")
		.exec(function(err, course) {
      		if(err) {
              	console.log('Error: ' + err);
            }
      		if(course!=null) {
              	console.log('here is the course: ' + course);

              	//Syllabus will hold type-weighting paris
				var newSyllabus = {};
				//Keys will hold index-type pairs (for saving)
				var keys = {};
				//Will keep track of how many assignment types there are
				var count = 0;

				var type = "";
				var weighting = "";

				var oldSyllabus = course.syllabus;
				console.log(oldSyllabus);

				function inSyllabus(aType) {
					for(var i = 0; i < oldSyllabus.length; i++) {
						var oldAssign = oldSyllabus[i];
						console.log("comparison assign name: " + oldAssign.name);
						console.log("our assign name: " + aType);
						if(aType.match(oldAssign.name)) return true;
					}
					return false;
				}

				var badWeight = false;

				//Create the type-weighting map and the index-type map
				for(var key in allFields) {
					//It's not the course ID
					console.log(allFields[key]);
					if(!key.match("courseId") && !inSyllabus(allFields[key]) && !badWeight) {
						//It's a type
						if(key.match(/type/gi) != null) {
							type = allFields[key];
							console.log("TYPE: " + type);
							badWeight = false;
						//It's a weighting
						} else {
							weighting = allFields[key];
							console.log("WEIGHTING: " + weighting + " and the type is: " + type);
							if(isNaN(parseFloat(weighting))) {
								console.log("UGH ITS NOT A NUMBER U SUCK");
							} else {
								newSyllabus[type] = weighting;
								keys[count] = type;
								count++;
							}
						}
					}
					badWeight = inSyllabus(allFields[key]);
				}
				console.log(newSyllabus);
				console.log(count);
				addToDatabase(0);

				//Recursiveley add the assignment types to the database and their ID's to the given course
				function addToDatabase(index) {
					if(index < count) {
						type = keys[index];
						//weighting = newSyllabus[type];
						var newAssignmentTypeInfo = {"name": type, "weighting": weighting};
						var newAssignmentType = new models.AssignmentType(newAssignmentTypeInfo);
						newAssignmentType.save(function(err) {
							if(err) console.log(err);
    						console.log(newAssignmentType);
	    					course.syllabus.push(newAssignmentType);
    						course.save(function(err) {
    							if(err) {
	                  				console.log('Error: ' + err);
 				               	}
 				               	newSyllabus[newAssignmentType._id] = newAssignmentTypeInfo;
	    						addToDatabase(index + 1);
 		   					});
						});
					} else {
						var returnData = {"syllabus": newSyllabus, "department": course.department, "number": course.number};
						console.log("OUT");
						console.log(course);
						res.json(returnData);
						return;
					}
				}
			}
		});
	// // here is where you wanna mess with the database stuff then return other
};

exports.delete_ajax = function(req, res) {
	var courseID = req.body.ID;
	console.log("CALLING THE DLETE FUNCTION");
	console.log(courseID);

	//Find the corresponding course in the database, delete it
	models.Course
		.findOne({"_id": courseID})
		//.populate("syllabus")
		.exec(function(err, course) {
      		if(err) console.log(err);
      		if(course!=null) {
              	console.log('here is the course: ' + course);
				var syllabusArray = course.syllabus;
				console.log(syllabusArray);
				var length =  syllabusArray.length;
				deleteSyllabus(0);

				function deleteSyllabus(index) {
					if(index < length) {
						models.AssignmentType.find({"_id": syllabusArray[index]})
							.remove()
							.exec(function(err) {
								if(err) console.log(err);
								deleteSyllabus(index + 1);
							});
					}
				}

				var assignmentArray = course.assignments;
				var asignlength =  assignmentArray.length;
				deleteAssign(0);

				function deleteAssign(index) {
					if(index < asignlength) {
						models.Assignment.find({"_id": assignmentArray[index]})
							.remove()
							.exec(function(err) {
								if(err) console.log(err);
								deleteAssign(index + 1);
							});
					}
				}
			}
		});
	models.Course.find({"_id": courseID})
		.remove()
		.exec(function(err) {
			if(err) console.log(err);
			res.send();
		});
}

exports.addSyllabusFields = function(req, res) {
	allFields = req.body;

	var syllabus = {};
	var type = "";
	var weighting = "";
	console.log(allFields);
	for(var key in allFields) {
		if(key.match(/type/gi) != null) {
			type = allFields[key];
			console.log("TYPE: " + type);
		} else {
			weighting = allFields[key];
			console.log("WEIGHTING: " + weighting + " and the type is: " + type);
			if(isNaN(parseFloat(weighting))) {
				console.log("UGH ITS NOT A NUMBER U SUCK");
			} else {
				syllabus[type] = weighting;
			}
		}
	}
	console.log(syllabus);
	// here is where you wanna mess with the database stuff then return other
	res.render('index',data);
	return;
};

<commit_msg>bona test things<commit_after>
var models = require('../models');
var data = require("../data.json");

exports.addAssignment = function(req, res) {

	// Your code goes here%
	var newAssignment = {name: req.query.name,
					 type: req.query.type,
					 score: req.query.score,
					 total: req.query.total};

	data["assignments"].push(newAssignment);

	console.log(newAssignment);
	// instead of rendering add screen, rendered data screen
	res.render('editCourse',data);

};

exports.view = function(req, res){

	console.log(data);
	res.render('editCourse',data);
};

exports.addSyllabusFields_ajax = function(req, res) {
	allFields = req.body;
	console.log("CALLING THE RIGHT FUNCTION");
	console.log(allFields);

	//Get the course ID number
	var id = "";
	for(var key in allFields) {
		if(key.match("courseId")) {
			id = allFields[key];
		}
	}

	//Find the corresponding course in the database, add the assignment types to it
	models.Course
		.findOne({"_id": id})
		.populate("syllabus")
		.exec(function(err, course) {
      		if(err) {
              	console.log('Error: ' + err);
            }
      		if(course!=null) {
              	console.log('here is the course: ' + course);

              	//Syllabus will hold type-weighting paris
				var newSyllabus = {};
				//Keys will hold index-type pairs (for saving)
				var keys = {};
				//Will keep track of how many assignment types there are
				var count = 0;

				var type = "";
				var weighting = "";

				var oldSyllabus = course.syllabus;
				console.log(oldSyllabus);

				function inSyllabus(aType) {
					for(var i = 0; i < oldSyllabus.length; i++) {
						var oldAssign = oldSyllabus[i];
						console.log("comparison assign name: " + oldAssign.name);
						console.log("our assign name: " + aType);
						if(aType.match(oldAssign.name)) return true;
					}
					return false;
				}

				var badWeight = false;

				//Create the type-weighting map and the index-type map
				for(var key in allFields) {
					//It's not the course ID
					console.log(allFields[key]);
					if(!key.match("courseId") && !inSyllabus(allFields[key]) && !badWeight) {
						//It's a type
						if(key.match(/type/gi) != null) {
							type = allFields[key];
							console.log("TYPE: " + type);
							badWeight = false;
						//It's a weighting
						} else {
							weighting = allFields[key];
							console.log("WEIGHTING: " + weighting + " and the type is: " + type);
							if(isNaN(parseFloat(weighting))) {
								console.log("UGH ITS NOT A NUMBER U SUCK");
							} else {
								newSyllabus[type] = weighting;
								keys[count] = type;
								count++;
							}
						}
					}
					badWeight = inSyllabus(allFields[key]);
				}
				console.log(newSyllabus);
				console.log(count);
				addToDatabase(0);
				var syllabusInfo = {};
				//Recursiveley add the assignment types to the database and their ID's to the given course
				function addToDatabase(index) {
					if(index < count) {
						type = keys[index];
						weighting = newSyllabus[type];
						var newAssignmentTypeInfo = {"name": type, "weighting": weighting};
						var newAssignmentType = new models.AssignmentType(newAssignmentTypeInfo);
						newAssignmentType.save(function(err) {
							if(err) console.log(err);
    						console.log(newAssignmentType);
	    					course.syllabus.push(newAssignmentType);
    						course.save(function(err) {
    							if(err) {
	                  				console.log('Error: ' + err);
 				               	}
 				               	syllabusInfo[newAssignmentType._id] = newAssignmentTypeInfo;
	    						addToDatabase(index + 1);
 		   					});
						});
					} else {
						var returnData = {"syllabus": newSyllabus, "department": course.department, "number": course.number};
						console.log("OUT");
						console.log(course);
						res.json(returnData);
						return;
					}
				}
			}
		});
	// // here is where you wanna mess with the database stuff then return other
};

exports.delete_ajax = function(req, res) {
	var courseID = req.body.ID;
	console.log("CALLING THE DLETE FUNCTION");
	console.log(courseID);

	//Find the corresponding course in the database, delete it
	models.Course
		.findOne({"_id": courseID})
		//.populate("syllabus")
		.exec(function(err, course) {
      		if(err) console.log(err);
      		if(course!=null) {
              	console.log('here is the course: ' + course);
				var syllabusArray = course.syllabus;
				console.log(syllabusArray);
				var length =  syllabusArray.length;
				deleteSyllabus(0);

				function deleteSyllabus(index) {
					if(index < length) {
						models.AssignmentType.find({"_id": syllabusArray[index]})
							.remove()
							.exec(function(err) {
								if(err) console.log(err);
								deleteSyllabus(index + 1);
							});
					}
				}

				var assignmentArray = course.assignments;
				var asignlength =  assignmentArray.length;
				deleteAssign(0);

				function deleteAssign(index) {
					if(index < asignlength) {
						models.Assignment.find({"_id": assignmentArray[index]})
							.remove()
							.exec(function(err) {
								if(err) console.log(err);
								deleteAssign(index + 1);
							});
					}
				}
			}
		});
	models.Course.find({"_id": courseID})
		.remove()
		.exec(function(err) {
			if(err) console.log(err);
			res.send();
		});
}

exports.addSyllabusFields = function(req, res) {
	allFields = req.body;

	var syllabus = {};
	var type = "";
	var weighting = "";
	console.log(allFields);
	for(var key in allFields) {
		if(key.match(/type/gi) != null) {
			type = allFields[key];
			console.log("TYPE: " + type);
		} else {
			weighting = allFields[key];
			console.log("WEIGHTING: " + weighting + " and the type is: " + type);
			if(isNaN(parseFloat(weighting))) {
				console.log("UGH ITS NOT A NUMBER U SUCK");
			} else {
				syllabus[type] = weighting;
			}
		}
	}
	console.log(syllabus);
	// here is where you wanna mess with the database stuff then return other
	res.render('index',data);
	return;
};

<|endoftext|>


<commit_before>(function() {  // self-executing function for encapsulation

    // Register the widget in the widgets collection.
    node.widgets.register('EndScreen', EndScreen);

    // Add Meta-data
    EndScreen.version = '0.0.1';
    EndScreen.description = 'Game end screen. With end game message, ' +
    'email form, and exit code.';

    // Title is displayed in the header.
    // is this necessary?
    EndScreen.title = 'End Screen';
    // Classname is added to the widgets.
    EndScreen.className = 'end-screen';

    // Dependencies are checked when the widget is created.
    EndScreen.dependencies = { JSUS: {} };

    // Constructor taking a configuration parameter.
    // The options object is always existing even if no
    //
    function EndScreen(options) {
        this.options = options;
        this.init(true, true);
    }

    // Implements the Widget.append method.
    EndScreen.prototype.append = function() {
        this.bodyDiv.appendChild(this.endScreen);

        var that;
        var emailErrorString;
        var emailButton, emailInput, emailForm;
        var feedbackButton, feedbackForm, feedbackInput;
        var charCounter;

        that = this;

        emailButton = W.getElementById('endscreen-submit-email');
        emailForm = W.getElementById('endscreen-email-form');
        emailInput = W.getElementById('endscreen-email');
        emailErrorString = 'Not a valid email address, ' +
                           'please correct it and submit again.';

        feedbackForm = W.getElementById('endscreen-feedback-form');
        feedbackInput = W.getElementById('endscreen-feedback');
        feedbackButton = W.getElementById('endscreen-submit-feedback');

        charCounter = W.getElementById('endscreen-char-count');

        if (this.showEmailForm) {
            emailForm.addEventListener('submit', function(event) {
                event.preventDefault();

                var email, indexAt, indexDot;
                email = emailInput.value;
                if (email.trim().length > 5) {
                    indexAt = email.indexOf('@');
                    if (indexAt !== -1 &&
                        indexAt !== 0 &&
                        indexAt !== (email.length-1)) {

                        indexDot = email.lastIndexOf('.');
                        if (indexDot !== -1 &&
                            indexDot !== (email.length-1) &&
                            indexDot > (indexAt+1)) {

                            node.say('email', 'SERVER', email);

                            emailButton.disabled = true;
                            emailInput.disabled = true;
                            emailButton.value = 'Sent!';
                        }
                    }
                }
                emailButton.value = emailErrorString;
            }, true);
        }

        if (this.showFeedbackForm) {
            feedbackForm.addEventListener('submit', function(event) {
                var feedback;

                event.preventDefault();
                feedback = feedbackInput.value.trim();

                if (feedback.length < that.maxFeedbackLength) {
                    node.say('feedback', 'SERVER', feedback);

                    feedbackButton.disabled = true;
                    feedbackButton.value = 'Sent!';
                }
                else {
                    feedbackButton.value = 'Please shorten your response ' +
                                           'and submit again.';
                }
            });

            feedbackForm.addEventListener('input', function(event) {
                var charLeft;

                charLeft = that.maxFeedbackLength - feedbackInput.value.length;
                charCounter.innerHTML = Math.abs(charLeft);

                if (charLeft < 0) {
                    charCounter.innerHTML += ' characters over.';
                }
                else {
                    charCounter.innerHTML += ' characters remaining.';
                }
            });
        }
    };

    EndScreen.prototype.init = function() {
        var exitCode; // exit code
        var topHTML, messageHTML, totalWinHTML, exitCodeHTML, emailHTML,
            endHTML, endScreenHTML;
        var endScreen;

        this.headerMessage = this.options.headerMessage ||
        'Thank You for Participating!';
        this.message = this.options.message ||
        'You have now completed this task and your data has been saved. ' +
        'Please go back to the Amazon Mechanical Turk web site and ' +
        'submit the HIT.';
        this.showEmailForm = 'showEmailForm' in this.options ?
                            this.options.showEmailForm : true;
        this.showFeedbackForm = 'showFeedbackForm' in this.options ?
                            this.options.showFeedbackForm : true;
        this.showTotalWin = 'showTotalWin' in this.options ?
                            this.options.showTotalWin : true;
        this.showExitCode = 'showExitCode' in this.options ?
                            this.options.showExitCode : true;
        this.maxFeedbackLength = this.options.maxFeedbackLength || 800;

        messageHTML = '
' + this.headerMessage +'
' + '
' +
                      this.message + '
';
        endScreenHTML = messageHTML;

        if (this.showTotalWin) {
            // totalWinHTML = '
Your total win: ' + totalWin + '
';
            totalWinHTML = '
Your total win: ' +
                           '<input id="endscreen-total" ' +
                           'class="form-control" ' +
                           'disabled></input>' +
                           '
';
            endScreenHTML += totalWinHTML;
        }
        if (this.showExitCode) {
            // exitCodeHTML = '
Your Exit code: ' + exitCode + '
';
            exitCodeHTML = '
Your exit code: ' +
                           '<input id="endscreen-exit-code" ' +
                           'class="form-control" disabled></input>' +
                           '
';
            endScreenHTML += exitCodeHTML;
        }
        if (this.showEmailForm) {
            emailHTML = '<form id="endscreen-email-form">' +
            '' +
            'Would you like to be contacted again ' +
            'for future experiments? ' +
            'If so, leave your email here and press submit:' +
            '' +
            '<input id="endscreen-email" type="text" placeholder="Email" ' +
            'class="form-control"/>' +
            '<input class="btn btn-lg btn-primary" ' +
            'id="endscreen-submit-email" ' +
            'type="submit" value="Submit email"></input>' +
            '</form>';
            endScreenHTML += emailHTML;
        }
        if (this.showFeedbackForm) {
            feedbackFormHTML = '<form id="endscreen-feedback-form">' +
            '' +
            'Any feedback about the experiment? Let us know here:' +
            '' +
            '<textarea id="endscreen-feedback" type="text" rows="3"' +
            'class="form-control"></textarea>' +
            '' +
            this.maxFeedbackLength +
            ' characters left' +
            '<input class="btn btn-lg btn-primary" ' +
            'id="endscreen-submit-feedback" ' +
            'type="submit" value="Submit feedback"></input>' +
            '</form>';
            endScreenHTML += feedbackFormHTML;
        }

        this.endScreen = document.createElement('div');
        this.endScreen.class = this.className;
        this.endScreen.id = 'endscreen';
        this.endScreen.innerHTML = endScreenHTML;
    }

    // Implements the Widget.listeners method.
    EndScreen.prototype.listeners = function() {
        // Listeners added here are automatically removed
        // when the widget is destroyed.
        node.on.data('WIN', function(message) {
            var totalWin;
            var exitCode;
            var data;

            var totalHTML, exitCodeHTML;

            data = message.data;
            totalWin = data.total;
            exitCode = data.exit;

            totalHTML = W.getElementById('endscreen-total');
            exitCodeHTML = W.getElementById('endscreen-exit-code');

            if (totalHTML) {
                totalHTML.value = totalWin;
            }

            if (exitCodeHTML) {
                exitCodeHTML.value = exitCode;
            }
        });
    };
})(node);
<commit_msg>update EndScreen version<commit_after>(function() {  // self-executing function for encapsulation

    // Register the widget in the widgets collection.
    node.widgets.register('EndScreen', EndScreen);

    // Add Meta-data
    EndScreen.version = '0.1.0';
    EndScreen.description = 'Game end screen. With end game message, ' +
    'email form, and exit code.';

    // Title is displayed in the header.
    // is this necessary?
    EndScreen.title = 'End Screen';
    // Classname is added to the widgets.
    EndScreen.className = 'end-screen';

    // Dependencies are checked when the widget is created.
    EndScreen.dependencies = { JSUS: {} };

    // Constructor taking a configuration parameter.
    // The options object is always existing even if no
    //
    function EndScreen(options) {
        this.options = options;
        this.init(true, true);
    }

    // Implements the Widget.append method.
    EndScreen.prototype.append = function() {
        this.bodyDiv.appendChild(this.endScreen);

        var that;
        var emailErrorString;
        var emailButton, emailInput, emailForm;
        var feedbackButton, feedbackForm, feedbackInput;
        var charCounter;

        that = this;

        emailButton = W.getElementById('endscreen-submit-email');
        emailForm = W.getElementById('endscreen-email-form');
        emailInput = W.getElementById('endscreen-email');
        emailErrorString = 'Not a valid email address, ' +
                           'please correct it and submit again.';

        feedbackForm = W.getElementById('endscreen-feedback-form');
        feedbackInput = W.getElementById('endscreen-feedback');
        feedbackButton = W.getElementById('endscreen-submit-feedback');

        charCounter = W.getElementById('endscreen-char-count');

        if (this.showEmailForm) {
            emailForm.addEventListener('submit', function(event) {
                event.preventDefault();

                var email, indexAt, indexDot;
                email = emailInput.value;
                if (email.trim().length > 5) {
                    indexAt = email.indexOf('@');
                    if (indexAt !== -1 &&
                        indexAt !== 0 &&
                        indexAt !== (email.length-1)) {

                        indexDot = email.lastIndexOf('.');
                        if (indexDot !== -1 &&
                            indexDot !== (email.length-1) &&
                            indexDot > (indexAt+1)) {

                            node.say('email', 'SERVER', email);

                            emailButton.disabled = true;
                            emailInput.disabled = true;
                            emailButton.value = 'Sent!';
                        }
                    }
                }
                emailButton.value = emailErrorString;
            }, true);
        }

        if (this.showFeedbackForm) {
            feedbackForm.addEventListener('submit', function(event) {
                var feedback;

                event.preventDefault();
                feedback = feedbackInput.value.trim();

                if (feedback.length < that.maxFeedbackLength) {
                    node.say('feedback', 'SERVER', feedback);

                    feedbackButton.disabled = true;
                    feedbackButton.value = 'Sent!';
                }
                else {
                    feedbackButton.value = 'Please shorten your response ' +
                                           'and submit again.';
                }
            });

            feedbackForm.addEventListener('input', function(event) {
                var charLeft;

                charLeft = that.maxFeedbackLength - feedbackInput.value.length;
                charCounter.innerHTML = Math.abs(charLeft);

                if (charLeft < 0) {
                    charCounter.innerHTML += ' characters over.';
                }
                else {
                    charCounter.innerHTML += ' characters remaining.';
                }
            });
        }
    };

    EndScreen.prototype.init = function() {
        var exitCode; // exit code
        var topHTML, messageHTML, totalWinHTML, exitCodeHTML, emailHTML,
            endHTML, endScreenHTML;
        var endScreen;

        this.headerMessage = this.options.headerMessage ||
        'Thank You for Participating!';
        this.message = this.options.message ||
        'You have now completed this task and your data has been saved. ' +
        'Please go back to the Amazon Mechanical Turk web site and ' +
        'submit the HIT.';
        this.showEmailForm = 'showEmailForm' in this.options ?
                            this.options.showEmailForm : true;
        this.showFeedbackForm = 'showFeedbackForm' in this.options ?
                            this.options.showFeedbackForm : true;
        this.showTotalWin = 'showTotalWin' in this.options ?
                            this.options.showTotalWin : true;
        this.showExitCode = 'showExitCode' in this.options ?
                            this.options.showExitCode : true;
        this.maxFeedbackLength = this.options.maxFeedbackLength || 800;

        messageHTML = '
' + this.headerMessage +'
' + '
' +
                      this.message + '
';
        endScreenHTML = messageHTML;

        if (this.showTotalWin) {
            // totalWinHTML = '
Your total win: ' + totalWin + '
';
            totalWinHTML = '
Your total win: ' +
                           '<input id="endscreen-total" ' +
                           'class="form-control" ' +
                           'disabled></input>' +
                           '
';
            endScreenHTML += totalWinHTML;
        }
        if (this.showExitCode) {
            // exitCodeHTML = '
Your Exit code: ' + exitCode + '
';
            exitCodeHTML = '
Your exit code: ' +
                           '<input id="endscreen-exit-code" ' +
                           'class="form-control" disabled></input>' +
                           '
';
            endScreenHTML += exitCodeHTML;
        }
        if (this.showEmailForm) {
            emailHTML = '<form id="endscreen-email-form">' +
            '' +
            'Would you like to be contacted again ' +
            'for future experiments? ' +
            'If so, leave your email here and press submit:' +
            '' +
            '<input id="endscreen-email" type="text" placeholder="Email" ' +
            'class="form-control"/>' +
            '<input class="btn btn-lg btn-primary" ' +
            'id="endscreen-submit-email" ' +
            'type="submit" value="Submit email"></input>' +
            '</form>';
            endScreenHTML += emailHTML;
        }
        if (this.showFeedbackForm) {
            feedbackFormHTML = '<form id="endscreen-feedback-form">' +
            '' +
            'Any feedback about the experiment? Let us know here:' +
            '' +
            '<textarea id="endscreen-feedback" type="text" rows="3"' +
            'class="form-control"></textarea>' +
            '' +
            this.maxFeedbackLength +
            ' characters left' +
            '<input class="btn btn-lg btn-primary" ' +
            'id="endscreen-submit-feedback" ' +
            'type="submit" value="Submit feedback"></input>' +
            '</form>';
            endScreenHTML += feedbackFormHTML;
        }

        this.endScreen = document.createElement('div');
        this.endScreen.class = this.className;
        this.endScreen.id = 'endscreen';
        this.endScreen.innerHTML = endScreenHTML;
    }

    // Implements the Widget.listeners method.
    EndScreen.prototype.listeners = function() {
        // Listeners added here are automatically removed
        // when the widget is destroyed.
        node.on.data('WIN', function(message) {
            var totalWin;
            var exitCode;
            var data;

            var totalHTML, exitCodeHTML;

            data = message.data;
            totalWin = data.total;
            exitCode = data.exit;

            totalHTML = W.getElementById('endscreen-total');
            exitCodeHTML = W.getElementById('endscreen-exit-code');

            if (totalHTML) {
                totalHTML.value = totalWin;
            }

            if (exitCodeHTML) {
                exitCodeHTML.value = exitCode;
            }
        });
    };
})(node);
<|endoftext|>


<commit_before>var app = require('app');
var path = require('path');
var optimist = require('optimist');

// Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', function() {
  if (app.listeners('window-all-closed').length == 1)
    app.quit();
});

var argv = optimist(process.argv.slice(1)).boolean('ci').argv;

// Start the specified app if there is one specified in command line, otherwise
// start the default app.
if (argv._.length > 0) {
  try {
    require(path.resolve(argv._[0]));
  } catch(e) {
    if (e.code == 'MODULE_NOT_FOUND') {
      console.error(e.stack);
      console.error('Specified app is invalid');
      process.exit(1);
    } else {
      throw e;
    }
  }
} else if (argv.version) {
  console.log('v' + process.versions['atom-shell']);
  process.exit(0);
} else {
  require('./default_app.js');
}
<commit_msg>Use dialog to report invalid app.<commit_after>var app = require('app');
var dialog = require('dialog');
var path = require('path');
var optimist = require('optimist');

// Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', function() {
  if (app.listeners('window-all-closed').length == 1)
    app.quit();
});

var argv = optimist(process.argv.slice(1)).boolean('ci').argv;

// Start the specified app if there is one specified in command line, otherwise
// start the default app.
if (argv._.length > 0) {
  try {
    require(path.resolve(argv._[0]));
  } catch(e) {
    if (e.code == 'MODULE_NOT_FOUND') {
      app.focus();
      dialog.showMessageBox({
        type: 'warning',
        buttons: ['OK'],
        title: 'Error opening app',
        message: 'The app provided is not a valid atom-shell app, please read the docs on how to write one:',
        detail: 'https://github.com/atom/atom-shell/tree/master/docs'
      });
      process.exit(1);
    } else {
      throw e;
    }
  }
} else if (argv.version) {
  console.log('v' + process.versions['atom-shell']);
  process.exit(0);
} else {
  require('./default_app.js');
}
<|endoftext|>


<commit_before>var _noCaptchaFields=_noCaptchaFields || [];

function noCaptchaFieldRender() {
    var submitListener=function(e) {
        e.preventDefault();

        grecaptcha.execute();
    };

    for(var i=0;i<_noCaptchaFields.length;i++) {
        var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);

        //For the invisible captcha we need to setup some callback listeners
        if(field.getAttribute('data-size')=='invisible' && field.getAttribute('data-callback')==null) {
            var form=document.getElementById(field.getAttribute('data-form'));
            var superHandler=false;

            if(typeof jQuery!='undefined' && typeof jQuery.fn.validate!='undefined') {
                var formValidator=jQuery(form).data('validator');
                var superHandler=formValidator.settings.submitHandler;
                formValidator.settings.submitHandler=function(form) {
                    grecaptcha.execute();
                };
            }else {
                if(form && form.addEventListener) {
                    form.addEventListener('submit', submitListener);
                }else if(form && form.attachEvent) {
                    window.attachEvent('onsubmit', submitListener);
                }else if(console.error) {
                    console.error('Could not attach event to the form');
                }
            }

            window['Nocaptcha-'+_noCaptchaFields[i]]=function() {
                if(typeof jQuery!='undefined' && typeof jQuery.fn.validate!='undefined' && superHandler) {
                    superHandler(form);
                }else {
                    form.submit();
                }
            };
        }

        var options={
            'sitekey': field.getAttribute('data-sitekey'),
            'theme': field.getAttribute('data-theme'),
            'type': field.getAttribute('data-type'),
            'size': field.getAttribute('data-size'),
            'badge': field.getAttribute('data-badge'),
            'callback': (field.getAttribute('data-callback') ? field.getAttribute('data-callback') : 'Nocaptcha-'+_noCaptchaFields[i])
        };

        var widget_id = grecaptcha.render(field, options);
        field.setAttribute("data-widgetid", widget_id);
    }
}
<commit_msg>Added potential fix for #47<commit_after>var _noCaptchaFields=_noCaptchaFields || [];

function noCaptchaFieldRender() {
    var submitListener=function(e) {
        e.preventDefault();

        grecaptcha.execute();
    };

    for(var i=0;i<_noCaptchaFields.length;i++) {
        var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);

        //For the invisible captcha we need to setup some callback listeners
        if(field.getAttribute('data-size')=='invisible' && field.getAttribute('data-callback')==null) {
            var form=document.getElementById(field.getAttribute('data-form'));
            var superHandler=false;

            if(typeof jQuery!='undefined' && typeof jQuery.fn.validate!='undefined') {
                var formValidator=jQuery(form).data('validator');
                var superHandler=formValidator.settings.submitHandler;
                formValidator.settings.submitHandler=function(form) {
                    grecaptcha.execute();
                };
            }else {
                if(form && form.addEventListener) {
                    form.addEventListener('submit', submitListener);
                }else if(form && form.attachEvent) {
                    window.attachEvent('onsubmit', submitListener);
                }else if(console.error) {
                    console.error('Could not attach event to the form');
                }
            }

            window['Nocaptcha-'+_noCaptchaFields[i]]=function() {
                return new Promise(function(resolve, reject) {
                    if(typeof jQuery!='undefined' && typeof jQuery.fn.validate!='undefined' && superHandler) {
                        superHandler(form);
                    }else {
                        form.submit();
                    }

                    resolve();
                });
            };
        }

        var options={
            'sitekey': field.getAttribute('data-sitekey'),
            'theme': field.getAttribute('data-theme'),
            'type': field.getAttribute('data-type'),
            'size': field.getAttribute('data-size'),
            'badge': field.getAttribute('data-badge'),
            'callback': (field.getAttribute('data-callback') ? field.getAttribute('data-callback') : 'Nocaptcha-'+_noCaptchaFields[i])
        };

        var widget_id = grecaptcha.render(field, options);
        field.setAttribute("data-widgetid", widget_id);
    }
}
<|endoftext|>


<commit_before>/* Copyright 2015 Bloomberg Finance L.P.
 *
 * Licensed 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.
 */

define(["d3", "./Selector", "./utils", "./lasso_test"], function(d3, Selectors, utils, point_in_lasso) {
    "use strict";

    var LassoSelector = Selectors.BaseXYSelector.extend({
        render : function() {
            LassoSelector.__super__.render.apply(this);
            var scale_creation_promise = this.create_scales();
            this.line = d3.svg.line();
            this.lasso_vertices = [];
            this.lasso_counter = 0;

            var self = this;
            Promise.all([this.mark_views_promise, scale_creation_promise]).then(function() {
                var drag = d3.behavior.drag()
                    .on("dragstart", _.bind(self.drag_start, self))
                    .on("drag", _.bind(self.drag_move, self))
                    .on("dragend", _.bind(self.drag_end, self));

                d3.select(window).on("keydown", _.bind(self.keydown, self));

                self.el.attr("class", "lassoselector");

                //container for mouse events
                self.background = self.el.append("rect")
                    .attr("x", 0)
                    .attr("y", 0)
                    .attr("width", self.width)
                    .attr("height", self.height)
                    .attr("visibility", "hidden")
                    .attr("pointer-events", "all")
                    .style("cursor", "crosshair")
                    .call(drag);

                self.create_listeners();
            });
        },
        create_listeners: function() {
            LassoSelector.__super__.create_listeners.apply(this);
            this.model.on("change:color", this.change_color, this);
        },
        change_color: function(model, color) {
            if (color) {
                this.el.selectAll("path").style("stroke", color);
            }
        },
        drag_start: function() {
            var self = this;
            this.lasso_vertices = [];
            var lasso = this.el.append("path")
                .attr("id", "l" + (++this.lasso_counter))
                .on("click", function() {
                    //toggle the opacity of lassos
                    var lasso = d3.select(this);
                    lasso.classed("selected", !lasso.classed("selected"));
                });
            var color = this.model.get("color");
            if (color) {
                lasso.style("stroke", color);
            }
        },
        drag_move: function() {
            this.lasso_vertices.push(d3.mouse(this.background.node()));
            this.el.select("#l" + this.lasso_counter)
                .attr("d", this.line(this.lasso_vertices));
        },
        drag_end: function() {
            //close the lasso
            this.el.select("#l" + this.lasso_counter)
                .attr("d", this.line(this.lasso_vertices) + "Z");

            var mark_data_in_lasso = false;
            var self = this;
            //update idx_selected for each mark
            this.mark_views.map(function(mark_view) {
                var data_in_lasso = mark_view.update_idx_selected_in_lasso("l" + self.lasso_counter,
                                                                           self.lasso_vertices,
                                                                           point_in_lasso);
                if (data_in_lasso) {
                    mark_data_in_lasso = true;
                }
            });

            //remove the lasso if it doesnt have any mark data
            if (!mark_data_in_lasso) {
                this.el.select("#l" + this.lasso_counter).remove();
                this.lasso_counter--;
            }
        },
        relayout: function() {
            LassoSelector.__super__.relayout.apply(this);
            this.background.attr("width", this.width).attr("height", this.height);
        },
        keydown: function() {
           //delete key pressed
           if (d3.event.keyCode === 46) {
               //delete selected lassos
               var lassos_to_delete = this.el.selectAll(".selected");

               var self = this;
               lassos_to_delete.each(function() {
                   var lasso_name = d3.select(this).attr("id");
                   //delete idx_selected for each mark
                   self.mark_views.map(function(mark_view) {
                       mark_view.update_idx_selected_in_lasso(lasso_name, null, null);
                   });
               });
               lassos_to_delete.remove();
          }
       },
    });

    return {
        LassoSelector: LassoSelector,
    };
});
<commit_msg>d3 -> ./d3<commit_after>/* Copyright 2015 Bloomberg Finance L.P.
 *
 * Licensed 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.
 */

define(["./d3", "./Selector", "./utils", "./lasso_test"], function(d3, Selectors, utils, point_in_lasso) {
    "use strict";

    var LassoSelector = Selectors.BaseXYSelector.extend({
        render : function() {
            LassoSelector.__super__.render.apply(this);
            var scale_creation_promise = this.create_scales();
            this.line = d3.svg.line();
            this.lasso_vertices = [];
            this.lasso_counter = 0;

            var self = this;
            Promise.all([this.mark_views_promise, scale_creation_promise]).then(function() {
                var drag = d3.behavior.drag()
                    .on("dragstart", _.bind(self.drag_start, self))
                    .on("drag", _.bind(self.drag_move, self))
                    .on("dragend", _.bind(self.drag_end, self));

                d3.select(window).on("keydown", _.bind(self.keydown, self));

                self.el.attr("class", "lassoselector");

                //container for mouse events
                self.background = self.el.append("rect")
                    .attr("x", 0)
                    .attr("y", 0)
                    .attr("width", self.width)
                    .attr("height", self.height)
                    .attr("visibility", "hidden")
                    .attr("pointer-events", "all")
                    .style("cursor", "crosshair")
                    .call(drag);

                self.create_listeners();
            });
        },
        create_listeners: function() {
            LassoSelector.__super__.create_listeners.apply(this);
            this.model.on("change:color", this.change_color, this);
        },
        change_color: function(model, color) {
            if (color) {
                this.el.selectAll("path").style("stroke", color);
            }
        },
        drag_start: function() {
            var self = this;
            this.lasso_vertices = [];
            var lasso = this.el.append("path")
                .attr("id", "l" + (++this.lasso_counter))
                .on("click", function() {
                    console.log("foobar");
                    //toggle the opacity of lassos
                    var lasso = d3.select(this);
                    lasso.classed("selected", !lasso.classed("selected"));
                });
            var color = this.model.get("color");
            if (color) {
                lasso.style("stroke", color);
            }
        },
        drag_move: function() {
            this.lasso_vertices.push(d3.mouse(this.background.node()));
            this.el.select("#l" + this.lasso_counter)
                .attr("d", this.line(this.lasso_vertices));
        },
        drag_end: function() {
            //close the lasso
            this.el.select("#l" + this.lasso_counter)
                .attr("d", this.line(this.lasso_vertices) + "Z");

            var mark_data_in_lasso = false;
            var self = this;
            //update idx_selected for each mark
            this.mark_views.map(function(mark_view) {
                var data_in_lasso = mark_view.update_idx_selected_in_lasso("l" + self.lasso_counter,
                                                                           self.lasso_vertices,
                                                                           point_in_lasso);
                if (data_in_lasso) {
                    mark_data_in_lasso = true;
                }
            });

            //remove the lasso if it doesnt have any mark data
            if (!mark_data_in_lasso) {
                this.el.select("#l" + this.lasso_counter).remove();
                this.lasso_counter--;
            }
        },
        relayout: function() {
            LassoSelector.__super__.relayout.apply(this);
            this.background.attr("width", this.width).attr("height", this.height);
        },
        keydown: function() {
           //delete key pressed
           if (d3.event.keyCode === 46) {
               //delete selected lassos
               var lassos_to_delete = this.el.selectAll(".selected");

               var self = this;
               lassos_to_delete.each(function() {
                   var lasso_name = d3.select(this).attr("id");
                   //delete idx_selected for each mark
                   self.mark_views.map(function(mark_view) {
                       mark_view.update_idx_selected_in_lasso(lasso_name, null, null);
                   });
               });
               lassos_to_delete.remove();
          }
       },
    });

    return {
        LassoSelector: LassoSelector,
    };
});
<|endoftext|>


<commit_before>Polymer({
	is: 'tripod-hero-marquee',

	properties: {
		/**
		 * The position of the content, separated by a dash. Available values are :
		 * "top-left", "top-center", "top-right",
		 * "center-left", "center-center", "center-right",
		 * "bottom-left", "bottom-center" and "bottom-right".
		**/
		contentPosition: {
			type: String,
			value: 'center-center',
			observer: '_validateContentPosition'
		},

		/**
		 * The CSS Layout for the hero content. Defaults to Flexbox, and can be set to "grid" for CSS Grid Layout.
		**/
		contentLayout: {
			type: String,
			value: 'flexbox',
			observer: '_validateContentLayout'
		},

		/**
		 * An attribute to help with responsive sizing.
		 * Use with `iron-media-query query-matches={{dekstopLayout}}` to bind a
		 * breakpoint at which to switch from the mobile layout.
		**/
		desktopLayout: {
			type: Boolean,
			value: false,
			reflectToAttribute: true
		},

		/**
		 * An attribute used to avoid distributed content (content passed in from the Light DOM) from
		 * flashing with external styling in browsers using the webcomponent.org shims if the shims.
		**/
		loaded: {
			type: Boolean,
			value: false,
			reflectToAttribute: true
		}
	},

	/**
	 * Life cycle function that gets called when the element is
	 * first attached to the DOM
	**/
	attached: function attached() {
		this.loaded = true;
	},

	/**
	 * Makes sure that the content position being set is valid
	 * if not it defaults to `center-center`
	**/
	_validateContentPosition: function() {
		if (!this._validate(this._allowedPositions, this.contentPosition, 'content-position')){
			this.contentPosition = this._allowedPositions[4]; /*'center-center'*/
		};
	},

	/**
	 * Makes sure that the content layout being set is valid
	 * if not it defaults to `flexbox`
	**/
	_validateContentLayout: function() {
		if (!this._validate(this._allowedLayouts, this.contentLayout, 'content-layout')) {
			this.contentLayout = this._allowedLayouts[0]; /*'flexbox'*/
		};
	},

	/**
	 * Generalized validation function for validation observers.
	**/
	_validate: function(allowedValues, inputValue, validateWhat) {
		let valid = false;
		for (let i = 0; i < allowedValues.length; i++) {
			if (inputValue === allowedValues[i]) {
				valid = true;
			}
		};
		if (valid = false) {
			console.warn(inputValue + ' is not a valid input for ' + validateWhat);
			return false;
		} else {
			return true
		};
	},

	/**
	 * Getters
	**/
	get _allowedPositions() {
		return['top-left', 'top-center', 'top-right', 'center-left', 'center-center', 'center-right', 'bottom-left', 'bottom-center', 'bottom-right'];
	},

	get _allowedLayouts() {
		return ['flexbox', 'grid'];
	}

});
<commit_msg>Missing an equal sign<commit_after>Polymer({
	is: 'tripod-hero-marquee',

	properties: {
		/**
		 * The position of the content, separated by a dash. Available values are :
		 * "top-left", "top-center", "top-right",
		 * "center-left", "center-center", "center-right",
		 * "bottom-left", "bottom-center" and "bottom-right".
		**/
		contentPosition: {
			type: String,
			value: 'center-center',
			observer: '_validateContentPosition'
		},

		/**
		 * The CSS Layout for the hero content. Defaults to Flexbox, and can be set to "grid" for CSS Grid Layout.
		**/
		contentLayout: {
			type: String,
			value: 'flexbox',
			observer: '_validateContentLayout'
		},

		/**
		 * An attribute to help with responsive sizing.
		 * Use with `iron-media-query query-matches={{dekstopLayout}}` to bind a
		 * breakpoint at which to switch from the mobile layout.
		**/
		desktopLayout: {
			type: Boolean,
			value: false,
			reflectToAttribute: true
		},

		/**
		 * An attribute used to avoid distributed content (content passed in from the Light DOM) from
		 * flashing with external styling in browsers using the webcomponent.org shims if the shims.
		**/
		loaded: {
			type: Boolean,
			value: false,
			reflectToAttribute: true
		}
	},

	/**
	 * Life cycle function that gets called when the element is
	 * first attached to the DOM
	**/
	attached: function attached() {
		this.loaded = true;
	},

	/**
	 * Makes sure that the content position being set is valid
	 * if not it defaults to `center-center`
	**/
	_validateContentPosition: function() {
		if (!this._validate(this._allowedPositions, this.contentPosition, 'content-position')){
			this.contentPosition = this._allowedPositions[4]; /*'center-center'*/
		};
	},

	/**
	 * Makes sure that the content layout being set is valid
	 * if not it defaults to `flexbox`
	**/
	_validateContentLayout: function() {
		if (!this._validate(this._allowedLayouts, this.contentLayout, 'content-layout')) {
			this.contentLayout = this._allowedLayouts[0]; /*'flexbox'*/
		};
	},

	/**
	 * Generalized validation function for validation observers.
	**/
	_validate: function(allowedValues, inputValue, validateWhat) {
		let valid = false;
		for (let i = 0; i < allowedValues.length; i++) {
			if (inputValue === allowedValues[i]) {
				valid = true;
			}
		};
		if (valid == false) {
			console.warn(inputValue + ' is not a valid input for ' + validateWhat);
			return false;
		} else {
			return true
		};
	},

	/**
	 * Getters
	**/
	get _allowedPositions() {
		return['top-left', 'top-center', 'top-right', 'center-left', 'center-center', 'center-right', 'bottom-left', 'bottom-center', 'bottom-right'];
	},

	get _allowedLayouts() {
		return ['flexbox', 'grid'];
	}

});
<|endoftext|>


<commit_before>/*************************************************
 * Copyright (c) 2015 Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

  /**
 * @ngdoc function
 * @name forms.function:Users
 * @description This form is for adding/editing users
*/

export default
    angular.module('UserFormDefinition', [])
        .factory('UserForm', ['i18n', function(i18n) {
        return {

            addTitle: i18n._('New User'),
            editTitle: '{{ username }}',
            name: 'user',
            // the top-most node of generated state tree
            stateTree: 'users',
            forceListeners: true,
            tabs: true,

            fields: {
                first_name: {
                    label: i18n._('First Name'),
                    type: 'text',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)',
                    required: true,
                    capitalize: true
                },
                last_name: {
                    label: i18n._('Last Name'),
                    type: 'text',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)',
                    required: true,
                    capitalize: true
                },
                email: {
                    label: i18n._('Email'),
                    type: 'email',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)',
                    required: true,
                    autocomplete: false
                },
                username: {
                    label: i18n._('Username'),
                    type: 'text',
                    awRequiredWhen: {
                        reqExpression: "not_ldap_user && external_account === null",
                        init: true
                    },
                    autocomplete: false,
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                organization: {
                    label: i18n._('Organization'),
                    type: 'lookup',
                    list: 'OrganizationList',
                    basePath: 'organizations',
                    sourceModel: 'organization',
                    sourceField: 'name',
                    required: true,
                    excludeMode: 'edit',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                password: {
                    label: i18n._('Password'),
                    type: 'sensitive',
                    hasShowInputButton: true,
                    ngShow: 'ldap_user == false && socialAuthUser === false && external_account === null',
                    ngRequired: "$state.match('add')",
                    labelNGClass: "{'prepend-asterisk' : $state.matches('add')}",
                    ngChange: "clearPWConfirm('password_confirm')",
                    autocomplete: false,
                    chkPass: true,
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                password_confirm: {
                    label: i18n._('Confirm Password'),
                    type: 'sensitive',
                    hasShowInputButton: true,
                    ngShow: 'ldap_user == false && socialAuthUser === false && external_account === null',
                    ngRequired: "$state.match('add')",
                    labelNGClass: "{'prepend-asterisk' : $state.matches('add')}",
                    awPassMatch: true,
                    associated: 'password',
                    autocomplete: false,
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                user_type: {
                    label: i18n._('User Type'),
                    type: 'select',
                    ngOptions: 'item as item.label for item in user_type_options track by item.type',
                    disableChooseOption: true,
                    ngModel: 'user_type',
                    ngShow: 'current_user["is_superuser"]',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
            },

            buttons: {
                cancel: {
                    ngClick: 'formCancel()',
                    ngShow: '(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                close: {
                    ngClick: 'formCancel()',
                    ngShow: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                save: {
                    ngClick: 'formSave()',
                    ngDisabled: true,
                    ngShow: '(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                }
            },

            related: {
                organizations: {
                    awToolTip: i18n._('Please save before assigning to organizations'),
                    basePath: 'api/v1/users/{{$stateParams.user_id}}/organizations',
                    emptyListText: i18n._('Please add user to an Organization.'),
                    search: {
                        page_size: '10'
                    },
                    dataPlacement: 'top',
                    type: 'collection',
                    title: i18n._('Organizations'),
                    iterator: 'organization',
                    index: false,
                    open: false,

                    actions: {},

                    fields: {
                        name: {
                            key: true,
                            label: i18n._('Name')
                        },
                        description: {
                            label: i18n._('Description')
                        }
                    },
                    //hideOnSuperuser: true // RBAC defunct
                },
                teams: {
                    awToolTip: i18n._('Please save before assigning to teams'),
                    basePath: 'api/v1/users/{{$stateParams.user_id}}/teams',
                    search: {
                        page_size: '10'
                    },
                    dataPlacement: 'top',
                    type: 'collection',
                    title: i18n._('Teams'),
                    iterator: 'team',
                    open: false,
                    index: false,
                    actions: {},
                    emptyListText: i18n._('This user is not a member of any teams'),
                    fields: {
                        name: {
                            key: true,
                            label: i18n._('Name')
                        },
                        description: {
                            label: i18n._('Description')
                        }
                    },
                    //hideOnSuperuser: true // RBAC defunct
                },
                permissions: {
                    basePath: 'api/v1/users/{{$stateParams.user_id}}/roles/',
                    search: {
                        page_size: '10',
                        order_by: 'id'
                    },
                    awToolTip: i18n._('Please save before assigning to organizations'),
                    dataPlacement: 'top',
                    hideSearchAndActions: true,
                    type: 'collection',
                    title: i18n._('Permissions'),
                    iterator: 'permission',
                    open: false,
                    index: false,
                    emptyListText: i18n._('No permissions have been granted'),
                    fields: {
                        name: {
                            label: i18n._('Name'),
                            ngBind: 'permission.summary_fields.resource_name',
                            linkTo: '{{convertApiUrl(permission.related[permission.summary_fields.resource_type])}}',
                            noSort: true
                        },
                        type: {
                            label: i18n._('Type'),
                            ngBind: 'permission.summary_fields.resource_type_display_name',
                            noSort: true
                        },
                        role: {
                            label: i18n._('Role'),
                            ngBind: 'permission.name',
                            noSort: true
                        },
                    },
                    actions: {
                        add: {
                            ngClick: "$state.go('.add')",
                            label: 'Add',
                            awToolTip: i18n._('Grant Permission'),
                            actionClass: 'btn List-buttonSubmit',
                            buttonContent: '+ ' + i18n._('ADD PERMISSIONS'),
                            ngShow: '(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                        }
                    },
                    fieldActions: {
                        "delete": {
                            label: i18n._('Remove'),
                            ngClick: 'deletePermissionFromUser(user_id, username, permission.name, permission.summary_fields.resource_name, permission.related.users)',
                            iconClass: 'fa fa-times',
                            awToolTip: i18n._('Dissasociate permission from user'),
                            ngShow: 'permission.summary_fields.user_capabilities.unattach'
                        }
                    },
                    //hideOnSuperuser: true // RBAC defunct
                }
            }

        };}]);
<commit_msg>hide add permissions when editing super user<commit_after>/*************************************************
 * Copyright (c) 2015 Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

  /**
 * @ngdoc function
 * @name forms.function:Users
 * @description This form is for adding/editing users
*/

export default
    angular.module('UserFormDefinition', [])
        .factory('UserForm', ['i18n', function(i18n) {
        return {

            addTitle: i18n._('New User'),
            editTitle: '{{ username }}',
            name: 'user',
            // the top-most node of generated state tree
            stateTree: 'users',
            forceListeners: true,
            tabs: true,

            fields: {
                first_name: {
                    label: i18n._('First Name'),
                    type: 'text',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)',
                    required: true,
                    capitalize: true
                },
                last_name: {
                    label: i18n._('Last Name'),
                    type: 'text',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)',
                    required: true,
                    capitalize: true
                },
                email: {
                    label: i18n._('Email'),
                    type: 'email',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)',
                    required: true,
                    autocomplete: false
                },
                username: {
                    label: i18n._('Username'),
                    type: 'text',
                    awRequiredWhen: {
                        reqExpression: "not_ldap_user && external_account === null",
                        init: true
                    },
                    autocomplete: false,
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                organization: {
                    label: i18n._('Organization'),
                    type: 'lookup',
                    list: 'OrganizationList',
                    basePath: 'organizations',
                    sourceModel: 'organization',
                    sourceField: 'name',
                    required: true,
                    excludeMode: 'edit',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                password: {
                    label: i18n._('Password'),
                    type: 'sensitive',
                    hasShowInputButton: true,
                    ngShow: 'ldap_user == false && socialAuthUser === false && external_account === null',
                    ngRequired: "$state.match('add')",
                    labelNGClass: "{'prepend-asterisk' : $state.matches('add')}",
                    ngChange: "clearPWConfirm('password_confirm')",
                    autocomplete: false,
                    chkPass: true,
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                password_confirm: {
                    label: i18n._('Confirm Password'),
                    type: 'sensitive',
                    hasShowInputButton: true,
                    ngShow: 'ldap_user == false && socialAuthUser === false && external_account === null',
                    ngRequired: "$state.match('add')",
                    labelNGClass: "{'prepend-asterisk' : $state.matches('add')}",
                    awPassMatch: true,
                    associated: 'password',
                    autocomplete: false,
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                user_type: {
                    label: i18n._('User Type'),
                    type: 'select',
                    ngOptions: 'item as item.label for item in user_type_options track by item.type',
                    disableChooseOption: true,
                    ngModel: 'user_type',
                    ngShow: 'current_user["is_superuser"]',
                    ngDisabled: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
            },

            buttons: {
                cancel: {
                    ngClick: 'formCancel()',
                    ngShow: '(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                close: {
                    ngClick: 'formCancel()',
                    ngShow: '!(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                },
                save: {
                    ngClick: 'formSave()',
                    ngDisabled: true,
                    ngShow: '(user_obj.summary_fields.user_capabilities.edit || canAdd)'
                }
            },

            related: {
                organizations: {
                    awToolTip: i18n._('Please save before assigning to organizations'),
                    basePath: 'api/v1/users/{{$stateParams.user_id}}/organizations',
                    emptyListText: i18n._('Please add user to an Organization.'),
                    search: {
                        page_size: '10'
                    },
                    dataPlacement: 'top',
                    type: 'collection',
                    title: i18n._('Organizations'),
                    iterator: 'organization',
                    index: false,
                    open: false,

                    actions: {},

                    fields: {
                        name: {
                            key: true,
                            label: i18n._('Name')
                        },
                        description: {
                            label: i18n._('Description')
                        }
                    },
                    //hideOnSuperuser: true // RBAC defunct
                },
                teams: {
                    awToolTip: i18n._('Please save before assigning to teams'),
                    basePath: 'api/v1/users/{{$stateParams.user_id}}/teams',
                    search: {
                        page_size: '10'
                    },
                    dataPlacement: 'top',
                    type: 'collection',
                    title: i18n._('Teams'),
                    iterator: 'team',
                    open: false,
                    index: false,
                    actions: {},
                    emptyListText: i18n._('This user is not a member of any teams'),
                    fields: {
                        name: {
                            key: true,
                            label: i18n._('Name')
                        },
                        description: {
                            label: i18n._('Description')
                        }
                    },
                    //hideOnSuperuser: true // RBAC defunct
                },
                permissions: {
                    basePath: 'api/v1/users/{{$stateParams.user_id}}/roles/',
                    search: {
                        page_size: '10',
                        order_by: 'id'
                    },
                    awToolTip: i18n._('Please save before assigning to organizations'),
                    dataPlacement: 'top',
                    hideSearchAndActions: true,
                    type: 'collection',
                    title: i18n._('Permissions'),
                    iterator: 'permission',
                    open: false,
                    index: false,
                    emptyListText: i18n._('No permissions have been granted'),
                    fields: {
                        name: {
                            label: i18n._('Name'),
                            ngBind: 'permission.summary_fields.resource_name',
                            linkTo: '{{convertApiUrl(permission.related[permission.summary_fields.resource_type])}}',
                            noSort: true
                        },
                        type: {
                            label: i18n._('Type'),
                            ngBind: 'permission.summary_fields.resource_type_display_name',
                            noSort: true
                        },
                        role: {
                            label: i18n._('Role'),
                            ngBind: 'permission.name',
                            noSort: true
                        },
                    },
                    actions: {
                        add: {
                            ngClick: "$state.go('.add')",
                            label: 'Add',
                            awToolTip: i18n._('Grant Permission'),
                            actionClass: 'btn List-buttonSubmit',
                            buttonContent: '+ ' + i18n._('ADD PERMISSIONS'),
                            ngShow: '(!is_superuser && (user_obj.summary_fields.user_capabilities.edit || canAdd))'
                        }
                    },
                    fieldActions: {
                        "delete": {
                            label: i18n._('Remove'),
                            ngClick: 'deletePermissionFromUser(user_id, username, permission.name, permission.summary_fields.resource_name, permission.related.users)',
                            iconClass: 'fa fa-times',
                            awToolTip: i18n._('Dissasociate permission from user'),
                            ngShow: 'permission.summary_fields.user_capabilities.unattach'
                        }
                    },
                    //hideOnSuperuser: true // RBAC defunct
                }
            }

        };}]);
<|endoftext|>


<commit_before>/**
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed 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.
 *
 * @fileoverview Monitoring API demo.
 */

/**
 * The MonitoringApiException class is thrown when there's an API error.
 * @constructor
 */
var MonitoringApiException = function(response) {
  /**
   * JSON response object.
   * @type {Object}
   */
  this.response = response;
};

/**
 * The MonitoringApi class performs authorization and retrieves
 * data from the Monitoring API.
 * @constructor
 */
var MonitoringApi = function() {
  /**
   * User's project ID. Set via the UI.
   * @type {string}
   */
  this.projectId = null;

  /**
   * API name.
   * @type {String}
   * @private
   */
  this.apiName_ = 'cloudmonitoring';

  /**
   * API version.
   * @type {String}
   * @private
   */
  this.apiVersion_ = 'v2beta1';

  /**
   * Google API Key.
   * @type {String}
   * @private
   */
  this.apiKey_ = '<your-api-key>';

  /**
   * Google Client ID.
   * @type {String}
   * @private
   */
  this.clientId_ = '<your-client-id>';

  /**
   * Google API scope.
   * @type {String}
   * @private
   */
  this.scopes_ = 'https://www.googleapis.com/auth/monitoring.readonly';
};

/**
 * Initialize the HTML page and authorization settings.
 * @param {Function} authComplete Function to call when authorization is done.
 */
MonitoringApi.prototype.auth = function(authComplete) {
  gapi.client.setApiKey(this.apiKey_);
  gapi.auth.authorize({
    client_id: this.clientId_,
    scope: this.scopes_,
    immediate: true}, this.handleAuthResult(authComplete));
};

/**
 * Handle the response from Google's authorization server.
 * @param {Function} authComplete Function to call when authorization is done.
 * @return {Function} A function to handle response from Google's authorization
 *     server.
 */
MonitoringApi.prototype.handleAuthResult = function(authComplete) {
  var self = this;

  return function(authResult) {
    if (authResult && authResult.name != 'TypeError') {
      $('#authorize-button').css('visibility', 'hidden');
      authComplete();
    } else {
      $('#authorize-button').css('visibility', '');
      $('#authorize-button').click(function(event) {
        gapi.auth.authorize({
          client_id: self.clientId_,
          scope: self.scopes_,
          immediate: false}, self.handleAuthResult(authComplete));
        return false;
      });
    }
  };
};

/**
 * Make a call to the Monitoring API timeseries.list endpoint. Pass
 * the returned data to the provided callback function.
 * @param {Object} query Query parameters for the call to the API. For example:
 *     {
 *       timespan: '2d',
 *       labels: ['label==value',...]
 *     }
 * @param {function} callback Method to call when API returns.
 */
MonitoringApi.prototype.getData = function(query, callback) {
  var self = this;
  var timeseries = [];

  // Make a copy of the query in case the pageToken needs to be added.
  // We don't want the pageToken added to the query object.
  var localQuery = $.extend({}, query);
  localQuery.youngest = new Date().toISOString();

  var makeCall = function() {
    gapi.client.load(self.apiName_, self.apiVersion_, function() {
      var request = gapi.client.cloudmonitoring.timeseries.list(localQuery);
      request.execute(function(response) {
        if (response.timeseries) {
          $.merge(timeseries, response.timeseries);
          if (response.nextPageToken) {
            $.extend(localQuery, {'pageToken': response.nextPageToken});
            makeCall();
          } else {
            callback(timeseries);
          }
        } else {
          // If there's no timeseries data, there was a problem. Return the
          // response to display in the error message.
          callback(timeseries, response);
        }
      });
    });
  };
  makeCall();
};

/**
 * Make a call to the Monitoring API metricDescriptors.list endpoint.
 * @param {function} callback Method to call when API returns.
 */
MonitoringApi.prototype.getMetrics = function(callback) {
  var self = this;
  gapi.client.load(this.apiName_, this.apiVersion_, function() {
    var request = gapi.client.cloudmonitoring.metricDescriptors.list({
      'project': self.projectId
    });
    request.execute(function(response) {
      callback(response.metrics);
    });
  });
};

/**
 * Make a call to the Monitoring API timeseriesDescriptors.list endpoint.
 * @param {string} metric String metric name (ex:
 *     compute.googleapis.com/instance/disk/read_latencies)
 * @param {function} callback Method to call when API returns.
 */
MonitoringApi.prototype.getDescriptors = function(metric, callback) {
  var self = this;
  gapi.client.load(this.apiName_, this.apiVersion_, function() {
    var request = gapi.client.cloudmonitoring.timeseriesDescriptors.list({
      'metric': metric,
      'project': self.projectId
    });
    request.execute(function(response) {
      callback(response.timeseries);
    });
  });
};
<commit_msg>Improved error messaging, updated for API changes.<commit_after>/**
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed 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.
 *
 * @fileoverview Monitoring API demo.
 */

/**
 * The MonitoringApi class performs authorization and retrieves
 * data from the Monitoring API.
 * @constructor
 */
var MonitoringApi = function() {
  /**
   * User's project ID. Set via the UI.
   * @type {string}
   */
  this.projectId = null;

  /**
   * API name.
   * @type {String}
   * @private
   */
  this.apiName_ = 'cloudmonitoring';

  /**
   * API version.
   * @type {String}
   * @private
   */
  this.apiVersion_ = 'v2beta1';

  /**
   * Google API Key.
   * @type {String}
   * @private
   */
  this.apiKey_ = '<your-api-key>';

  /**
   * Google Client ID.
   * @type {String}
   * @private
   */
  this.clientId_ = '<your-client-id>';

  /**
   * Google API scope.
   * @type {String}
   * @private
   */
  this.scopes_ = 'https://www.googleapis.com/auth/monitoring.readonly';
};

/**
 * Initialize the HTML page and authorization settings.
 * @param {Function} authComplete Function to call when authorization is done.
 */
MonitoringApi.prototype.auth = function(authComplete) {
  gapi.client.setApiKey(this.apiKey_);
  gapi.auth.authorize({
    client_id: this.clientId_,
    scope: this.scopes_,
    immediate: true}, this.handleAuthResult(authComplete));
};

/**
 * Handle the response from Google's authorization server.
 * @param {Function} authComplete Function to call when authorization is done.
 * @return {Function} A function to handle response from Google's authorization
 *     server.
 */
MonitoringApi.prototype.handleAuthResult = function(authComplete) {
  var self = this;

  return function(authResult) {
    if (authResult && authResult.name != 'TypeError') {
      $('#authorize-button').css('visibility', 'hidden');
      authComplete();
    } else {
      $('#authorize-button').css('visibility', '');
      $('#authorize-button').click(function(event) {
        gapi.auth.authorize({
          client_id: self.clientId_,
          scope: self.scopes_,
          immediate: false}, self.handleAuthResult(authComplete));
        return false;
      });
    }
  };
};

/**
 * Make a call to the Monitoring API timeseries.list endpoint. Pass
 * the returned data to the provided callback function.
 * @param {Object} query Query parameters for the call to the API. For example:
 *     {
 *       timespan: '2d',
 *       labels: ['label==value',...]
 *     }
 * @param {function} callback Method to call when API returns.
 */
MonitoringApi.prototype.getData = function(query, callback) {
  var self = this;
  var timeseries = [];

  // Make a copy of the query in case the pageToken needs to be added.
  // We don't want the pageToken added to the query object.
  var localQuery = $.extend({}, query);
  localQuery.youngest = new Date().toISOString();

  var makeCall = function() {
    gapi.client.load(self.apiName_, self.apiVersion_, function() {
      var request = gapi.client.cloudmonitoring.timeseries.list(localQuery);
      request.execute(function(response) {
        if (response.timeseries) {
          $.merge(timeseries, response.timeseries);
          if (response.nextPageToken) {
            $.extend(localQuery, {'pageToken': response.nextPageToken});
            makeCall();
          } else {
            callback(timeseries);
          }
        } else {
          // If there's no timeseries data, there was a problem. Return the
          // response to display in the error message.
          callback(timeseries, response);
        }
      });
    });
  };
  makeCall();
};

/**
 * Make a call to the Monitoring API metricDescriptors.list endpoint.
 * @param {function} callback Method to call when API returns.
 */
MonitoringApi.prototype.getMetrics = function(callback) {
  var self = this;
  gapi.client.load(this.apiName_, this.apiVersion_, function() {
    var request = gapi.client.cloudmonitoring.metricDescriptors.list({
      'project': self.projectId
    });
    request.execute(function(response) {
      callback(response.metrics);
    });
  });
};

/**
 * Make a call to the Monitoring API timeseriesDescriptors.list endpoint.
 * @param {string} metric String metric name (ex:
 *     compute.googleapis.com/instance/disk/read_latencies)
 * @param {function} callback Method to call when API returns.
 */
MonitoringApi.prototype.getDescriptors = function(metric, callback) {
  var self = this;
  gapi.client.load(this.apiName_, this.apiVersion_, function() {
    var request = gapi.client.cloudmonitoring.timeseriesDescriptors.list({
      'metric': metric,
      'project': self.projectId
    });
    request.execute(function(response) {
      callback(response.timeseries);
    });
  });
};
<|endoftext|>