<commit_before>//Lunch Roulette

//TODO, enter locations for restaurants, work on displaying locations,

document.addEventListener("DOMContentLoaded", function(event) {

	var healthyRestaurantsData = [
		{
			"restaurantName":"Chop't",
			"restaurantLocation":"1 New York Plaza New York, NY 10004",
			"phoneNumber":"646-741-9968"
		},
		{
			"restaurantName":"Chipotle",
			"restaurantLocation": "1 New York Plaza New York, NY 10004",
			"phoneNumber": "646-882-3252"
		},
		{
			"restaurantName":"Water Street Deli",
			"restaurantLocation": "130 Water St New York, NY 10005",
			"phoneNumber": "212-785-1320"
		},
		{
			"restaurantName":"Open Kitchen",
			"restaurantLocation": "15 William St, New York, NY 10005",
			"phoneNumber": "212-785-5555"
		},
		{
			"restaurantName":"GuacStar",
			"restaurantLocation": "66 Pearl St, New York, NY 10004",
			"phoneNumber": "212-425-7171"
		}
	]

	var unhealthyRestaurantsData = [
		{
			"restaurantName":"Thai OBAO",
			"restaurantLocation": "38 Water St New York, NY 10004",
			"phoneNumber": "212-361-6311"
		},
		{
			"restaurantName":"Golden Chopsticks",
			"restaurantLocation": "77 Pearl St #3, New York, NY 10004",
			"phoneNumber": "212-825-0314"
		},
		{
			"restaurantName":"Nu Sushi",
			"restaurantLocation": "76 Pearl St New York, NY 10004",
			"phoneNumber":"212-363-1668"
		},
		{
			"restaurantName":"Schnippers",
			"restaurantLocation": "1 New York Plaza New York, NY 10004",
			"phoneNumber": "646-964-5409"
		},
		{
			"restaurantName":"Veronica's Kitchen",
			"restaurantLocation": "Front St & Pine St New York, NY 10005",
			"phoneNumber": "917-848-2465"
		},
		{
			"restaurantName":"Lenny's",
			"restaurantLocation": "32 Water St New York, NY 10004",
			"phoneNumber": "212-785-7500"
		}
	]

	var wednesdayRestaurants = [
		{
			"restaurantName":"Diso Truck",
			"restaurantLocation": "Old Slip Park",
			"phoneNumber": "917-756-4145"
		}
	]

	var choice;
	var shuffledChoices;

	//CONTROLLER
	Array.prototype.pushArray = function() {
	    this.push.apply(this, this.concat.apply([], arguments));
	};

	function initialize() {
		chooseRestaurantList();
		shuffleRestaurants(choice);
		displayResult(shuffledChoices);
	};

	function onClickHandler() {

		var initializeButton = document.getElementById("initialize");
		initializeButton.addEventListener("click", function(event) {
			var existingResult = document.getElementById("result");
			existingResult.innerHTML = "";
			removeListItems();
			initialize();
		});

		var resetButton = document.getElementById("reset");
		resetButton.addEventListener("click", function(event){
			pageReload();
		});

	};

	function pageReload() {
		document.location.reload(true);
	}

	function removeListItems() {
		var parentNode = document.getElementById("display-list");
		while (parentNode.firstChild) {
	    parentNode.removeChild(parentNode.firstChild);
		};
	}

	function acquireDay() {
		var day = new Date();
		//getDay() 0 to 6 => Sunday to Saturday
		var newDay = day.getDay();
		return newDay;
	}

	function healthyConditionalRestaurants () {
		var mergedArray = healthyRestaurantsData;
		return mergedArray;
	}

	function unhealthyConditionalRestaurants() {
		if (acquireDay() == 3) {
			var mergedArray = [];
			mergedArray.pushArray(unhealthyRestaurantsData, wednesdayRestaurants);
		}
		else {
			var mergedArray = unhealthyRestaurantsData;
		}
		return mergedArray;
	};

	function chooseRestaurantList() {
		choice = document.getElementById("selection-box").value;
		if (choice == 1) {
			choice = healthyConditionalRestaurants();
			displayRestaurantList(choice);
		}
		else if( choice == 2) {
			choice = unhealthyConditionalRestaurants();
			displayRestaurantList(choice);
		}
		else {
			alert("That is an incorrect choice, please try again");
		}
		return choice;
	};

	function shuffleRestaurants(data) {
	  var currentIndex = data.length, temporaryValue, randomIndex;

	  while (0 !== currentIndex) {

	    randomIndex = Math.floor(Math.random() * currentIndex);
	    currentIndex -= 1;

	    temporaryValue = data[currentIndex];
	    data[currentIndex] = data[randomIndex];
	    data[randomIndex] = temporaryValue;
	  };

	  shuffledChoices = data;
	  return shuffledChoices;
	};

	//VIEW

	function displayRestaurantList(data) {

		var headline = document.getElementById("headline");
		headline.innerHTML = "This is your restaurant list:";

		for (var i = 0; i < data.length; i++) {
      if ( data[i].hasOwnProperty("restaurantName") ) {
	      var displayList = document.getElementById("display-list");
				var listItem = document.createElement('li');
				displayList.appendChild(listItem);
				document.getElementsByTagName("li")[i].innerHTML = data[i].restaurantName;
       }
    }

	};

	function createHeadline (elementTag, description, dataObj) {
		var headline = document.createElement(elementTag);
		headline.style.fontSize="20px";
		headline.style.textAlign="center";
		headline.innerHTML = description + dataObj;
		document.getElementById("result").appendChild(headline);
	}

	function displayResult(shuffledChoices) {
		var lunchResult = shuffledChoices.pop();
		createHeadline("h2","Your result is: ", lunchResult.restaurantName);
		createHeadline("p","Restaurant location: ", lunchResult.restaurantLocation);
		createHeadline("p","Phone Number: ", lunchResult.phoneNumber);
	};

	onClickHandler();

});
<commit_msg>add restaurants<commit_after>//Lunch Roulette

//TODO, enter locations for restaurants, work on displaying locations,

document.addEventListener("DOMContentLoaded", function(event) {

	var healthyRestaurantsData = [
		{
			"restaurantName":"Chop't",
			"restaurantLocation":"1 New York Plaza New York, NY 10004",
			"phoneNumber":"646-741-9968"
		},
		{
			"restaurantName":"Chipotle",
			"restaurantLocation": "1 New York Plaza New York, NY 10004",
			"phoneNumber": "646-882-3252"
		},
		{
			"restaurantName":"Water Street Deli",
			"restaurantLocation": "130 Water St New York, NY 10005",
			"phoneNumber": "212-785-1320"
		},
		{
			"restaurantName":"Open Kitchen",
			"restaurantLocation": "15 William St, New York, NY 10005",
			"phoneNumber": "212-785-5555"
		},
		{
			"restaurantName":"Nu Sushi",
			"restaurantLocation": "76 Pearl St New York, NY 10004",
			"phoneNumber":"212-363-1668"
		},
		{
			"restaurantName":"GuacStar",
			"restaurantLocation": "66 Pearl St, New York, NY 10004",
			"phoneNumber": "212-425-7171"
		},
		{
			"restaurantName":"Niko Niko",
			"restaurantLocation": "133 John St, New York, NY 10005",
			"phoneNumber": "212-232-0152"
		}

	]

	var unhealthyRestaurantsData = [
		{
			"restaurantName":"Thai OBAO",
			"restaurantLocation": "38 Water St New York, NY 10004",
			"phoneNumber": "212-361-6311"
		},
		{
			"restaurantName":"Golden Chopsticks",
			"restaurantLocation": "77 Pearl St #3, New York, NY 10004",
			"phoneNumber": "212-825-0314"
		},
		{
			"restaurantName":"Schnippers",
			"restaurantLocation": "1 New York Plaza New York, NY 10004",
			"phoneNumber": "646-964-5409"
		},
		{
			"restaurantName":"Veronica's Kitchen",
			"restaurantLocation": "Front St & Pine St New York, NY 10005",
			"phoneNumber": "917-848-2465"
		},
		{
			"restaurantName":"Lenny's",
			"restaurantLocation": "32 Water St New York, NY 10004",
			"phoneNumber": "212-785-7500"
		},
		{
			"restaurantName":"BonChon Chicken",
			"restaurantLocation": "104 John St, New York, NY 10038",
			"phoneNumber": "646-692-4660"
		}

	]

	var wednesdayRestaurants = [
		{
			"restaurantName":"Diso Truck",
			"restaurantLocation": "Old Slip Park",
			"phoneNumber": "917-756-4145"
		}
	]

	var choice;
	var shuffledChoices;

	//CONTROLLER
	Array.prototype.pushArray = function() {
	    this.push.apply(this, this.concat.apply([], arguments));
	};

	function initialize() {
		chooseRestaurantList();
		shuffleRestaurants(choice);
		displayResult(shuffledChoices);
	};

	function onClickHandler() {

		var initializeButton = document.getElementById("initialize");
		initializeButton.addEventListener("click", function(event) {
			var existingResult = document.getElementById("result");
			existingResult.innerHTML = "";
			removeListItems();
			initialize();
		});

		var resetButton = document.getElementById("reset");
		resetButton.addEventListener("click", function(event){
			pageReload();
		});

	};

	function pageReload() {
		document.location.reload(true);
	}

	function removeListItems() {
		var parentNode = document.getElementById("display-list");
		while (parentNode.firstChild) {
	    parentNode.removeChild(parentNode.firstChild);
		};
	}

	function acquireDay() {
		var day = new Date();
		//getDay() 0 to 6 => Sunday to Saturday
		var newDay = day.getDay();
		return newDay;
	}

	function healthyConditionalRestaurants () {
		var mergedArray = healthyRestaurantsData;
		return mergedArray;
	}

	function unhealthyConditionalRestaurants() {
		if (acquireDay() == 3) {
			var mergedArray = [];
			mergedArray.pushArray(unhealthyRestaurantsData, wednesdayRestaurants);
		}
		else {
			var mergedArray = unhealthyRestaurantsData;
		}
		return mergedArray;
	};

	function chooseRestaurantList() {
		choice = document.getElementById("selection-box").value;
		if (choice == 1) {
			choice = healthyConditionalRestaurants();
			displayRestaurantList(choice);
		}
		else if (choice == 2) {
			choice = unhealthyConditionalRestaurants();
			displayRestaurantList(choice);
		}
		else {
			alert("That is an incorrect choice, please try again");
		}
		return choice;
	};

	function shuffleRestaurants(data) {
	  var currentIndex = data.length, temporaryValue, randomIndex;

	  while (0 !== currentIndex) {

	    randomIndex = Math.floor(Math.random() * currentIndex);
	    currentIndex -= 1;

	    temporaryValue = data[currentIndex];
	    data[currentIndex] = data[randomIndex];
	    data[randomIndex] = temporaryValue;
	  };

	  shuffledChoices = data;
	  return shuffledChoices;
	};

	//VIEW

	function displayRestaurantList(data) {

		var headline = document.getElementById("headline");
		headline.innerHTML = "This is your restaurant list:";

		for (var i = 0; i < data.length; i++) {
      if ( data[i].hasOwnProperty("restaurantName") ) {
	      var displayList = document.getElementById("display-list");
				var listItem = document.createElement('li');
				displayList.appendChild(listItem);
				document.getElementsByTagName("li")[i].innerHTML = data[i].restaurantName;
       }
    }

	};

	function createHeadline (elementTag, description, dataObj) {
		var headline = document.createElement(elementTag);
		headline.style.fontSize="20px";
		headline.style.textAlign="center";
		headline.innerHTML = description + dataObj;
		document.getElementById("result").appendChild(headline);
	}

	function displayResult(shuffledChoices) {
		var lunchResult = shuffledChoices.pop();
		createHeadline("h2","Your result is: ", lunchResult.restaurantName);
		createHeadline("p","Restaurant location: ", lunchResult.restaurantLocation);
		createHeadline("p","Phone Number: ", lunchResult.phoneNumber);
	};

	onClickHandler();

});
<|endoftext|>


<commit_before>! function (definition) {
    /* istanbul ignore next */
    if (typeof module === 'object') module.exports = definition()
    else if (typeof window !== 'undefined') window.cadence = definition()
    else if (typeof define === 'function') define(definition)
} (function () {
    var stack = [], push = [].push, token = {}

    function Cadence (cadence, steps, callback) {
        this.finalizers = cadence.finalizers
        this.self = cadence.self
        this.steps = steps
        this.callback = callback
        this.loop = false
    }

    Cadence.prototype.done = function (vargs) {
        if (this.finalizers.length == 0) {
            this.callback.apply(null, vargs)
        } else {
            finalize(this, [], this.callback, vargs)
        }
    }

    function Step (cadence, index, vargs) {
        this.cadence = cadence
        this.results = []
        this.errors = []
        this.called = 0
        this.index = index
        this.sync = true
        this.next = null
        this.vargs = vargs
    }

    Step.prototype.callback = function (result, vargs) {
        var error = vargs.shift()
        if (error == null) {
            result.vargs = vargs
        } else {
            this.errors.push(error)
        }
        if (++this.called === this.results.length) {
            if (this.next == null) {
                this.sync = true
            } else {
                invoke(this.next)
            }
        }
    }

    Step.prototype.createCallback = function () {
        var self = this
        var result = { vargs: [], starter: null }

        self.results.push(result)
        self.sync = false

        return callback

        function callback () {
            var I = arguments.length
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            self.callback(result, vargs)

            return

            // This try/catch will prevent V8 from marking this function of
            // optimization because it will only ever run once.
            /* istanbul ignore next */
            try {} catch(e) {}
        }
    }

    Step.prototype.createCadence = function (vargs) {
        var self = this

        var callback = this.createCallback()

        var result = this.results[this.results.length - 1]

        var cadence = new Cadence(self.cadence, vargs, callback)

        var step = new Step(cadence, -1, [])

        return result.starter = starter

        function starter () {
            var I = arguments.length
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            return self.starter(step, result, vargs)
        }
    }

    Step.prototype.starter = function (step, result, vargs) {
        if (vargs[0] === token) {
            invoke(step)
        } else {
            var count = 0, cadence = step.cadence

            label.loopy = token
            label.loop = false
            label.cadence = cadence
            label.index = cadence.steps.length

            step.repeat = false
            step.cadence.loop = true
            push.apply(step.vargs, vargs)

            async.continue = { loopy: token, repeat: true, loop: false, cadence: cadence }
            async.break = { loopy: token, repeat: false, loop: false, cadence: cadence }

            return label

            function label () {
                return {
                    loopy: token,
                    loop: true,
                    cadence: cadence,
                    repeat: true
                }
            }
        }
    }

    function async () {
        var step = stack[stack.length - 1]
        var I = arguments.length
        if (I) {
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            return step.createCadence(vargs)
        } else {
            return step.createCallback()
        }
    }

    async.__defineGetter__('self', function () {
        return stack[stack.length - 1].cadence.self
    })

    async.continue = { loopy: token, repeat: true, loop: false }
    async.break = { loopy: token, repeat: false, loop: false }

    function call (fn, self, vargs) {
        try {
            var ret = fn.apply(self, vargs)
        } catch (e) {
            return [ ret, e ]
        }
        return [ ret ]
    }

    function rescue (step) {
        if (step.errors.length === 0) {
            invoke(step)
        } else {
            var error = step.errors.shift()

            execute(step.cadence.self, [
                step.catcher,
                function () {
                    var I = arguments.length
                    var vargs = new Array(I)
                    for (var i = 0; i < I; i++) {
                        vargs[i] = arguments[i]
                    }
                    if (vargs[0] !== error) {
                        step.vargs = vargs
                        step.results.length = 0
                    }
                }
            ], [ error, done ])

            function done (error) {
                if (error) {
                    step.cadence.done([ error ])
                } else {
                    rescue(step)
                }
            }
        }
    }

    function invoke (step) {
        for (;;) {
            var vargs, cadence = step.cadence, steps = cadence.steps

            if (step.errors.length) {
                if (step.catcher) {
                    rescue(step)
                } else {
                    cadence.done([ step.errors[0] ])
                }
                break
            }

            if (step.results.length == 0) {
                vargs = step.vargs
                if (vargs[0] && vargs[0].loopy === token) {
                    var label = vargs.shift()
                    if (label.cadence) {
                        cadence = step.cadence = label.cadence
                        steps = cadence.steps
                    }
                    step.index = label.repeat ? -1 : steps.length - 1
                    cadence.loop = label.loop
                }
            } else {
                vargs = []
                for (var i = 0, I = step.results.length; i < I; i++) {
                    var vargs_ = step.results[i].vargs
                    for (var j = 0, J = vargs_.length; j < J; j++) {
                        vargs.push(vargs_[j])
                    }
                }
            }

            step = new Step(step.cadence, step.index + 1, vargs)

            if (step.index == steps.length) {
                if (cadence.loop) {
                    step.index = 0
                } else {
                    if (vargs.length !== 0) {
                        vargs.unshift(null)
                    }
                    cadence.done(vargs)
                    break
                }
            }

            var fn = steps[step.index]

            if (Array.isArray(fn)) {
                if (fn.length === 1) {
                    cadence.finalizers.push({ steps: fn, vargs: vargs })
                    continue
                } else if (fn.length === 2) {
                    step.catcher = fn[1]
                    fn = fn[0]
                } else if (fn.length === 3) {
                    var filter = fn
                    step.catcher = function (error) {
                        if (filter[1].test(error.code || error.message)) {
                            return filter[2](error)
                        } else {
                            throw error
                        }
                    }
                    fn = fn[0]
                } else {
                    step.vargs = [ step.vargs ]
                    continue
                }
            }

            stack.push(step)

            var ret = call(fn, cadence.self, vargs)
                   // ^^^^

            stack.pop()

            if (ret.length === 2) {
                step.errors.push(ret[1])
                step.vargs = vargs
                step.sync = true
            } else {
                for (var i = 0, I = step.results.length; i < I; i++) {
                    var result = step.results[i]
                    if (result.starter) {
                        result.starter(token)
                    }
                }
                step.vargs = [].concat(ret[0] === void(0) ? vargs : ret[0])
            }

            if (!step.sync) {
                step.next = step
                break
            }
        }
    }

    function finalize (cadence, errors, callback, vargs) {
        if (cadence.finalizers.length == 0) {
            if (errors.length === 0) {
                callback.apply(null, vargs)
            } else {
                callback.apply(null, [ errors[0] ])
            }
        } else {
            var finalizer = cadence.finalizers.pop()
            execute(cadence.self, finalizer.steps, finalizer.vargs.concat(done))
        }
        function done (error) {
            if (error) {
                errors.push(error)
            }
            finalize(cadence, errors, callback, vargs)
        }
    }

    function execute (self, steps, vargs) {
        var callback = vargs.pop()

        var cadence = new Cadence({ finalizers: [], self: self }, steps, callback)

        var step = new Step(cadence, -1, vargs)

        // async.self = self

        invoke(step)
    }

    function cadence () {
        var I = arguments.length
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        return _cadence(vargs)
    }

    function _cadence (steps) {
        var f

        // Preserving arity costs next to nothing; the call to `execute` in
        // these functions will be inlined. The airty function itself will never
        // be inlined because it is in a different context than that of our
        // dear user, but it will be compiled.
        switch (steps[0].length) {
        case 0:
            f = function () {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 1:
            f = function (one) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 2:
            f = function (one, two) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 3:
            f = function (one, two, three) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 4:
            f = function (one, two, three, four) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        default:
            // Avert your eyes if you're squeamish.
            var args = []
            for (var i = 0, I = steps[0].length; i < I; i++) {
                args[i] = '_' + i
            }
            var f = (new Function('execute', 'steps', 'async', '                \n\
                return function (' + args.join(',') + ') {                      \n\
                    var I = arguments.length                                    \n\
                    var vargs = new Array(I + 1)                                \n\
                    vargs[0] = async                                            \n\
                    for (var i = 0; i < I; i++) {                               \n\
                        vargs[i + 1] = arguments[i]                             \n\
                    }                                                           \n\
                    execute(this, steps, vargs)                                 \n\
                }                                                               \n\
           '))(execute, steps, async)
        }

        f.toString = function () { return steps[0].toString() }

        f.isCadence = true

        return f
    }

    return cadence
})
<commit_msg>Fix untested `break` and `continue`.<commit_after>! function (definition) {
    /* istanbul ignore next */
    if (typeof module === 'object') module.exports = definition()
    else if (typeof window !== 'undefined') window.cadence = definition()
    else if (typeof define === 'function') define(definition)
} (function () {
    var stack = [], push = [].push, token = {}

    function Cadence (cadence, steps, callback) {
        this.finalizers = cadence.finalizers
        this.self = cadence.self
        this.steps = steps
        this.callback = callback
        this.loop = false
    }

    Cadence.prototype.done = function (vargs) {
        if (this.finalizers.length == 0) {
            this.callback.apply(null, vargs)
        } else {
            finalize(this, [], this.callback, vargs)
        }
    }

    function Step (cadence, index, vargs) {
        this.cadence = cadence
        this.results = []
        this.errors = []
        this.called = 0
        this.index = index
        this.sync = true
        this.next = null
        this.vargs = vargs
    }

    Step.prototype.callback = function (result, vargs) {
        var error = vargs.shift()
        if (error == null) {
            result.vargs = vargs
        } else {
            this.errors.push(error)
        }
        if (++this.called === this.results.length) {
            if (this.next == null) {
                this.sync = true
            } else {
                invoke(this.next)
            }
        }
    }

    Step.prototype.createCallback = function () {
        var self = this
        var result = { vargs: [], starter: null }

        self.results.push(result)
        self.sync = false

        return callback

        function callback () {
            var I = arguments.length
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            self.callback(result, vargs)

            return

            // This try/catch will prevent V8 from marking this function of
            // optimization because it will only ever run once.
            /* istanbul ignore next */
            try {} catch(e) {}
        }
    }

    Step.prototype.createCadence = function (vargs) {
        var self = this

        var callback = this.createCallback()

        var result = this.results[this.results.length - 1]

        var cadence = new Cadence(self.cadence, vargs, callback)

        var step = new Step(cadence, -1, [])

        return result.starter = starter

        function starter () {
            var I = arguments.length
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            return self.starter(step, result, vargs)
        }
    }

    Step.prototype.starter = function (step, result, vargs) {
        if (vargs[0] === token) {
            invoke(step)
        } else {
            var count = 0, cadence = step.cadence

            label.loopy = token
            label.loop = false
            label.cadence = cadence
            label.index = cadence.steps.length

            step.repeat = false
            step.cadence.loop = true
            push.apply(step.vargs, vargs)

            label.continue = { loopy: token, repeat: true, loop: false, cadence: cadence }
            label.break = { loopy: token, repeat: false, loop: false, cadence: cadence }

            return label

            function label () {
                return {
                    loopy: token,
                    loop: true,
                    cadence: cadence,
                    repeat: true
                }
            }
        }
    }

    function async () {
        var step = stack[stack.length - 1]
        var I = arguments.length
        if (I) {
            var vargs = new Array(I)
            for (var i = 0; i < I; i++) {
                vargs[i] = arguments[i]
            }
            return step.createCadence(vargs)
        } else {
            return step.createCallback()
        }
    }

    async.__defineGetter__('self', function () {
        return stack[stack.length - 1].cadence.self
    })

    async.continue = { loopy: token, repeat: false, loop: false }
    async.break = { loopy: token, repeat: false, loop: false }

    function call (fn, self, vargs) {
        try {
            var ret = fn.apply(self, vargs)
        } catch (e) {
            return [ ret, e ]
        }
        return [ ret ]
    }

    function rescue (step) {
        if (step.errors.length === 0) {
            invoke(step)
        } else {
            var error = step.errors.shift()

            execute(step.cadence.self, [
                step.catcher,
                function () {
                    var I = arguments.length
                    var vargs = new Array(I)
                    for (var i = 0; i < I; i++) {
                        vargs[i] = arguments[i]
                    }
                    if (vargs[0] !== error) {
                        step.vargs = vargs
                        step.results.length = 0
                    }
                }
            ], [ error, done ])

            function done (error) {
                if (error) {
                    step.cadence.done([ error ])
                } else {
                    rescue(step)
                }
            }
        }
    }

    function invoke (step) {
        for (;;) {
            var vargs, cadence = step.cadence, steps = cadence.steps

            if (step.errors.length) {
                if (step.catcher) {
                    rescue(step)
                } else {
                    cadence.done([ step.errors[0] ])
                }
                break
            }

            if (step.results.length == 0) {
                vargs = step.vargs
                if (vargs[0] && vargs[0].loopy === token) {
                    var label = vargs.shift()
                    if (label.cadence) {
                        cadence = step.cadence = label.cadence
                        steps = cadence.steps
                    }
                    step.index = label.repeat ? -1 : steps.length - 1
                    cadence.loop = label.loop
                }
            } else {
                vargs = []
                for (var i = 0, I = step.results.length; i < I; i++) {
                    var vargs_ = step.results[i].vargs
                    for (var j = 0, J = vargs_.length; j < J; j++) {
                        vargs.push(vargs_[j])
                    }
                }
            }

            step = new Step(step.cadence, step.index + 1, vargs)

            if (step.index == steps.length) {
                if (cadence.loop) {
                    step.index = 0
                } else {
                    if (vargs.length !== 0) {
                        vargs.unshift(null)
                    }
                    cadence.done(vargs)
                    break
                }
            }

            var fn = steps[step.index]

            if (Array.isArray(fn)) {
                if (fn.length === 1) {
                    cadence.finalizers.push({ steps: fn, vargs: vargs })
                    continue
                } else if (fn.length === 2) {
                    step.catcher = fn[1]
                    fn = fn[0]
                } else if (fn.length === 3) {
                    var filter = fn
                    step.catcher = function (error) {
                        if (filter[1].test(error.code || error.message)) {
                            return filter[2](error)
                        } else {
                            throw error
                        }
                    }
                    fn = fn[0]
                } else {
                    step.vargs = [ step.vargs ]
                    continue
                }
            }

            stack.push(step)

            var ret = call(fn, cadence.self, vargs)
                   // ^^^^

            stack.pop()

            if (ret.length === 2) {
                step.errors.push(ret[1])
                step.vargs = vargs
                step.sync = true
            } else {
                for (var i = 0, I = step.results.length; i < I; i++) {
                    var result = step.results[i]
                    if (result.starter) {
                        result.starter(token)
                    }
                }
                step.vargs = [].concat(ret[0] === void(0) ? vargs : ret[0])
            }

            if (!step.sync) {
                step.next = step
                break
            }
        }
    }

    function finalize (cadence, errors, callback, vargs) {
        if (cadence.finalizers.length == 0) {
            if (errors.length === 0) {
                callback.apply(null, vargs)
            } else {
                callback.apply(null, [ errors[0] ])
            }
        } else {
            var finalizer = cadence.finalizers.pop()
            execute(cadence.self, finalizer.steps, finalizer.vargs.concat(done))
        }
        function done (error) {
            if (error) {
                errors.push(error)
            }
            finalize(cadence, errors, callback, vargs)
        }
    }

    function execute (self, steps, vargs) {
        var callback = vargs.pop()

        var cadence = new Cadence({ finalizers: [], self: self }, steps, callback)

        var step = new Step(cadence, -1, vargs)

        // async.self = self

        invoke(step)
    }

    function cadence () {
        var I = arguments.length
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        return _cadence(vargs)
    }

    function _cadence (steps) {
        var f

        // Preserving arity costs next to nothing; the call to `execute` in
        // these functions will be inlined. The airty function itself will never
        // be inlined because it is in a different context than that of our
        // dear user, but it will be compiled.
        switch (steps[0].length) {
        case 0:
            f = function () {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 1:
            f = function (one) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 2:
            f = function (one, two) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 3:
            f = function (one, two, three) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        case 4:
            f = function (one, two, three, four) {
                var I = arguments.length
                var vargs = new Array(I + 1)
                vargs[0] = async
                for (var i = 0; i < I; i++) {
                    vargs[i + 1] = arguments[i]
                }
                execute(this, steps, vargs)
            }
            break
        default:
            // Avert your eyes if you're squeamish.
            var args = []
            for (var i = 0, I = steps[0].length; i < I; i++) {
                args[i] = '_' + i
            }
            var f = (new Function('execute', 'steps', 'async', '                \n\
                return function (' + args.join(',') + ') {                      \n\
                    var I = arguments.length                                    \n\
                    var vargs = new Array(I + 1)                                \n\
                    vargs[0] = async                                            \n\
                    for (var i = 0; i < I; i++) {                               \n\
                        vargs[i + 1] = arguments[i]                             \n\
                    }                                                           \n\
                    execute(this, steps, vargs)                                 \n\
                }                                                               \n\
           '))(execute, steps, async)
        }

        f.toString = function () { return steps[0].toString() }

        f.isCadence = true

        return f
    }

    return cadence
})
<|endoftext|>


<commit_before>var builder = require('focus').component.builder;
var React = require('react');
var QuickSearch  = require('../../../search/quick-search').component;
var List = require('../../../list/selection').list.component;
var SearchStore = require('focus').store.SearchStore;
var assign = require('object-assign');
var type = require('focus').component.types;
var InfiniteScrollPageMixin = require("../common-mixin/infinite-scroll-page-mixin").mixin;

var searchMixin = {
    mixins: [InfiniteScrollPageMixin],

    /**
     * Tag name.
     */
    displayName: "search-panel",

    /**
     * Component intialization
     */
    componentDidMount: function searchComponentDidMount(){
        this._registerListeners();
    },

    /**
     * Actions before component will unmount.
     * @constructor
     */
    componentWillUnmount: function SearchComponentWillUnmount(){
        this._unRegisterListeners();
    },

    getDefaultProps: function getDefaultProps(){
        return {
            lineComponent: undefined,
            isSelection: false,
            lineOperationList: {},
            idField: "id"
        }
    },

    /**
     * properties validation
     */
    propTypes:{
        lineComponent: type('object'),
        isSelection: type('bool'),
        lineOperationList: type('array'),
        idField: type('string')
    },

    /**
     * Initial state of the list component.
     * @returns {{list: (*|Array)}}
     */
    getInitialState: function(){
        return {
            isAllSelected: false,
            selected: []
        }
    },

    /**
     * Register a listener on the store.
     * @private
     */
    _registerListeners: function registerSearchListeners(){
        if(this.store){
            this.store.addSearchChangeListener(this.onSearchChange);
        }
    },

    /**
     * Unregister a listener on the store.
     * @private
     */
    _unRegisterListeners: function unRegisterSearchListeners(){
        if(this.store){
            this.store.removeSearchChangeListener(this.onSearchChange);
        }
    },

    /**
     * Handler when store emit a change event.
     */
    onSearchChange: function onSearchChange() {
        this.setState(this.getScrollState());

    },

    /**
     * Action on item selection.
     * @param item
     */
    _selectItem: function selectItem(item){
        var index = this.state.selected.indexOf(item);
        if(index){
            this.state.selected.splice(index,index);
        }else{
            this.state.selected.push(item);
        }
    },

    /**
     * Action on line click.
     * @param item
     */
    _lineClick: function lineClick(item){
        if(this.props.onLineClick){
            this.props.onLineClick(item);
        }
    },

    /**
     * Run search action.
     * @param event
     */
    search: function search(event){
        if(event) {
            event.preventDefault();
        }
        var searchValues = this.refs.quickSearch.getValue();
        this.actions.search(
            this.getSearchCriteria(searchValues.scope,  searchValues.query)
        );
    },

    /**
     * return a quickSearchComponent
     */
    quickSearchComponent: function quickSearchComponent(){
        return(
            <QuickSearch handleKeyUp={this.search}
                ref="quickSearch"
                scope={this.props.scope}
                scopes={this.props.scopeList}
            />
        );
    },

    /**
     * return a list component
     */
    listComponent: function listComponent(){
        return(
            <List data={this.state.list}
                ref="list"
                idField={this.props.idField}
                isSelection={this.props.isSelection}
                onSelection={this._selectItem}
                onLineClick={this._lineClick}
                fetchNextPage={this.fetchNextPage}
                hasMoreData={this.state.hasMoreData}
                isLoading={this.state.isLoading}
                operationList={this.props.operationList}
                lineComponent={this.props.lineComponent}
            />
        );
    }

    /**
     * render the searchComponent.
     */
    /*render: function renderSearchComponent(){
        return(
            <div className="search-panel">
                <QuickSearch handleKeyUp={this.search}
                    ref="quickSearch"
                    scope={this.props.scope}
                    scopes={this.props.scopeList}
                />
                <List data={this.state.list}
                    ref="list"
                    idField={this.props.idField}
                    isSelection={this.props.isSelection}
                    onSelection={this._selectItem}
                    onLineClick={this._lineClick}
                    fetchNextPage={this.fetchNextPage}
                    hasMoreData={this.state.hasMoreData}
                    isLoading={this.state.isLoading}
                    operationList={this.props.operationList}
                    lineComponent={this.props.lineComponent}
                />
            </div>
        );
    }*/
};

module.exports = builder(searchMixin,true);<commit_msg>clean code<commit_after>var builder = require('focus').component.builder;
var React = require('react');
var QuickSearch  = require('../../../search/quick-search').component;
var List = require('../../../list/selection').list.component;
var SearchStore = require('focus').store.SearchStore;
var assign = require('object-assign');
var type = require('focus').component.types;
var InfiniteScrollPageMixin = require("../common-mixin/infinite-scroll-page-mixin").mixin;

var searchMixin = {
    mixins: [InfiniteScrollPageMixin],

    /**
     * Tag name.
     */
    displayName: "search-panel",

    /**
     * Component intialization
     */
    componentDidMount: function searchComponentDidMount(){
        this._registerListeners();
    },

    /**
     * Actions before component will unmount.
     * @constructor
     */
    componentWillUnmount: function SearchComponentWillUnmount(){
        this._unRegisterListeners();
    },

    getDefaultProps: function getDefaultProps(){
        return {
            lineComponent: undefined,
            isSelection: false,
            lineOperationList: {},
            idField: "id"
        }
    },

    /**
     * properties validation
     */
    propTypes:{
        lineComponent: type('object'),
        isSelection: type('bool'),
        lineOperationList: type('array'),
        idField: type('string')
    },

    /**
     * Initial state of the list component.
     * @returns {{list: (*|Array)}}
     */
    getInitialState: function(){
        return {
            isAllSelected: false,
            selected: []
        }
    },

    /**
     * Register a listener on the store.
     * @private
     */
    _registerListeners: function registerSearchListeners(){
        if(this.store){
            this.store.addSearchChangeListener(this.onSearchChange);
        }
    },

    /**
     * Unregister a listener on the store.
     * @private
     */
    _unRegisterListeners: function unRegisterSearchListeners(){
        if(this.store){
            this.store.removeSearchChangeListener(this.onSearchChange);
        }
    },

    /**
     * Handler when store emit a change event.
     */
    onSearchChange: function onSearchChange() {
        this.setState(this.getScrollState());

    },

    /**
     * Action on item selection.
     * @param item
     */
    _selectItem: function selectItem(item){
        var index = this.state.selected.indexOf(item);
        if(index){
            this.state.selected.splice(index,index);
        }else{
            this.state.selected.push(item);
        }
    },

    /**
     * Action on line click.
     * @param item
     */
    _lineClick: function lineClick(item){
        if(this.props.onLineClick){
            this.props.onLineClick(item);
        }
    },

    /**
     * Run search action.
     * @param event
     */
    search: function search(event){
        if(event) {
            event.preventDefault();
        }
        var searchValues = this.refs.quickSearch.getValue();
        this.actions.search(
            this.getSearchCriteria(searchValues.scope,  searchValues.query)
        );
    },

    /**
     * return a quickSearchComponent
     */
    quickSearchComponent: function quickSearchComponent(){
        return(
            <QuickSearch handleKeyUp={this.search}
                ref="quickSearch"
                scope={this.props.scope}
                scopes={this.props.scopeList}
            />
        );
    },

    /**
     * return a list component
     */
    listComponent: function listComponent(){
        return(
            <List data={this.state.list}
                ref="list"
                idField={this.props.idField}
                isSelection={this.props.isSelection}
                onSelection={this._selectItem}
                onLineClick={this._lineClick}
                fetchNextPage={this.fetchNextPage}
                hasMoreData={this.state.hasMoreData}
                isLoading={this.state.isLoading}
                operationList={this.props.operationList}
                lineComponent={this.props.lineComponent}
            />
        );
    }
};

module.exports = builder(searchMixin,true);<|endoftext|>


<commit_before>import wd from '../utils/wd.js'
import { StaleElementReference, ElementNotVisible } from '../../../utils/errors.js'
import some from 'lodash/some'
import $ from 'jquery'

let elementId = 0

function getById (id) {
  let el = wd.elements[id]
  if (!el) {
    throw new StaleElementReference()
  }
  return el
}

function getByLocation (x, y) {
  let el = window.elementFromPoint(x, y)
  if (!el) {
    throw new StaleElementReference()
  }
  return el
}

function getVisible (id) {
  let el = getById(id)
  if (isHidden(el)) {
    throw new ElementNotVisible()
  }
  return el
}

function getOrCreate (el) {
  let ret = -1
  some(wd.elements, (v, k) => {
    if (v === el) {
      ret = k
      return true
    }
  })
  return (ret === -1) ? create(el) : ret
}

function isHidden (el) {
  let $el = $(el)
  return ($el.width() + $el.height() < 1)
}

function toString (id) {
  let el = getById(id)
  let classList = el.className
    .split(/\s+/)
    .filter(cls => !!cls)
    .map(cls => '.' + cls)
    .join('')
  let idStr = el.getAttribute('id')
  idStr = idStr ? '#' + idStr : ''
  return el.tagName + classList + idStr + ` (${id})`
}

function create (el) {
  wd.elements[elementId] = el
  return elementId++
}

export default {getVisible, getById, getByLocation, toString, getOrCreate, create, isHidden}
<commit_msg>fix: use :hidden instead of width & height calculate<commit_after>import wd from '../utils/wd.js'
import { StaleElementReference, ElementNotVisible } from '../../../utils/errors.js'
import some from 'lodash/some'
import $ from 'jquery'

let elementId = 0

function getById (id) {
  let el = wd.elements[id]
  if (!el) {
    throw new StaleElementReference()
  }
  return el
}

function getByLocation (x, y) {
  let el = window.elementFromPoint(x, y)
  if (!el) {
    throw new StaleElementReference()
  }
  return el
}

function getVisible (id) {
  let el = getById(id)
  if (isHidden(el)) {
    throw new ElementNotVisible()
  }
  return el
}

function getOrCreate (el) {
  let ret = -1
  some(wd.elements, (v, k) => {
    if (v === el) {
      ret = k
      return true
    }
  })
  return (ret === -1) ? create(el) : ret
}

function isHidden (el) {
  return $(el).is(':hidden')
}

function toString (id) {
  let el = getById(id)
  let classList = el.className
    .split(/\s+/)
    .filter(cls => !!cls)
    .map(cls => '.' + cls)
    .join('')
  let idStr = el.getAttribute('id')
  idStr = idStr ? '#' + idStr : ''
  return el.tagName + classList + idStr + ` (${id})`
}

function create (el) {
  wd.elements[elementId] = el
  return elementId++
}

export default {getVisible, getById, getByLocation, toString, getOrCreate, create, isHidden}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {Button, FormControl, FormGroup }  from 'react-bootstrap'
import api from '../utils/api'
import '../style/CallsignDetails.css'

const callsignAttributeDictionary = {
  callsign: 'Callsign',
  license_status: 'License status',
  effective_date: 'Effective date',
  cancellation_date: 'Cancellation date',
  expired_date: 'Expiration date',
  certifier_first_name: 'Licenseholder first name',
  certifier_mi: 'Licenseholder middle initial',
  certifier_last_name: 'Licenseholder last name',
  certifier_suffix: 'Licenseholder suffix',
  grant_date: 'Grant date',
}

class CallsignDetails extends Component {
  constructor(props) {
    super(props)
    console.log(props)
    this.state = {
      query: props.match.params.callsign,
      isValidCallsign: true,
     }
    this.callsignLookup = this.callsignLookup.bind(this)
    this.handleChange = this.handleChange.bind(this)
    this.runSearch = this.runSearch.bind(this)
  }
  componentWillMount() {
    // Run the search with a fake event (there's probably a better way of doing this)
    if (this.props.match.params.callsign) this.runSearch(new Event('foo'))
  }
  runSearch(e) {
    e.preventDefault()
    const callsignRegex = /^(?=.{4,6}$)^((?:A[A-K])|(?:[WKN][A-Z]?))[0-9][A-Z]{1,3}$/i
    const isValidCallsign = callsignRegex.test(this.state.query)
    console.log('is',this.state.query,'a valid callsign:', isValidCallsign)
    this.setState( {isValidCallsign: isValidCallsign })
    if(isValidCallsign) {
      this.callsignLookup(this.state.query)
      this.props.history.push('/callsign/' + this.state.query)
    }
  }
  callsignLookup(callsign) {
    api.bulkSearch([callsign.toUpperCase()])
    .then( (res) => {
      console.log('callsignLookup received', res)
      this.setState( { res: res })
    })
  }
  handleChange(e){
    this.setState({ query: e.target.value })
  }
  render(){
    return(

        <form className='callsignLookupForm'>
          <FormGroup className='detailSearchForm'>

Callsign:

            <FormControl type='text' className='detailedCallsignInfoInput'
              value={this.state.query} onChange={this.handleChange}
            />
            <Button type='submit' value='search' onClick={this.runSearch}>Lookup</Button>
          </FormGroup>
        </form>
        { !this.state.isValidCallsign &&
Invalid callsign.
}
        {(this.state.hasOwnProperty('res') && this.state.res.length >0 && this.state.isValidCallsign) &&

            {
              Object.entries(this.state.res[0]).map( ([key, value]) => {
                return <CallsignAttribute key={key} shortname={key} fullname={callsignAttributeDictionary[key]} value={value} />
              })
            }

        }
        { (this.state.hasOwnProperty('res') && this.state.res.length == 0 && this.state.isValidCallsign ) &&

No results found.

        }

    )
  }
}

function CallsignAttribute(props) {
  return

{props.fullname}

{props.value}

}

CallsignAttribute.propTypes = {
  shortname: PropTypes.string.isRequired,
  fullname: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
}

export default CallsignDetails
<commit_msg>Disable search button and change label while search is running<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {Button, FormControl, FormGroup }  from 'react-bootstrap'
import api from '../utils/api'
import '../style/CallsignDetails.css'

const callsignAttributeDictionary = {
  callsign: 'Callsign',
  license_status: 'License status',
  effective_date: 'Effective date',
  cancellation_date: 'Cancellation date',
  expired_date: 'Expiration date',
  certifier_first_name: 'Licenseholder first name',
  certifier_mi: 'Licenseholder middle initial',
  certifier_last_name: 'Licenseholder last name',
  certifier_suffix: 'Licenseholder suffix',
  grant_date: 'Grant date',
}

class CallsignDetails extends Component {
  constructor(props) {
    super(props)
    console.log(props)
    this.state = {
      query: props.match.params.callsign,
      isValidCallsign: true,
      searchIsRunning: false,
     }
    this.callsignLookup = this.callsignLookup.bind(this)
    this.handleChange = this.handleChange.bind(this)
    this.runSearch = this.runSearch.bind(this)
  }
  componentWillMount() {
    // Run the search with a fake event (there's probably a better way of doing this)
    if (this.props.match.params.callsign) this.runSearch(new Event('foo'))
  }
  runSearch(e) {
    e.preventDefault()
    const callsignRegex = /^(?=.{4,6}$)^((?:A[A-K])|(?:[WKN][A-Z]?))[0-9][A-Z]{1,3}$/i
    const isValidCallsign = callsignRegex.test(this.state.query)
    console.log('is',this.state.query,'a valid callsign:', isValidCallsign)
    this.setState( {isValidCallsign: isValidCallsign })
    if(isValidCallsign) {
      this.setState( {searchIsRunning: true })
      this.callsignLookup(this.state.query)
      this.props.history.push('/callsign/' + this.state.query)
    }
  }
  callsignLookup(callsign) {
    api.bulkSearch([callsign.toUpperCase()])
    .then( (res) => {
      console.log('callsignLookup received', res)
      this.setState( {
        res: res,
        searchIsRunning: false
      })
    })
  }
  handleChange(e){
    this.setState({ query: e.target.value })
  }
  render(){
    return(

        <form className='callsignLookupForm'>
          <FormGroup className='detailSearchForm'>

Callsign:

            <FormControl type='text' className='detailedCallsignInfoInput'
              value={this.state.query} onChange={this.handleChange}
            />
            <Button disabled={this.state.searchIsRunning} type='submit' value='search' onClick={this.runSearch}>{this.state.searchIsRunning ? 'Searching...' : 'Lookup'}</Button>
          </FormGroup>
        </form>
        { !this.state.isValidCallsign &&
Invalid callsign.
}
        {(this.state.hasOwnProperty('res') && this.state.res.length >0 && this.state.isValidCallsign) &&

            {
              Object.entries(this.state.res[0]).map( ([key, value]) => {
                return <CallsignAttribute key={key} shortname={key} fullname={callsignAttributeDictionary[key]} value={value} />
              })
            }

        }
        { (this.state.hasOwnProperty('res') && this.state.res.length == 0 && this.state.isValidCallsign ) &&

No results found.

        }

    )
  }
}

function CallsignAttribute(props) {
  return

{props.fullname}

{props.value}

}

CallsignAttribute.propTypes = {
  shortname: PropTypes.string.isRequired,
  fullname: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
}

export default CallsignDetails
<|endoftext|>


<commit_before>var AddRantView = Backbone.View.extend({

  events: {
    'submit': 'onSubmit',
    'keyup textarea': 'onChange'
  },

  initialize: function() {
    var text = localStorage.getItem('next-rant');
    if (text) {
      this.$('textarea').val(text);
    }
  },

  onChange: function(evt) {
    var text = (evt.target || {}).value;
    if (text) {
      localStorage.setItem('next-rant', text);
    }
  },

  onSubmit: function(evt) {
    evt.preventDefault();
    var form = evt.target;

    analytics.trackConversion();
    this.collection.create({
      text: form.rant.value
    }, { wait: true });

    form.rant.value = '';
  }

});
<commit_msg>moved event for better demo<commit_after>var AddRantView = Backbone.View.extend({

  events: {
    'submit': 'onSubmit'
  },

  initialize: function() {
    this.$('textarea').on('keyup', this.onChange);
    var text = localStorage.getItem('next-rant');
    if (text) {
      this.$('textarea').val(text);
    }
  },

  onChange: function(evt) {
    var text = (evt.target || {}).value;
    if (text) {
      localStorage.setItem('next-rant', text);
    }
  },

  onSubmit: function(evt) {
    evt.preventDefault();
    var form = evt.target;

    analytics.trackConversion();
    this.collection.create({
      text: form.rant.value
    }, { wait: true });

    form.rant.value = '';
  }

});
<|endoftext|>


<commit_before>var $speeches = null;
var $tags = null;
var $tagButtons = null;
var $resetSearchButton = null;
var $search = null;
var $body = null;
var $leadQuote = null;
var $imgSource = null;
var $refreshQuoteButton = null;
var $noResults = null;
var $speechCount = null;
var $speechTotal = null;
var FEATURED = null;
var featured_position = 0;

var searchIndex = null;

var filterSpeeches = function() {
    $speeches.hide();

    var $visibleSpeeches = $speeches;
    var query = $search.val();
    var tags = $tags.find('.active').first().data('tag');
    var showReset = false;

    if (query) {
        var results = searchIndex.search(query);
        var slugs = _.pluck(results, 'ref');
        var ids = _.map(slugs, function(s) { return '#' + s });

        $visibleSpeeches = $(ids.join(','));

        showReset = true;
    }

    if (tags) {
        $visibleSpeeches = $visibleSpeeches.filter('.tag-' + tags)

        showReset = true;
    }

    if (showReset) {
        $resetSearchButton.show();
    } else {
        $resetSearchButton.hide();
    }

    $visibleSpeeches.show();

    if ($visibleSpeeches.length > 0){
        $noResults.hide();
        $speechCount.html($visibleSpeeches.length);
        $speechCount.parent('p').show();
    } else {
        $noResults.show();
        $speechCount.html(0);
        $speechCount.parent('p').show();
    }
}

var renderLeadQuote = function() {

    // Indexes into the list of featured quotes using the global state
    // of where you are in the list.
    var context = FEATURED[featured_position];
    if (featured_position == (FEATURED.length - 1)) {
        featured_position = 0;
    } else {
        featured_position += 1;
    }

    // Loads the identified quote with some easing animation.
    var html = JST.quote(context);
    var src = context['img_source'];

    $leadQuote.fadeOut('fast', function(){
        $leadQuote.html(html);
        $leadQuote.fadeIn();
    });
}

var onTagButtonClick = function() {
    hasher.setHash($(this).data('tag'));
}

var onResetSearchButtonClick = function() {
    $search.val('');
    hasher.setHash('_');
}

var onRefreshQuoteButtonClick = function() {
    renderLeadQuote();
}

var onHashChanged = function(new_hash, old_hash) {
    if (new_hash === '_') { new_hash = ''; }

    if (new_hash === '') {
        $tagButtons.removeClass('active');
    } else {
        var $this = $('div.tags li a[data-tag="' + new_hash + '"]');
        $tagButtons.not($this).removeClass('active');
        $this.toggleClass('active');

        $.scrollTo('.filters', { duration: 350 });
    }

    filterSpeeches();
};

$(function() {
    $speeches = $('.speeches .speech');
    $tags = $('.tags');
    $tagButtons = $('.tags .btn').not('.reset-tags');
    $resetSearchButton = $('.reset-tags');
    $search = $('#search');
    $body = $('body');
    $refreshQuoteButton = $('#refresh-quote');

    if ($body.hasClass('homepage')){
        $leadQuote = $('#lead-quote');
        $imgSource = $('.img-source');
        $noResults = $('#no-results');
        $speechCount = $('.speech-count');
        $speechTotal = $('.speech-total');

        $tagButtons.on('click', onTagButtonClick);
        $resetSearchButton.on('click', onResetSearchButtonClick);
        $search.on('keyup', filterSpeeches);
        $refreshQuoteButton.on('click', onRefreshQuoteButtonClick);

        hasher.changed.add(onHashChanged);
        hasher.initialized.add(onHashChanged);
        hasher.init();

        // Get the featured speeches.
        FEATURED = _.where(SPEECHES, {'featured': 'y'});

        // Add the initial speech slug to the list.
        FEATURED.push(_.where(SPEECHES, {'slug': APP_CONFIG.INITIAL_SPEECH_SLUG })[0])

        // Set up the search index.
        searchIndex = lunr(function () {
            this.field('name', {boost: 10})
            this.field('mood')
            this.field('school')
            this.field('year')
            this.ref('slug')
        })
        _.each(SPEECHES, function(speech) { searchIndex.add(speech); });

        $speechTotal.html(SPEECHES.length);
    }
});
<commit_msg>Make search work w/ or w/out punctuation. Closes #163.<commit_after>var $speeches = null;
var $tags = null;
var $tagButtons = null;
var $resetSearchButton = null;
var $search = null;
var $body = null;
var $leadQuote = null;
var $imgSource = null;
var $refreshQuoteButton = null;
var $noResults = null;
var $speechCount = null;
var $speechTotal = null;
var FEATURED = null;
var featured_position = 0;

var searchIndex = null;

var filterSpeeches = function() {
    $speeches.hide();

    var $visibleSpeeches = $speeches;
    var query = $search.val();
    var tags = $tags.find('.active').first().data('tag');
    var showReset = false;

    if (query) {
        var results = searchIndex.search(query);
        var slugs = _.pluck(results, 'ref');
        var ids = _.map(slugs, function(s) { return '#' + s });

        $visibleSpeeches = $(ids.join(','));

        showReset = true;
    }

    if (tags) {
        $visibleSpeeches = $visibleSpeeches.filter('.tag-' + tags)

        showReset = true;
    }

    if (showReset) {
        $resetSearchButton.show();
    } else {
        $resetSearchButton.hide();
    }

    $visibleSpeeches.show();

    if ($visibleSpeeches.length > 0){
        $noResults.hide();
        $speechCount.html($visibleSpeeches.length);
        $speechCount.parent('p').show();
    } else {
        $noResults.show();
        $speechCount.html(0);
        $speechCount.parent('p').show();
    }
}

var renderLeadQuote = function() {

    // Indexes into the list of featured quotes using the global state
    // of where you are in the list.
    var context = FEATURED[featured_position];
    if (featured_position == (FEATURED.length - 1)) {
        featured_position = 0;
    } else {
        featured_position += 1;
    }

    // Loads the identified quote with some easing animation.
    var html = JST.quote(context);
    var src = context['img_source'];

    $leadQuote.fadeOut('fast', function(){
        $leadQuote.html(html);
        $leadQuote.fadeIn();
    });
}

var onTagButtonClick = function() {
    hasher.setHash($(this).data('tag'));
}

var onResetSearchButtonClick = function() {
    $search.val('');
    hasher.setHash('_');
}

var onRefreshQuoteButtonClick = function() {
    renderLeadQuote();
}

var onHashChanged = function(new_hash, old_hash) {
    if (new_hash === '_') { new_hash = ''; }

    if (new_hash === '') {
        $tagButtons.removeClass('active');
    } else {
        var $this = $('div.tags li a[data-tag="' + new_hash + '"]');
        $tagButtons.not($this).removeClass('active');
        $this.toggleClass('active');

        $.scrollTo('.filters', { duration: 350 });
    }

    filterSpeeches();
};

$(function() {
    $speeches = $('.speeches .speech');
    $tags = $('.tags');
    $tagButtons = $('.tags .btn').not('.reset-tags');
    $resetSearchButton = $('.reset-tags');
    $search = $('#search');
    $body = $('body');
    $refreshQuoteButton = $('#refresh-quote');

    if ($body.hasClass('homepage')){
        $leadQuote = $('#lead-quote');
        $imgSource = $('.img-source');
        $noResults = $('#no-results');
        $speechCount = $('.speech-count');
        $speechTotal = $('.speech-total');

        $tagButtons.on('click', onTagButtonClick);
        $resetSearchButton.on('click', onResetSearchButtonClick);
        $search.on('keyup', filterSpeeches);
        $refreshQuoteButton.on('click', onRefreshQuoteButtonClick);

        hasher.changed.add(onHashChanged);
        hasher.initialized.add(onHashChanged);
        hasher.init();

        // Get the featured speeches.
        FEATURED = _.where(SPEECHES, {'featured': 'y'});

        // Add the initial speech slug to the list.
        FEATURED.push(_.where(SPEECHES, {'slug': APP_CONFIG.INITIAL_SPEECH_SLUG })[0])

        for (i = 0; i < SPEECHES.length; i++) {
            SPEECHES[i]['simple_name'] = SPEECHES[i]['name'].replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()']/g, '')
            console.log(SPEECHES[i]['simple_name']);
        }

        // Set up the search index.
        searchIndex = lunr(function () {
            this.field('name', {boost: 10})
            this.field('simple_name', {boost: 10})
            this.field('school')
            this.field('year')
            this.ref('slug')
        })
        _.each(SPEECHES, function(speech) { searchIndex.add(speech); });

        $speechTotal.html(SPEECHES.length);
    }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/paper-data-table-dialog-inner';

export default Ember.Component.extend({
	layout,
	tagName: 'md-edit-dialog',
	attributeBindings: ['style'],
	transitionClass: 'ng',
	classNames: ['md-whiteframe-1dp'],
	style: Ember.computed('left','top',function() {
		return "left: " + this.get('left') + "px;top: " + this.get('top') + "px";
	}),
	positionDialog() {
		let size = { width: this.get('element').clientWidth, height: this.get('element').clientHeight };
		let cellBounds = Ember.$('#'+this.get('parent'))[0].getBoundingClientRect();
		let tableBounds = this.$().closest('md-table-container')[0].getBoundingClientRect();

		if (size.width > tableBounds.right - cellBounds.left) {
			this.set('left',tableBounds.right - size.width);
		} else {
			this.set('left',cellBounds.left);
		}

		if (size.height > tableBounds.bottom - cellBounds.top) {
			this.set('top',tableBounds.bottom - size.height);
		} else {
			this.set('top',cellBounds.top + 1);
		}

		this.$().css('min-width',(this.get('row') ? tableBounds.width : cellBounds.width) + 'px');
	},
	didInsertElement() {
		this.positionDialog();
		Ember.$(window).on('resize',this.positionDialog.bind(this));
		Ember.run.scheduleOnce('afterRender',this,function() { this.$('input').first().focus(); });
	},
	willDestroyElement() {
		Ember.$(window).off('resize',this.positionDialog.bind(this));
	}
});
<commit_msg>style fix<commit_after>import Ember from 'ember';
import layout from '../templates/components/paper-data-table-dialog-inner';

export default Ember.Component.extend({
	layout,
	tagName: 'md-edit-dialog',
	attributeBindings: ['style'],
	width: null,
	transitionClass: 'ng',
	classNames: ['md-whiteframe-1dp'],
	style: Ember.computed('left','top','width',function() {
		return `left: ${this.get('left')}px;top: ${this.get('top')}px; min-width: ${this.get('width')}px;`;
	}),
	positionDialog() {
		let size = { width: this.get('element').clientWidth, height: this.get('element').clientHeight };
		let cellBounds = Ember.$('#'+this.get('parent'))[0].getBoundingClientRect();
		let tableBounds = this.$().closest('md-table-container')[0].getBoundingClientRect();

		if (size.width > tableBounds.right - cellBounds.left) {
			this.set('left',tableBounds.right - size.width);
		} else {
			this.set('left',cellBounds.left);
		}

		if (size.height > tableBounds.bottom - cellBounds.top) {
			this.set('top',tableBounds.bottom - size.height);
		} else {
			this.set('top',cellBounds.top + 1);
		}
		this.set('width',(this.get('row') ? tableBounds.width : cellBounds.width));
	},
	didInsertElement() {
		this.positionDialog();
		Ember.$(window).on('resize',this.positionDialog.bind(this));
		Ember.run.scheduleOnce('afterRender',this,function() { this.$('input').first().focus(); });
	},
	willDestroyElement() {
		Ember.$(window).off('resize',this.positionDialog.bind(this));
	}
});
<|endoftext|>


<commit_before>import 'babel-polyfill';
import 'whatwg-fetch';
import { createFetch, base, accept, parseJSON } from 'http-client';
import { forEach, filter, matches } from 'lodash';

let fetchPromise;

const fetchProtosFetch = createFetch(
  accept('application/json'),
  parseJSON()
);

export default function fetchProtos(state) {
  if (fetchPromise) return fetchPromise;

  fetchPromise = Promise.all([
      fetchProtosFetch('/local/proto-bundle').then((localResponse) => {
        handleFileSet(state, localResponse.jsonData);
      })
  ]);

  return fetchPromise;
}

function handleFileSet(state, fileset) {
  state.byFile = state.byFile || {};
  window.state = state;

  forEach(fileset.file, (file) => {
    fileDocs(file);
    state.byFile[file.name] = file;
    let thingName = `${file.package}`;

    mapAllTheThings(state, file, file, thingName, []);
  });
}

function mapAllTheThings(state, file, thing, thingName, path) {
  path = path || [];
  handleMessages(state, file, thing.messageType, thingName, path);
  handleMessages(state, file, thing.nestedType, thingName, path);
  handleServices(state, file, thing.service, thingName, path);
  handleEnums(state, file, thing.enumType, thingName, path);
}

function handleMessages(state, file, messages, thingName, path) {
  let thisPath = path.concat(4);

  state.byMessage = state.byMessage || {};
  forEach(messages, (msg, i) => {
    let thePath = thisPath.concat(i);
    let thisName = `${thingName}.${msg.name}`;
    state.byMessage[thisName] = msg;
    msg.fullName=thisName;
    msg.fileDescriptor = file;
    let docs = pathDocs(thePath, file.sourceCodeInfo.location);
    attachDocs(msg, docs[0]);
    messageDocs(msg, docs, thePath);
    mapAllTheThings(state, file, msg, thisName, thePath);
  });
}

function handleServices(state, file, services, thingName, path) {
  state.byService = state.byService || {};

  let thisPath = path.concat(6);

  forEach(services, (service, i) => {
    let thisName = `${thingName}.${service.name}`;
    let thePath = thisPath.concat(i);
    state.byService[thisName] = service;
    service.fullName=thisName;
    service.fileDescriptor = file;
    let docs = pathDocs(thePath, file.sourceCodeInfo.location)[0];
    attachDocs(service, docs);
    mapAllTheThings(state, file, service, thisName, thePath);
  });
}

function handleEnums(state, file, enums, thingName, path) {
  state.byEnum = state.byEnum || {};
  let thisPath = path.concat(5);

  forEach(enums, (theEnum, i) => {
    let thisName = `${thingName}.${theEnum.name}`;
    let thePath = thisPath.concat(i);
    state.byEnum[thisName] = theEnum;
    theEnum.fullName=thisName;
    theEnum.fileDescriptor = file;
    let docs = pathDocs(thePath, file.sourceCodeInfo.location)[0];
    mapAllTheThings(state, file, theEnum, thisName, thePath);
  });
}

function pathDocs(path, items) {
  let matcher = matches(path);
  return filter(items, (loc) => {
    return matcher(loc.path);
  });
}

function fileDocs(fd) {
  let packageDocs = pathDocs([2], fd.sourceCodeInfo.location);
  let syntaxDocs = pathDocs([12], fd.sourceCodeInfo.location);

  attachDocs(fd, syntaxDocs[0]);
  attachDocs(fd, packageDocs[0]);
}

function attachDocs(thing, docs) {
  if (!docs) return;
  let docString = thing.documentation || '';
  forEach(docs.leadingDetachedComments, (cmt) => {
    docString = `${docString}\n${cmt}`;
  });

  if(docs.leadingComments) {
    docString = `${docString}\n${docs.leadingComments}`;
  }

  forEach(docs.trailingComments, (cmt) => {
    docString = `${docString}\n${cmt}`;
  });

  if(docString) thing.documentation = docString;
}

// locs = local docs
function messageDocs(msg, locs, path) {
  // Each of these numbers come from the file descriptor google protobuf definition.
  // Since enums can have recursive messages which can have recursive enums etc, the location structure is like this:
  // location: [TokenType, TokenIndex].  The token index is simply to support multiple tokens inside of a scope, i.e.
  // message Foo {
  //   message Bar {
  //     enum Baz1 {
  //     }
  //     enum Baz2 {
  //     }
  //   }
  // }
  //
  // The location for Foo is [4, 0]
  // The location for Bar is [4, 0, 3, 0]
  // The location for Baz1 is [4, 0, 3, 0, 4, 0]
  // The location for Baz2 is [4, 0, 3, 0, 4, 1]
  //
  // NB: enums and messages share the same position... need to find out more
  let fieldsPath = path.concat(2);
  let nestedTypePath = path.concat(3);
  let enumTypePath = path.concat(4);
  let oneOfPath = path.concat(8);

  forEach(msg.field, (field, i) => {
    let docs = pathDocs(fieldsPath.concat(i), locs)[0];
    attachDocs(field, docs);
  });

  forEach(msg.nestedType, (nestedMsg, i) => {
    let docs = pathDocs(nestedTypePath.concat(i), locs)[0];
    attachDocs(nestedMsg, docs);
  });

  forEach(msg.enumType, (enumType, i) => {
    let docs = pathDocs(enumTypePath.concat(i), locs)[0];
    attachDocs(enumType, docs);
  });

  forEach(msg.oneofDecl, (oneOf, i) => {
    let docs = pathDocs(oneOfPath.concat(i), locs)[0];
    attachDocs(oneOf, docs);
  });
}

<commit_msg>Whitespace.<commit_after>import 'babel-polyfill';
import 'whatwg-fetch';
import {createFetch, base, accept, parseJSON} from 'http-client';
import {forEach, filter, matches} from 'lodash';

let fetchPromise;

const fetchProtosFetch = createFetch(
    accept('application/json'),
    parseJSON()
);

export default function fetchProtos(state) {
  if (fetchPromise) return fetchPromise;

  fetchPromise = Promise.all([
    fetchProtosFetch('/local/proto-bundle').then((localResponse) => {
      handleFileSet(state, localResponse.jsonData);
    })
  ]);

  return fetchPromise;
}

function handleFileSet(state, fileset) {
  state.byFile = state.byFile || {};
  window.state = state;

  forEach(fileset.file, (file) => {
    fileDocs(file);
    state.byFile[file.name] = file;
    let thingName = `${file.package}`;

    mapAllTheThings(state, file, file, thingName, []);
  });
}

function mapAllTheThings(state, file, thing, thingName, path) {
  path = path || [];
  handleMessages(state, file, thing.messageType, thingName, path);
  handleMessages(state, file, thing.nestedType, thingName, path);
  handleServices(state, file, thing.service, thingName, path);
  handleEnums(state, file, thing.enumType, thingName, path);
}

function handleMessages(state, file, messages, thingName, path) {
  let thisPath = path.concat(4);

  state.byMessage = state.byMessage || {};
  forEach(messages, (msg, i) => {
    let thePath = thisPath.concat(i);
    let thisName = `${thingName}.${msg.name}`;
    state.byMessage[thisName] = msg;
    msg.fullName = thisName;
    msg.fileDescriptor = file;
    let docs = pathDocs(thePath, file.sourceCodeInfo.location);
    attachDocs(msg, docs[0]);
    messageDocs(msg, docs, thePath);
    mapAllTheThings(state, file, msg, thisName, thePath);
  });
}

function handleServices(state, file, services, thingName, path) {
  state.byService = state.byService || {};

  let thisPath = path.concat(6);

  forEach(services, (service, i) => {
    let thisName = `${thingName}.${service.name}`;
    let thePath = thisPath.concat(i);
    state.byService[thisName] = service;
    service.fullName = thisName;
    service.fileDescriptor = file;
    let docs = pathDocs(thePath, file.sourceCodeInfo.location)[0];
    attachDocs(service, docs);
    mapAllTheThings(state, file, service, thisName, thePath);
  });
}

function handleEnums(state, file, enums, thingName, path) {
  state.byEnum = state.byEnum || {};
  let thisPath = path.concat(5);

  forEach(enums, (theEnum, i) => {
    let thisName = `${thingName}.${theEnum.name}`;
    let thePath = thisPath.concat(i);
    state.byEnum[thisName] = theEnum;
    theEnum.fullName = thisName;
    theEnum.fileDescriptor = file;
    let docs = pathDocs(thePath, file.sourceCodeInfo.location)[0];
    mapAllTheThings(state, file, theEnum, thisName, thePath);
  });
}

function pathDocs(path, items) {
  let matcher = matches(path);
  return filter(items, (loc) => {
    return matcher(loc.path);
  });
}

function fileDocs(fd) {
  let packageDocs = pathDocs([2], fd.sourceCodeInfo.location);
  let syntaxDocs = pathDocs([12], fd.sourceCodeInfo.location);

  attachDocs(fd, syntaxDocs[0]);
  attachDocs(fd, packageDocs[0]);
}

function attachDocs(thing, docs) {
  if (!docs) return;
  let docString = thing.documentation || '';
  forEach(docs.leadingDetachedComments, (cmt) => {
    docString = `${docString}\n${cmt}`;
  });

  if (docs.leadingComments) {
    docString = `${docString}\n${docs.leadingComments}`;
  }

  forEach(docs.trailingComments, (cmt) => {
    docString = `${docString}\n${cmt}`;
  });

  if (docString) thing.documentation = docString;
}

// locs = local docs
function messageDocs(msg, locs, path) {
  // Each of these numbers come from the file descriptor google protobuf definition.
  // Since enums can have recursive messages which can have recursive enums etc, the location structure is like this:
  // location: [TokenType, TokenIndex].  The token index is simply to support multiple tokens inside of a scope, i.e.
  // message Foo {
  //   message Bar {
  //     enum Baz1 {
  //     }
  //     enum Baz2 {
  //     }
  //   }
  // }
  //
  // The location for Foo is [4, 0]
  // The location for Bar is [4, 0, 3, 0]
  // The location for Baz1 is [4, 0, 3, 0, 4, 0]
  // The location for Baz2 is [4, 0, 3, 0, 4, 1]
  //
  // NB: enums and messages share the same position... need to find out more
  let fieldsPath = path.concat(2);
  let nestedTypePath = path.concat(3);
  let enumTypePath = path.concat(4);
  let oneOfPath = path.concat(8);

  forEach(msg.field, (field, i) => {
    let docs = pathDocs(fieldsPath.concat(i), locs)[0];
    attachDocs(field, docs);
  });

  forEach(msg.nestedType, (nestedMsg, i) => {
    let docs = pathDocs(nestedTypePath.concat(i), locs)[0];
    attachDocs(nestedMsg, docs);
  });

  forEach(msg.enumType, (enumType, i) => {
    let docs = pathDocs(enumTypePath.concat(i), locs)[0];
    attachDocs(enumType, docs);
  });

  forEach(msg.oneofDecl, (oneOf, i) => {
    let docs = pathDocs(oneOfPath.concat(i), locs)[0];
    attachDocs(oneOf, docs);
  });
}

<|endoftext|>


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

    var EmailBodyView;
    var $ = require('jquery');
    var _ = require('underscore');
    var BaseView = require('oroui/js/app/views/base/view');

    EmailBodyView = BaseView.extend({
        autoRender: true,

        /**
         * @type {string}
         */
        bodyContent: null,

        /**
         * @type {Array.<string>}
         */
        styles: null,

        events: {
            'click .email-extra-body-toggle': 'onEmailExtraBodyToggle'
        },

        listen: {
            'layout:reposition mediator': '_updateHeight'
        },

        /**
         * @inheritDoc
         */
        constructor: function EmailBodyView() {
            EmailBodyView.__super__.constructor.apply(this, arguments);
        },

        /**
         * @inheritDoc
         */
        initialize: function(options) {
            _.extend(this, _.pick(options, ['bodyContent', 'styles']));
            this.$frame = this.$el;
            this.$frame.on('emailShown', _.bind(this._updateHeight, this));
            this.$frame.on('load', this.reattachBody.bind(this));
            this.setElement(this.$el.contents().find('html'));
            EmailBodyView.__super__.initialize.apply(this, arguments);
        },

        /**
         * @inheritDoc
         */
        dispose: function() {
            if (this.disposed) {
                return;
            }
            if (this.$frame) {
                this.$frame.off();
            }
            delete this.$frame;
            EmailBodyView.__super__.dispose.call(this);
        },

        /**
         * @inheritDoc
         */
        render: function() {
            var $content;
            var content = this.bodyContent;
            try {
                $content = $(content);
            } catch (e) {
                // if content can not be processed as HTML, output it as plain text
                content = content.replace(/[&<>]/g, function(c) {
                    return '&#' + c.charCodeAt(0) + ';';
                });
                $content = $('
' + content + '
');
            }
            this.$('body').html($content);
            this._injectStyles();
            this._markEmailExtraBody();
            this._updateHeight();
            return this;
        },

        /**
         * Fixes issue when iframe get empty after DOM-manipulation
         */
        reattachBody: function() {
            this.undelegateEvents();
            this.$frame.contents().find('html').replaceWith(this.$el);
            this.delegateEvents();
        },

        /**
         * Add application styles to the iframe document
         *
         * @protected
         */
        _injectStyles: function() {
            var $head;
            if (!this.styles) {
                return;
            }
            $head = this.$('head');
            _.each(this.styles, function(src) {
                $('<link/>', {rel: 'stylesheet', href: src}).appendTo($head);
            });
        },

        /**
         * Updates height for iFrame element depending on the email content size
         *
         * @protected
         */
        _updateHeight: function() {
            var $frame = this.$frame;
            var $el = this.$el;
            _.delay(function() {
                $frame.height(0);
                $frame.height($el[0].scrollHeight);
            }, 50);
        },

        /**
         * Marks email extra-body part and adds the toggler
         *
         * @protected
         */
        _markEmailExtraBody: function() {
            var $extraBodies = this.$('body>.quote, body>.gmail_extra')
                .not('.email-extra-body')
                .addClass('email-extra-body');
            $('

').insertBefore($extraBodies);
        },

        /**
         * Handles click on email extra-body toggle button
         * @param {jQuery.Event} e
         */
        onEmailExtraBodyToggle: function(e) {
            this.$(e.currentTarget)
                .next()
                .toggleClass('in');
            this._updateHeight();
        }
    });

    return EmailBodyView;
});
<commit_msg>BAP-16698: Incorrect display of HTML email body (#17084)<commit_after>define(function(require) {
    'use strict';

    var EmailBodyView;
    var $ = require('jquery');
    var _ = require('underscore');
    var BaseView = require('oroui/js/app/views/base/view');
    var errorHandler = require('oroui/js/error');

    EmailBodyView = BaseView.extend({
        autoRender: true,

        /**
         * @type {string}
         */
        bodyContent: null,

        /**
         * @type {Array.<string>}
         */
        styles: null,

        events: {
            'click .email-extra-body-toggle': 'onEmailExtraBodyToggle'
        },

        listen: {
            'layout:reposition mediator': '_updateHeight'
        },

        /**
         * @inheritDoc
         */
        constructor: function EmailBodyView() {
            EmailBodyView.__super__.constructor.apply(this, arguments);
        },

        /**
         * @inheritDoc
         */
        initialize: function(options) {
            _.extend(this, _.pick(options, ['bodyContent', 'styles']));
            this.$frame = this.$el;
            this.$frame.on('emailShown', _.bind(this._updateHeight, this));
            this.$frame.on('load', this.reattachBody.bind(this));
            this.setElement(this.$el.contents().find('html'));
            EmailBodyView.__super__.initialize.apply(this, arguments);
        },

        /**
         * @inheritDoc
         */
        dispose: function() {
            if (this.disposed) {
                return;
            }
            if (this.$frame) {
                this.$frame.off();
            }
            delete this.$frame;
            EmailBodyView.__super__.dispose.call(this);
        },

        /**
         * @inheritDoc
         */
        render: function() {
            var $content;
            var content = this.bodyContent;
            try {
                /**
                 * Valid email could not contain a root node after HTML tags strip,
                 * but it is still valid HTML fragment and it should be displayed like an HTML
                 *
                 * Example:
                 * Original email:
                 *
                 *
                 *         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                 *
                 *
                 *         Some Text Some other text
                 *
                 *
                 *
                 * Content after strip:
                 * Some Text Some other text
                 *
                 * This content will not be correctly parsed by JQuery, but should be displayed as an HTML
                 */
                var contentWithRootNode = '
' + content + '
';
                $content = $(contentWithRootNode);
            } catch (e) {
                errorHandler.showErrorInConsole(e);
                // if content can not be processed as HTML, output it as plain text
                content = content.replace(/[&<>]/g, function(c) {
                    return '&#' + c.charCodeAt(0) + ';';
                });
                $content = $('
' + content + '
');
            }
            this.$('body').html($content);
            this._injectStyles();
            this._markEmailExtraBody();
            this._updateHeight();
            return this;
        },

        /**
         * Fixes issue when iframe get empty after DOM-manipulation
         */
        reattachBody: function() {
            this.undelegateEvents();
            this.$frame.contents().find('html').replaceWith(this.$el);
            this.delegateEvents();
        },

        /**
         * Add application styles to the iframe document
         *
         * @protected
         */
        _injectStyles: function() {
            var $head;
            if (!this.styles) {
                return;
            }
            $head = this.$('head');
            _.each(this.styles, function(src) {
                $('<link/>', {rel: 'stylesheet', href: src}).appendTo($head);
            });
        },

        /**
         * Updates height for iFrame element depending on the email content size
         *
         * @protected
         */
        _updateHeight: function() {
            var $frame = this.$frame;
            var $el = this.$el;
            _.delay(function() {
                $frame.height(0);
                $frame.height($el[0].scrollHeight);
            }, 50);
        },

        /**
         * Marks email extra-body part and adds the toggler
         *
         * @protected
         */
        _markEmailExtraBody: function() {
            var $extraBodies = this.$('body>.quote, body>.gmail_extra')
                .not('.email-extra-body')
                .addClass('email-extra-body');
            $('

').insertBefore($extraBodies);
        },

        /**
         * Handles click on email extra-body toggle button
         * @param {jQuery.Event} e
         */
        onEmailExtraBodyToggle: function(e) {
            this.$(e.currentTarget)
                .next()
                .toggleClass('in');
            this._updateHeight();
        }
    });

    return EmailBodyView;
});
<|endoftext|>


<commit_before>// newick tree
// console.log(JSON.stringify(tnt.tree.parse_newick(newick)))
var newick = "";
var tree = tnt.tree();
var parsedObj = tnt.tree.parse_newick(newick);
var newickInput = document.getElementById("userInput").value;
var treeCreated = false;

tree.on("click", function (node)
{
  var root = tree.root();
  //node.sort(function (node, node.parent()) {return 1});
  var tempTree = root.subtree(node.get_all_leaves());
  var nodeParent = node.parent();
  tree.data(tempTree.data());
  //tree.node_display(tree.node_display()
        //.size(10)
        //.fill("cyan"));
    tree.update();
});

function makeTree(newick) {
    document.getElementById("treemaker").innerHTML=""
    tree
        .data(tnt.tree.parse_newick(newick))
        .node_display(tree.node_display()
            .size(10)
            .fill("gray")
            )
        .label (tnt.tree.label.text()
        .fontsize(12)
        .height(50)
            )
        .layout(tnt.tree.layout.vertical()
        .width(300)
        .scale(false)
            );
    tree(document.getElementById("treemaker"));

function makeTree ()
{
if (parsedObj != null)
{
    treeCreated = true;
}
if (treeCreated = false)
{
    console.log("error should be thrown");
}
document.getElementById("treemaker").innerHTML=""
  tree
    .data(parsedObj)
    .node_display(tree.node_display()
        .size(10)
        .fill("gray")
        )
    .label (tnt.tree.label.text()
    .fontsize(12)
    .height(50)
        )
    .layout(tnt.tree.layout.vertical()
    .width(300)
    .scale(false)
        );
tree(document.getElementById("treemaker"));
}

function submitNewick ()
{
  var newick=document.getElementById("userInput").value;
  makeTree(newick);
}

function submitFile() {

    var fileInput = document.getElementById("fileInput")
    console.log(fileInput.files[0])
    var newick = ''

    var file = fileInput.files[0]
    var reader = new FileReader()

    reader.onload = function(e) {
        newick = reader.result
        console.log('dsadsa')
        console.log(newick)
        makeTree(newick);
    }
    reader.readAsText(file);
  newick=document.getElementById("userInput").value;
  parsedObj=tnt.tree.parse_newick(newick);
  makeTree();
}

function submitFile()
{
  var reader=new FileReader ();
  reader.addEventListener("loadend", function() {
   // reader.result contains the contents of blob as a typed array
   document.getElementById("fileInput").innerText = reader.result;
});
  console.log(document.getElementById("fileInput").innerText);
  newick=reader.readAsText(reader.result);
  parsedObj=tnt.tree.parse_newick(newick);
  makeTree();
}

function updateVertical()
{
            tree.layout(tnt.tree.layout.vertical().width(300).scale(false));
            tree.update();
}

function updateRadial()
{
  {
            tree.layout(tnt.tree.layout.radial().width(300).scale(false));
            tree.update();
        }
}<commit_msg>added bracket (why?)<commit_after>// newick tree
// console.log(JSON.stringify(tnt.tree.parse_newick(newick)))
var newick = "";
var tree = tnt.tree();
var parsedObj = tnt.tree.parse_newick(newick);
var newickInput = document.getElementById("userInput").value;
var treeCreated = false;

tree.on("click", function (node)
{
  var root = tree.root();
  //node.sort(function (node, node.parent()) {return 1});
  var tempTree = root.subtree(node.get_all_leaves());
  var nodeParent = node.parent();
  tree.data(tempTree.data());
  //tree.node_display(tree.node_display()
        //.size(10)
        //.fill("cyan"));
    tree.update();
});

function makeTree(newick) {
    document.getElementById("treemaker").innerHTML=""
    tree
        .data(tnt.tree.parse_newick(newick))
        .node_display(tree.node_display()
            .size(10)
            .fill("gray")
            )
        .label (tnt.tree.label.text()
        .fontsize(12)
        .height(50)
            )
        .layout(tnt.tree.layout.vertical()
        .width(300)
        .scale(false)
            );
    tree(document.getElementById("treemaker"));

function makeTree ()
{
if (parsedObj != null)
{
    treeCreated = true;
}
if (treeCreated = false)
{
    console.log("error should be thrown");
}
document.getElementById("treemaker").innerHTML=""
  tree
    .data(parsedObj)
    .node_display(tree.node_display()
        .size(10)
        .fill("gray")
        )
    .label (tnt.tree.label.text()
    .fontsize(12)
    .height(50)
        )
    .layout(tnt.tree.layout.vertical()
    .width(300)
    .scale(false)
        );
tree(document.getElementById("treemaker"));
}

function submitNewick ()
{
  var newick=document.getElementById("userInput").value;
  makeTree(newick);
}

function submitFile() {

    var fileInput = document.getElementById("fileInput")
    console.log(fileInput.files[0])
    var newick = ''

    var file = fileInput.files[0]
    var reader = new FileReader()

    reader.onload = function(e) {
        newick = reader.result
        console.log('dsadsa')
        console.log(newick)
        makeTree(newick);
    }
    reader.readAsText(file);
  newick=document.getElementById("userInput").value;
  parsedObj=tnt.tree.parse_newick(newick);
  makeTree();
}

function submitFile()
{
  var reader=new FileReader ();
  reader.addEventListener("loadend", function() {
   // reader.result contains the contents of blob as a typed array
   document.getElementById("fileInput").innerText = reader.result;
});
  console.log(document.getElementById("fileInput").innerText);
  newick=reader.readAsText(reader.result);
  parsedObj=tnt.tree.parse_newick(newick);
  makeTree();
}

function updateVertical()
{
            tree.layout(tnt.tree.layout.vertical().width(300).scale(false));
            tree.update();
}

function updateRadial()
{
  {
            tree.layout(tnt.tree.layout.radial().width(300).scale(false));
            tree.update();
        }
}
}<|endoftext|>


<commit_before>// Given two strings, write a method to decide if one is a permutation of the other.

const SPACE_PATTERN = /\s+/g;

const _isString = (content) => typeof content === 'string';

const _isValidInput = (...values) => {
  let isValid = false;

  if (values.every(_isString)) {
    const valuesWithoutSpaces = values.map((value) => value.replace(SPACE_PATTERN, ''));

    // after stripping down spaces, we check if we still have valid strings.
    isValid = valuesWithoutSpaces.every((value) => value.length);
  }

  return isValid;
};
// in this case normalize means, that we would count the letters in every word, so we can compare them letter on.

const _normalize = (word) => (
  word.reduce((memo, char) => {
    let additive = 1;

    if (char in memo) {
      additive += memo[char];
    }

    // we normalize every string to an object counting every letter used.
    return {...memo, [char]: additive};
  }, {})
);

const isaPermutation = (original = '', permutation = '') => {
// we are gonna define, for the sake of the excercise that an empty string is not a permutation of itself :P
// we are not gonna consider spaces
  if (!_isValidInput(original, permutation)) {
    throw new Error('invalid input, please try to provide 2 valid strings');
  }

  // Quick exist cases.
  // different length.
  // same string
  if (original === permutation || original.length !== permutation.length ) {
    return false;
  }

  const values = [original, permutation].map((value) => (
    value.replace(SPACE_PATTERN, '').split('')
  ));

  const [originalToObj, permutationtoObj] = values.reduce((valuesToHashes, value) => {
    const hash = _normalize(value);

    // we return both words as normalized objects
    return [...valuesToHashes, hash];
  }, []);

  // we compare both objects. for an exact match.
  return Object.keys(originalToObj).every((key) => originalToObj[key] === permutationtoObj[key]);
};

export default isaPermutation;
<commit_msg>a bit of simplification for is a permutation<commit_after>// Given two strings, write a method to decide if one is a permutation of the other.

const SPACE_PATTERN = /\s+/g;

const _isString = (content) => typeof content === 'string';

const _isValidInput = (...values) => {
  let isValid = false;

  if (values.every(_isString)) {
    const valuesWithoutSpaces = values.map((value) => value.replace(SPACE_PATTERN, ''));

    // after stripping down spaces, we check if we still have valid strings.
    isValid = valuesWithoutSpaces.every((value) => value.length);
  }

  return isValid;
};
// in this case normalize means, that we would count the letters in every word, so we can compare them letter on.

const _normalize = (word) => (
  word.reduce((memo, char) => {
    let additive = 1;

    if (char in memo) {
      additive += memo[char];
    }

    // we normalize every string to an object counting every letter used.
    return {...memo, [char]: additive};
  }, {})
);

const isaPermutation = (original = '', permutation = '') => {
// we are gonna define, for the sake of the excercise that an empty string is not a permutation of itself :P
// we are not gonna consider spaces
  if (!_isValidInput(original, permutation)) {
    throw new Error('invalid input, please try to provide 2 valid strings');
  }

  // Quick exit cases.
  // different length.
  // same string
  if (original === permutation || original.length !== permutation.length ) {
    return false;
  }

  const values = [original, permutation].map((value) => (
    value.replace(SPACE_PATTERN, '').split('')
  ));

  const [normalizedOriginal, normalizedPermutation] = values.map(_normalize);

  // we compare both objects. for an exact match.
  return Object.keys(normalizedOriginal).every((key) => normalizedOriginal[key] === normalizedPermutation[key]);
};

export default isaPermutation;
<|endoftext|>