<commit_before>$(function() {
    "use strict";

    var opt = {
        'row': 1,
        'noedit': false,
        'nomask': false,
        'memory': null,
        'export': false,
        'data': null
    };

    var current_row = 0;
    var mouse_tracking;
    var touch_tracking = [];

    // http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript
    function is_touch_device() {
        return !!('ontouchstart' in window) // works on most browsers
            || !!('onmsgesturechange' in window); // works on ie10
    }

    function toggle_panel_color(panel) {
        if ($(panel).hasClass("black") || $(panel).hasClass("white")) {
            $(panel).toggleClass("black white");
        }
        else {
            $(panel).addClass("white invisible-text");
        }
        localStorage['resume_data'] = JSON.stringify({ 'row': current_row, 'data': get_data() });
    }

    function unmagnify_row(i, duration, delay) {
        duration /= 1000;
        delay /= 1000;
        var row = $('#row' + i);
        row.css({
            'transition-duration': '0.001s, ' + duration + 's, ' + duration + 's, ' + duration + 's, ' + duration + 's',
            'transition-delay': delay + 's'
        });
        row.removeClass('magnified');
    }

    function magnify_row(i, duration, delay) {
        duration /= 1000;
        delay /= 1000;
        var row = $('#row' + i);
        row.css({
            'transition-duration': '0.001s, ' + duration + 's, ' + duration + 's, ' + duration + 's, ' + duration + 's',
            'transition-delay': delay + 's'
        });
        row.addClass('magnified');
    }

    function move_focus(i) {
        var row = $('#row' + i);

        var unmasked_top = row.position().top;
        var unmasked_bottom = unmasked_top + row.outerHeight();

        var upper_mask = $('#upper-mask');
        var lower_mask = $('#lower-mask');
        upper_mask.css('transform', 'translate3d(0px, ' + (unmasked_top - upper_mask.outerHeight()) + 'px, 0px)');
        lower_mask.css('transform', 'translate3d(0px, ' + unmasked_bottom + 'px, 0px)');
    }

    function move_cursor_button(i) {
        var row = $('#row' + i);

        var unmasked_top = row.position().top;
        var unmasked_bottom = unmasked_top + row.outerHeight();

        var scaled_top = unmasked_top - 0.3 * 40 / 2;
        var scaled_bottom = unmasked_bottom + 0.3 * 40 / 2;
        var scaled_left = -0.3 * row.outerWidth() / 2;

        var space = 10;

        var prev_button = $('#prev-button');
        var next_button = $('#next-button');
        prev_button.css('transform',
            'translate3d(' +
                (scaled_left - 1.3 * 60 / 2 - prev_button.outerWidth() / 2) + 'px, ' +
                (scaled_top - 40 / 2 - space) + 'px, ' +
                '0) ' +
            'rotate(45deg)');
        next_button.css('transform',
            'translate3d(' +
                (scaled_left - 1.3 * 60 / 2 - next_button.outerWidth() / 2) + 'px, ' +
                (scaled_bottom - 40 / 2 + space) + 'px, ' +
                '0) ' +
            'rotate(45deg)'
        );
    }

    function initialize_mask_transformations() {
        var board_height = $('#board').outerHeight();

        $('#upper-mask').css('transform', 'translate3d(0px, ' + (-board_height) + 'px, 0px)');
        $('#lower-mask').css('transform', 'translate3d(0px, ' + board_height + 'px, 0px)');
    }

    function select_row(i) {
        unmagnify_row(current_row, 400, 0);
        current_row = i;
        move_focus(current_row);
        move_cursor_button(current_row);
        magnify_row(current_row, 400, 400);
        localStorage['resume_data'] = JSON.stringify({ 'row': current_row, 'data': get_data() });
    }

    function on_panel_mousedown(e) {
        mouse_tracking = { target: this };
        toggle_panel_color(this);
    }

    function on_panel_mousemove(e) {
        if (mouse_tracking && mouse_tracking.target !== this) {
            toggle_panel_color(this);
            mouse_tracking.target = this;
        }
    }

    function on_panel_mouseup(e) {
        mouse_tracking = null;
    }

    function on_panel_touchstart(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            var target = document.elementFromPoint(t.clientX, t.clientY);
            if ($(target).hasClass('panel')) {
                touch_tracking[t.identifier] = { target: target };
                toggle_panel_color(target);
            }
        });
    }

    function on_panel_touchmove(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            var target = document.elementFromPoint(t.clientX, t.clientY);
            if ($(target).hasClass('panel')) {
                if (touch_tracking[t.identifier] && touch_tracking[t.identifier].target !== target) {
                    toggle_panel_color(target);
                    touch_tracking[t.identifier].target = target;
                }
            }
        });
    }

    function on_panel_touchend(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            touch_tracking[t.identifier] = null;
        });
    }

    function change_query_string(qs, kvs) {
        $.each(kvs, function(key, value) {
            var re = new RegExp('([?&])' + key + '=[^&]+');
            if (qs.match(re)) {
                // The key is already used.
                qs = qs.replace(re, '$1' + key + '=' + value);
            }
            else {
                // The key isn't used.
                if (qs.match(/[?&]$/)) {
                    qs += key + '=' + value;
                }
                else if (qs.length > 0) {
                    qs += '&' + key + '=' + value;
                }
                else {
                    qs += '?' + key + '=' + value;
                }
            }
        });
        return qs;
    }

    function get_data() {
        var data = "";
        for (var i = 1; i <= 16; ++i) {
            for (var j = 1; j <= 16; ++j) {
                var panel = $('#panel' + i + '-' + j);

                if (panel.hasClass('white')) {
                    data += '0';
                }
                else if (panel.hasClass('black')) {
                    data += '1';
                }
                else {
                    data += '.';
                }
            }
        }
        return data;
    }

    function set_data(data) {
        for (var i = 1; i <= 16; ++i) {
            for (var j = 1; j <= 16; ++j) {
                var panel = $('#panel' + i + '-' + j);

                var k = 16 * (i - 1) + (j - 1);
                if (data[k] === '0') {
                    panel.addClass("white invisible-text");
                    panel.removeClass("black");
                }
                else if (data[k] === '1') {
                    panel.addClass("black invisible-text");
                    panel.removeClass("white");
                }
                else {
                    panel.removeClass("white black invisible-text");
                }
            }
        }
    }

    function export_data() {
        var loc = window.location;
        loc.search = change_query_string(loc.search, { 'data': get_data() });
    }

    // process options
    $.each(window.location.search.slice(1).split("&"), function(_, param) {
        var kv = param.split("=");

        switch (kv[0]) {
        case "row":
            opt.row = parseInt(kv[1]);
            break;
        case "noedit":
            opt.noedit = true;
            break;
        case "nomask":
            opt.nomask = true;
            break;
        case "memory":
            switch (kv[1]) {
            case 'save':
                opt.memory = 'save';
                break;
            case 'load':
                opt.memory = 'load';
                break;
            case 'clear':
                opt.memory = 'clear';
                break;
            }
            break;
        case "export":
            opt['export'] = true;
            break;
        case "data":
            opt.data = kv[1];
            break;
        }
    });

    // create the board
    for (var i = 1; i <= 16; ++i) {
        var row = $('

');
        for (var j = 1; j <= 16; ++j) {
            var cell = $('

');
            var panel = $('
?
');
            panel.appendTo(cell);
            cell.appendTo(row);
        }
        row.appendTo('#board');
        var num_str = (i < 10 ? '0' : '') + i;
        $('').appendTo('#board');
    }

    if (opt.data !== null) {
        set_data(opt.data);
    }
    else if (typeof localStorage['resume_data'] !== 'undefined') {
        set_data(JSON.parse(localStorage['resume_data']).data);
    }

    if (opt['export']) {
        $('#export-button').css('display', 'block');
    }

    if (opt.nomask) {
        $('.mask').css('display', 'none');
        $('#prev-button, #next-button').css('display', 'none');
    }
    else {
        // masks
        initialize_mask_transformations();

        // initial focus
        if (opt.data !== null) {
            current_row = opt.row;
        }
        else if (typeof localStorage['resume_data'] !== 'undefined') {
            current_row = JSON.parse(localStorage['resume_data']).row;
        }
        else {
            current_row = opt.row;
        }
        move_focus(current_row, 400, 0);
        move_cursor_button(current_row, 400, 400);
        magnify_row(current_row, 400, 400);
    }

    // memory
    switch (opt.memory) {
    case 'load':
        $('#load-panel').css('display', 'block');
        $('.load-button').on('click', function() {
            var n = parseInt($(this).attr("id").slice('load-button'.length));
            set_data(localStorage[n] || '');
        });
        break;
    case 'save':
        $('#save-panel').css('display', 'block');
        $('.save-button').on('click', function() {
            var n = parseInt($(this).attr("id").slice('save-button'.length));
            localStorage[n] = get_data();
        });
        break;
    case 'clear':
        localStorage.clear();
        break;
    }

    // events
    if (is_touch_device()) {
        // disable the overscroll effect on touch-capable environments.
        // http://www.html5rocks.com/en/mobile/touch/
        // http://stackoverflow.com/questions/2890361/disable-scrolling-in-an-iphone-web-application
        $(document).on('touchmove', function(e) {
            e.preventDefault();
        });

        if (!opt.nomask) {
            $('#prev-button').on('touchstart', function() {
                if (current_row > 1) {
                    select_row(current_row - 1);
                }
            });
            $('#next-button').on('touchstart', function() {
                if (current_row < 16) {
                    select_row(current_row + 1);
                }
            });
        }

        if (!opt.noedit) {
            $(".panel").each(function() {
                $(this).on('touchstart', on_panel_touchstart);
                $(this).on('touchmove', on_panel_touchmove);
                $(this).on('touchend', on_panel_touchend);
            });
        }
    }
    else {
        if (!opt.nomask) {
            $('#prev-button').on('click', function() {
                if (current_row > 1) {
                    select_row(current_row - 1);
                }
            });
            $('#next-button').on('click', function() {
                if (current_row < 16) {
                    select_row(current_row + 1);
                }
            });
        }

        if (!opt.noedit) {
            $(".panel").each(function() {
                $(this).on('mousedown', on_panel_mousedown);
                $(this).on('mousemove', on_panel_mousemove);
                $(this).on('mouseup', on_panel_mouseup);
            });
        }
    }

    if (opt['export']) {
        $('#export-button').on('click', function() {
            export_data();
        });
    }
});
<commit_msg>Fix function definitions that come after uses of them.<commit_after>$(function() {
    "use strict";

    var opt = {
        'row': 1,
        'noedit': false,
        'nomask': false,
        'memory': null,
        'export': false,
        'data': null
    };

    var current_row = 0;
    var mouse_tracking;
    var touch_tracking = [];

    // http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript
    function is_touch_device() {
        return !!('ontouchstart' in window) // works on most browsers
            || !!('onmsgesturechange' in window); // works on ie10
    }

    function get_data() {
        var data = "";
        for (var i = 1; i <= 16; ++i) {
            for (var j = 1; j <= 16; ++j) {
                var panel = $('#panel' + i + '-' + j);

                if (panel.hasClass('white')) {
                    data += '0';
                }
                else if (panel.hasClass('black')) {
                    data += '1';
                }
                else {
                    data += '.';
                }
            }
        }
        return data;
    }

    function set_data(data) {
        for (var i = 1; i <= 16; ++i) {
            for (var j = 1; j <= 16; ++j) {
                var panel = $('#panel' + i + '-' + j);

                var k = 16 * (i - 1) + (j - 1);
                if (data[k] === '0') {
                    panel.addClass("white invisible-text");
                    panel.removeClass("black");
                }
                else if (data[k] === '1') {
                    panel.addClass("black invisible-text");
                    panel.removeClass("white");
                }
                else {
                    panel.removeClass("white black invisible-text");
                }
            }
        }
    }

    function toggle_panel_color(panel) {
        if ($(panel).hasClass("black") || $(panel).hasClass("white")) {
            $(panel).toggleClass("black white");
        }
        else {
            $(panel).addClass("white invisible-text");
        }
        localStorage['resume_data'] = JSON.stringify({ 'row': current_row, 'data': get_data() });
    }

    function unmagnify_row(i, duration, delay) {
        duration /= 1000;
        delay /= 1000;
        var row = $('#row' + i);
        row.css({
            'transition-duration': '0.001s, ' + duration + 's, ' + duration + 's, ' + duration + 's, ' + duration + 's',
            'transition-delay': delay + 's'
        });
        row.removeClass('magnified');
    }

    function magnify_row(i, duration, delay) {
        duration /= 1000;
        delay /= 1000;
        var row = $('#row' + i);
        row.css({
            'transition-duration': '0.001s, ' + duration + 's, ' + duration + 's, ' + duration + 's, ' + duration + 's',
            'transition-delay': delay + 's'
        });
        row.addClass('magnified');
    }

    function move_focus(i) {
        var row = $('#row' + i);

        var unmasked_top = row.position().top;
        var unmasked_bottom = unmasked_top + row.outerHeight();

        var upper_mask = $('#upper-mask');
        var lower_mask = $('#lower-mask');
        upper_mask.css('transform', 'translate3d(0px, ' + (unmasked_top - upper_mask.outerHeight()) + 'px, 0px)');
        lower_mask.css('transform', 'translate3d(0px, ' + unmasked_bottom + 'px, 0px)');
    }

    function move_cursor_button(i) {
        var row = $('#row' + i);

        var unmasked_top = row.position().top;
        var unmasked_bottom = unmasked_top + row.outerHeight();

        var scaled_top = unmasked_top - 0.3 * 40 / 2;
        var scaled_bottom = unmasked_bottom + 0.3 * 40 / 2;
        var scaled_left = -0.3 * row.outerWidth() / 2;

        var space = 10;

        var prev_button = $('#prev-button');
        var next_button = $('#next-button');
        prev_button.css('transform',
            'translate3d(' +
                (scaled_left - 1.3 * 60 / 2 - prev_button.outerWidth() / 2) + 'px, ' +
                (scaled_top - 40 / 2 - space) + 'px, ' +
                '0) ' +
            'rotate(45deg)');
        next_button.css('transform',
            'translate3d(' +
                (scaled_left - 1.3 * 60 / 2 - next_button.outerWidth() / 2) + 'px, ' +
                (scaled_bottom - 40 / 2 + space) + 'px, ' +
                '0) ' +
            'rotate(45deg)'
        );
    }

    function initialize_mask_transformations() {
        var board_height = $('#board').outerHeight();

        $('#upper-mask').css('transform', 'translate3d(0px, ' + (-board_height) + 'px, 0px)');
        $('#lower-mask').css('transform', 'translate3d(0px, ' + board_height + 'px, 0px)');
    }

    function select_row(i) {
        unmagnify_row(current_row, 400, 0);
        current_row = i;
        move_focus(current_row);
        move_cursor_button(current_row);
        magnify_row(current_row, 400, 400);
        localStorage['resume_data'] = JSON.stringify({ 'row': current_row, 'data': get_data() });
    }

    function on_panel_mousedown(e) {
        mouse_tracking = { target: this };
        toggle_panel_color(this);
    }

    function on_panel_mousemove(e) {
        if (mouse_tracking && mouse_tracking.target !== this) {
            toggle_panel_color(this);
            mouse_tracking.target = this;
        }
    }

    function on_panel_mouseup(e) {
        mouse_tracking = null;
    }

    function on_panel_touchstart(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            var target = document.elementFromPoint(t.clientX, t.clientY);
            if ($(target).hasClass('panel')) {
                touch_tracking[t.identifier] = { target: target };
                toggle_panel_color(target);
            }
        });
    }

    function on_panel_touchmove(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            var target = document.elementFromPoint(t.clientX, t.clientY);
            if ($(target).hasClass('panel')) {
                if (touch_tracking[t.identifier] && touch_tracking[t.identifier].target !== target) {
                    toggle_panel_color(target);
                    touch_tracking[t.identifier].target = target;
                }
            }
        });
    }

    function on_panel_touchend(e) {
        $.each(e.originalEvent.changedTouches, function(_, t) {
            touch_tracking[t.identifier] = null;
        });
    }

    function change_query_string(qs, kvs) {
        $.each(kvs, function(key, value) {
            var re = new RegExp('([?&])' + key + '=[^&]+');
            if (qs.match(re)) {
                // The key is already used.
                qs = qs.replace(re, '$1' + key + '=' + value);
            }
            else {
                // The key isn't used.
                if (qs.match(/[?&]$/)) {
                    qs += key + '=' + value;
                }
                else if (qs.length > 0) {
                    qs += '&' + key + '=' + value;
                }
                else {
                    qs += '?' + key + '=' + value;
                }
            }
        });
        return qs;
    }

    function export_data() {
        var loc = window.location;
        loc.search = change_query_string(loc.search, { 'data': get_data() });
    }

    // process options
    $.each(window.location.search.slice(1).split("&"), function(_, param) {
        var kv = param.split("=");

        switch (kv[0]) {
        case "row":
            opt.row = parseInt(kv[1]);
            break;
        case "noedit":
            opt.noedit = true;
            break;
        case "nomask":
            opt.nomask = true;
            break;
        case "memory":
            switch (kv[1]) {
            case 'save':
                opt.memory = 'save';
                break;
            case 'load':
                opt.memory = 'load';
                break;
            case 'clear':
                opt.memory = 'clear';
                break;
            }
            break;
        case "export":
            opt['export'] = true;
            break;
        case "data":
            opt.data = kv[1];
            break;
        }
    });

    // create the board
    for (var i = 1; i <= 16; ++i) {
        var row = $('

');
        for (var j = 1; j <= 16; ++j) {
            var cell = $('

');
            var panel = $('
?
');
            panel.appendTo(cell);
            cell.appendTo(row);
        }
        row.appendTo('#board');
        var num_str = (i < 10 ? '0' : '') + i;
        $('').appendTo('#board');
    }

    if (opt.data !== null) {
        set_data(opt.data);
    }
    else if (typeof localStorage['resume_data'] !== 'undefined') {
        set_data(JSON.parse(localStorage['resume_data']).data);
    }

    if (opt['export']) {
        $('#export-button').css('display', 'block');
    }

    if (opt.nomask) {
        $('.mask').css('display', 'none');
        $('#prev-button, #next-button').css('display', 'none');
    }
    else {
        // masks
        initialize_mask_transformations();

        // initial focus
        if (opt.data !== null) {
            current_row = opt.row;
        }
        else if (typeof localStorage['resume_data'] !== 'undefined') {
            current_row = JSON.parse(localStorage['resume_data']).row;
        }
        else {
            current_row = opt.row;
        }
        move_focus(current_row, 400, 0);
        move_cursor_button(current_row, 400, 400);
        magnify_row(current_row, 400, 400);
    }

    // memory
    switch (opt.memory) {
    case 'load':
        $('#load-panel').css('display', 'block');
        $('.load-button').on('click', function() {
            var n = parseInt($(this).attr("id").slice('load-button'.length));
            set_data(localStorage[n] || '');
        });
        break;
    case 'save':
        $('#save-panel').css('display', 'block');
        $('.save-button').on('click', function() {
            var n = parseInt($(this).attr("id").slice('save-button'.length));
            localStorage[n] = get_data();
        });
        break;
    case 'clear':
        localStorage.clear();
        break;
    }

    // events
    if (is_touch_device()) {
        // disable the overscroll effect on touch-capable environments.
        // http://www.html5rocks.com/en/mobile/touch/
        // http://stackoverflow.com/questions/2890361/disable-scrolling-in-an-iphone-web-application
        $(document).on('touchmove', function(e) {
            e.preventDefault();
        });

        if (!opt.nomask) {
            $('#prev-button').on('touchstart', function() {
                if (current_row > 1) {
                    select_row(current_row - 1);
                }
            });
            $('#next-button').on('touchstart', function() {
                if (current_row < 16) {
                    select_row(current_row + 1);
                }
            });
        }

        if (!opt.noedit) {
            $(".panel").each(function() {
                $(this).on('touchstart', on_panel_touchstart);
                $(this).on('touchmove', on_panel_touchmove);
                $(this).on('touchend', on_panel_touchend);
            });
        }
    }
    else {
        if (!opt.nomask) {
            $('#prev-button').on('click', function() {
                if (current_row > 1) {
                    select_row(current_row - 1);
                }
            });
            $('#next-button').on('click', function() {
                if (current_row < 16) {
                    select_row(current_row + 1);
                }
            });
        }

        if (!opt.noedit) {
            $(".panel").each(function() {
                $(this).on('mousedown', on_panel_mousedown);
                $(this).on('mousemove', on_panel_mousemove);
                $(this).on('mouseup', on_panel_mouseup);
            });
        }
    }

    if (opt['export']) {
        $('#export-button').on('click', function() {
            export_data();
        });
    }
});
<|endoftext|>


<commit_before>/**
* Story controller
* Used to get process info about a story such as url, title, and type
*/
HN.Story = (function(){

	function HNStory(storyInfo){
		this.storyInfo = storyInfo;
	};

	HNStory.prototype.url = function() {
		//for ask or show HN stories
		if(this.isLocalHNUrl()){
			return "https://news.ycombinator.com/item?id=" + this.storyInfo['id'];
		}
		return this.storyInfo['url'];
	};
	HNStory.prototype.isLocalHNUrl = function(){
		return this.storyInfo['url'] === '';
	};

	/**
	* gets the url root domain for display with story
	* http://www.nytimes.com/story becomes (nytimes.com)
	*/
	HNStory.prototype.urlRoot = function() {
		//for ask or show HN stories
		if(this.storyInfo['url'] === ''){
			return '';
		}
		//removes first part of url (http://www.)
		var base_url = this.storyInfo['url'];
		base_url =  base_url.replace(/^http(s)?:\/\/(www.)?/, '');
		//removes subfolders from url (/index.html)
		base_url = base_url.replace(/\/.*$/, '');
		//removes get requests from url (?q=something)
		return '(' + base_url.replace(/\?.*$/,'') + ')';
	};
	HNStory.prototype.title = function(){
		return this.storyInfo['title'];
	};
	HNStory.prototype.storyType = function(){
		if(this.type() !== 'story'){
			return false;
		}
		if(this.isLocalHNUrl()){
			if(this.title().substring(0,3).toLowerCase() === 'ask'){
				return 'ask';
			}
			return 'show';
		}
		return 'story';
	};
	HNStory.prototype.type = function(){
		return this.storyInfo['type'];
	};
	HNStory.prototype.numComments = function(){
		if(!this.storyInfo['descendants']){
			return 0;
		}
		return this.storyInfo['descendants'];
	};
	HNStory.prototype.getTopLevelCommentsIds = function(){
		if(!this.storyInfo['kids']){
			return [];
		}
		return this.storyInfo['kids'];
	};
	HNStory.prototype.commentsUrl = function(){
		// return 'https://news.ycombinator.com/item?id=' + this.storyInfo['id'];
		return HN.commentsUrl + this.storyInfo['id'];
	};
	return HNStory;
})();
<commit_msg>replace ycombinator link for ask page to local ask page<commit_after>/**
* Story controller
* Used to get process info about a story such as url, title, and type
*/
HN.Story = (function(){

	function HNStory(storyInfo){
		this.storyInfo = storyInfo;
	};

	HNStory.prototype.url = function() {
		//for ask or show HN stories
		if(this.isLocalHNUrl()){
			return HN.askUrl + this.storyInfo['id'];
		}
		return this.storyInfo['url'];
	};
	HNStory.prototype.isLocalHNUrl = function(){
		return this.storyInfo['url'] === '';
	};

	/**
	* gets the url root domain for display with story
	* http://www.nytimes.com/story becomes (nytimes.com)
	*/
	HNStory.prototype.urlRoot = function() {
		//for ask or show HN stories
		if(this.storyInfo['url'] === ''){
			return '';
		}
		//removes first part of url (http://www.)
		var base_url = this.storyInfo['url'];
		base_url =  base_url.replace(/^http(s)?:\/\/(www.)?/, '');
		//removes subfolders from url (/index.html)
		base_url = base_url.replace(/\/.*$/, '');
		//removes get requests from url (?q=something)
		return '(' + base_url.replace(/\?.*$/,'') + ')';
	};
	HNStory.prototype.title = function(){
		return this.storyInfo['title'];
	};
	HNStory.prototype.storyType = function(){
		if(this.type() !== 'story'){
			return false;
		}
		if(this.isLocalHNUrl()){
			if(this.title().substring(0,3).toLowerCase() === 'ask'){
				return 'ask';
			}
			return 'show';
		}
		return 'story';
	};
	HNStory.prototype.type = function(){
		return this.storyInfo['type'];
	};
	HNStory.prototype.numComments = function(){
		if(!this.storyInfo['descendants']){
			return 0;
		}
		return this.storyInfo['descendants'];
	};
	HNStory.prototype.getTopLevelCommentsIds = function(){
		if(!this.storyInfo['kids']){
			return [];
		}
		return this.storyInfo['kids'];
	};
	HNStory.prototype.commentsUrl = function(){
		// return 'https://news.ycombinator.com/item?id=' + this.storyInfo['id'];
		return HN.commentsUrl + this.storyInfo['id'];
	};
	return HNStory;
})();
<|endoftext|>


<commit_before>
createTest('Nested route with the many children as a tokens, callbacks should yield historic params', {
  '/a': {
    '/:id': {
      '/:id': function(a, b) {
        shared.fired.push(location.hash, a, b);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['#/a/b/c', 'b', 'c']);
    this.finish();
  });
});

createTest('Nested route with the first child as a token, callback should yield a param', {
  '/foo': {
    '/:id': {
      on: function(id) {
        shared.fired.push(location.hash, id);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/foo/a', function() {
    this.navigate('/foo/b/c', function() {
      deepEqual(shared.fired, ['#/foo/a', 'a']);
      this.finish();
    });
  });
});

createTest('Nested route with the first child as a regexp, callback should yield a param', {
  '/foo': {
    '/(\\w+)': {
      on: function(value) {
        shared.fired.push(location.hash, value);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/foo/a', function() {
    this.navigate('/foo/b/c', function() {
      deepEqual(shared.fired, ['#/foo/a', 'a']);
      this.finish();
    });
  });
});

createTest('Nested route with the several regular expressions, callback should yield a param', {
  '/a': {
    '/(\\w+)': {
      '/(\\w+)': function(a, b) {
        shared.fired.push(a, b);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['b', 'c']);
    this.finish();
  });
});

createTest('Single nested route with on member containing function value', {
  '/a': {
    '/b': {
      on: function() {
        shared.fired.push(location.hash);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b', function() {
      deepEqual(shared.fired, ['#/a/b']);
      this.finish();
  });
});

createTest('Single non-nested route with on member containing function value', {
  '/a/b': {
    on: function() {
      shared.fired.push(location.hash);
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b', function() {
    deepEqual(shared.fired, ['#/a/b']);
    this.finish();
  });
});

createTest('Single nested route with on member containing array of function values', {
  '/a': {
    '/b': {
      on: [function() { shared.fired.push(location.hash); },
        function() { shared.fired.push(location.hash); }]
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b', function() {
      deepEqual(shared.fired, ['#/a/b', '#/a/b']);
      this.finish();
  });
});

createTest('method should only fire once on the route.', {
  '/a': {
    '/b': {
      once: function() {
        shared.fired++;
      }
    }
  }
}, function() {
  shared.fired = 0;
  this.navigate('/a/b', function() {
    this.navigate('/a/b', function() {
      this.navigate('/a/b', function() {
        deepEqual(shared.fired, 1);
        this.finish();
      });
    });
  });
});

createTest('method should only fire once on the route, multiple nesting.', {
  '/a': {
    on: function() { shared.fired++; },
    once: function() { shared.fired++; }
  },
  '/b': {
    on: function() { shared.fired++; },
    once: function() { shared.fired++; }
  }
}, function() {
  shared.fired = 0;
  this.navigate('/a', function() {
    this.navigate('/b', function() {
      this.navigate('/a', function() {
        this.navigate('/b', function() {
          deepEqual(shared.fired, 6);
          this.finish();
        });
      });
    });
  });
});

createTest('overlapping routes with tokens.', {
  '/a/:b/c' : function(){
    shared.fired.push(location.hash);
  },
  '/a/:b/c/:d' : function(){
    shared.fired.push(location.hash);
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b/c', function() {
    this.navigate('/a/b/c/d', function() {
      deepEqual(shared.fired, ['#/a/b/c', '#/a/b/c/d']);
      this.finish();
    });
  });
});

//
// Recursion features
// ----------------------------------------------------------

createTest('Nested routes with no recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['c']);
    this.finish();
  });
});

createTest('Nested routes with backward recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, {
  recurse: 'backward'
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['c', 'b', 'a']);
    this.finish();
  });
});

createTest('Breaking out of nested routes with backward recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
        return false;
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, {
  recurse: 'backward'
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['c', 'b']);
    this.finish();
  });
});

createTest('Nested routes with forward recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, {
  recurse: 'forward'
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['a', 'b', 'c']);
    this.finish();
  });
});

createTest('Breaking out of nested routes with forward recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
        return false;
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, {
  recurse: 'forward'
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['a', 'b']);
    this.finish();
  });
});

//
// Special Events
// ----------------------------------------------------------

createTest('All global event should fire after every route', {
  '/a': {
    on: function a() {
      shared.fired.push('a');
    }
  },
  '/b': {
    '/c': {
      on: function a() {
        shared.fired.push('a');
      }
    }
  },
  '/d': {
    '/:e': {
      on: function a() {
        shared.fired.push('a');
      }
    }
  }
}, {
  after: function() {
    shared.fired.push('b');
  }
}, function() {
  shared.fired = [];

  this.navigate('/a', function() {
    this.navigate('/b/c', function() {
      this.navigate('/d/e', function() {
        deepEqual(shared.fired, ['a', 'b', 'a', 'b', 'a', 'b']);
        this.finish();
      });
    });
  });

});

createTest('Not found.', {
  '/a': {
    on: function a() {
      shared.fired.push('a');
    }
  },
  '/b': {
    on: function a() {
      shared.fired.push('b');
    }
  }
}, {
  notfound: function() {
    shared.fired.push('notfound');
  }
}, function() {
  shared.fired = [];

  this.navigate('/c', function() {
    this.navigate('/d', function() {
      deepEqual(shared.fired, ['notfound', 'notfound']);
      this.finish();
    });
  });
});

createTest('On all.', {
  '/a': {
    on: function a() {
      shared.fired.push('a');
    }
  },
  '/b': {
    on: function a() {
      shared.fired.push('b');
    }
  }
}, {
  on: function() {
    shared.fired.push('c');
  }
}, function() {
  shared.fired = [];

  this.navigate('/a', function() {
    this.navigate('/b', function() {
      deepEqual(shared.fired, ['a', 'c', 'b', 'c']);
      this.finish();
    });
  });
});

createTest('After all.', {
  '/a': {
    on: function a() {
      shared.fired.push('a');
    }
  },
  '/b': {
    on: function a() {
      shared.fired.push('b');
    }
  }
}, {
  after: function() {
    shared.fired.push('c');
  }
}, function() {
  shared.fired = [];

  this.navigate('/a', function() {
    this.navigate('/b', function() {
      deepEqual(shared.fired, ['a', 'c', 'b', 'c']);
      this.finish();
    });
  });
});

createTest('resource object.', {
  '/a': {
    '/b/:c': {
      on: 'f1'
    },
    on: 'f2'
  },
  '/d': {
    on: ['f1', 'f2']
  }
},
{
  resource: {
    f1: function (name){
        shared.fired.push("f1-" + name);
    },
    f2: function (name){
        shared.fired.push("f2");
    }
  }
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    this.navigate('/d', function() {
      deepEqual(shared.fired, ['f1-c', 'f1-undefined', 'f2']);
      this.finish();
    });
  });
});
<commit_msg>[test] testing forward recursion with an after event<commit_after>
createTest('Nested route with the many children as a tokens, callbacks should yield historic params', {
  '/a': {
    '/:id': {
      '/:id': function(a, b) {
        shared.fired.push(location.hash, a, b);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['#/a/b/c', 'b', 'c']);
    this.finish();
  });
});

createTest('Nested route with the first child as a token, callback should yield a param', {
  '/foo': {
    '/:id': {
      on: function(id) {
        shared.fired.push(location.hash, id);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/foo/a', function() {
    this.navigate('/foo/b/c', function() {
      deepEqual(shared.fired, ['#/foo/a', 'a']);
      this.finish();
    });
  });
});

createTest('Nested route with the first child as a regexp, callback should yield a param', {
  '/foo': {
    '/(\\w+)': {
      on: function(value) {
        shared.fired.push(location.hash, value);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/foo/a', function() {
    this.navigate('/foo/b/c', function() {
      deepEqual(shared.fired, ['#/foo/a', 'a']);
      this.finish();
    });
  });
});

createTest('Nested route with the several regular expressions, callback should yield a param', {
  '/a': {
    '/(\\w+)': {
      '/(\\w+)': function(a, b) {
        shared.fired.push(a, b);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['b', 'c']);
    this.finish();
  });
});

createTest('Single nested route with on member containing function value', {
  '/a': {
    '/b': {
      on: function() {
        shared.fired.push(location.hash);
      }
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b', function() {
      deepEqual(shared.fired, ['#/a/b']);
      this.finish();
  });
});

createTest('Single non-nested route with on member containing function value', {
  '/a/b': {
    on: function() {
      shared.fired.push(location.hash);
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b', function() {
    deepEqual(shared.fired, ['#/a/b']);
    this.finish();
  });
});

createTest('Single nested route with on member containing array of function values', {
  '/a': {
    '/b': {
      on: [function() { shared.fired.push(location.hash); },
        function() { shared.fired.push(location.hash); }]
    }
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b', function() {
      deepEqual(shared.fired, ['#/a/b', '#/a/b']);
      this.finish();
  });
});

createTest('method should only fire once on the route.', {
  '/a': {
    '/b': {
      once: function() {
        shared.fired++;
      }
    }
  }
}, function() {
  shared.fired = 0;
  this.navigate('/a/b', function() {
    this.navigate('/a/b', function() {
      this.navigate('/a/b', function() {
        deepEqual(shared.fired, 1);
        this.finish();
      });
    });
  });
});

createTest('method should only fire once on the route, multiple nesting.', {
  '/a': {
    on: function() { shared.fired++; },
    once: function() { shared.fired++; }
  },
  '/b': {
    on: function() { shared.fired++; },
    once: function() { shared.fired++; }
  }
}, function() {
  shared.fired = 0;
  this.navigate('/a', function() {
    this.navigate('/b', function() {
      this.navigate('/a', function() {
        this.navigate('/b', function() {
          deepEqual(shared.fired, 6);
          this.finish();
        });
      });
    });
  });
});

createTest('overlapping routes with tokens.', {
  '/a/:b/c' : function(){
    shared.fired.push(location.hash);
  },
  '/a/:b/c/:d' : function(){
    shared.fired.push(location.hash);
  }
}, function() {
  shared.fired = [];
  this.navigate('/a/b/c', function() {
    this.navigate('/a/b/c/d', function() {
      deepEqual(shared.fired, ['#/a/b/c', '#/a/b/c/d']);
      this.finish();
    });
  });
});

//
// Recursion features
// ----------------------------------------------------------

createTest('Nested routes with no recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['c']);
    this.finish();
  });
});

createTest('Nested routes with backward recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, {
  recurse: 'backward'
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['c', 'b', 'a']);
    this.finish();
  });
});

createTest('Breaking out of nested routes with backward recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
        return false;
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, {
  recurse: 'backward'
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['c', 'b']);
    this.finish();
  });
});

createTest('Nested routes with forward recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, {
  recurse: 'forward'
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['a', 'b', 'c']);
    this.finish();
  });
});

createTest('Nested routes with forward recursion, single route with an after event.', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        },
        after: function() {
          shared.fired.push('c-after');
        }
      },
      on: function b() {
        shared.fired.push('b');
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, {
  recurse: 'forward'
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    this.navigate('/a/b', function() {
      deepEqual(shared.fired, ['a', 'b', 'c', 'c-after', 'a', 'b']);
      this.finish();
    });
  });
});

createTest('Breaking out of nested routes with forward recursion', {
  '/a': {
    '/b': {
      '/c': {
        on: function c() {
          shared.fired.push('c');
        }
      },
      on: function b() {
        shared.fired.push('b');
        return false;
      }
    },
    on: function a() {
      shared.fired.push('a');
    }
  }
}, {
  recurse: 'forward'
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    deepEqual(shared.fired, ['a', 'b']);
    this.finish();
  });
});

//
// Special Events
// ----------------------------------------------------------

createTest('All global event should fire after every route', {
  '/a': {
    on: function a() {
      shared.fired.push('a');
    }
  },
  '/b': {
    '/c': {
      on: function a() {
        shared.fired.push('a');
      }
    }
  },
  '/d': {
    '/:e': {
      on: function a() {
        shared.fired.push('a');
      }
    }
  }
}, {
  after: function() {
    shared.fired.push('b');
  }
}, function() {
  shared.fired = [];

  this.navigate('/a', function() {
    this.navigate('/b/c', function() {
      this.navigate('/d/e', function() {
        deepEqual(shared.fired, ['a', 'b', 'a', 'b', 'a', 'b']);
        this.finish();
      });
    });
  });

});

createTest('Not found.', {
  '/a': {
    on: function a() {
      shared.fired.push('a');
    }
  },
  '/b': {
    on: function a() {
      shared.fired.push('b');
    }
  }
}, {
  notfound: function() {
    shared.fired.push('notfound');
  }
}, function() {
  shared.fired = [];

  this.navigate('/c', function() {
    this.navigate('/d', function() {
      deepEqual(shared.fired, ['notfound', 'notfound']);
      this.finish();
    });
  });
});

createTest('On all.', {
  '/a': {
    on: function a() {
      shared.fired.push('a');
    }
  },
  '/b': {
    on: function a() {
      shared.fired.push('b');
    }
  }
}, {
  on: function() {
    shared.fired.push('c');
  }
}, function() {
  shared.fired = [];

  this.navigate('/a', function() {
    this.navigate('/b', function() {
      deepEqual(shared.fired, ['a', 'c', 'b', 'c']);
      this.finish();
    });
  });
});

createTest('After all.', {
  '/a': {
    on: function a() {
      shared.fired.push('a');
    }
  },
  '/b': {
    on: function a() {
      shared.fired.push('b');
    }
  }
}, {
  after: function() {
    shared.fired.push('c');
  }
}, function() {
  shared.fired = [];

  this.navigate('/a', function() {
    this.navigate('/b', function() {
      deepEqual(shared.fired, ['a', 'c', 'b', 'c']);
      this.finish();
    });
  });
});

createTest('resource object.', {
  '/a': {
    '/b/:c': {
      on: 'f1'
    },
    on: 'f2'
  },
  '/d': {
    on: ['f1', 'f2']
  }
},
{
  resource: {
    f1: function (name){
        shared.fired.push("f1-" + name);
    },
    f2: function (name){
        shared.fired.push("f2");
    }
  }
}, function() {
  shared.fired = [];

  this.navigate('/a/b/c', function() {
    this.navigate('/d', function() {
      deepEqual(shared.fired, ['f1-c', 'f1-undefined', 'f2']);
      this.finish();
    });
  });
});

<|endoftext|>


<commit_before>/*
 * tweetable 2.0 - jQuery twitter feed plugin
 *
 * Copyright (c) 2009 Philip Beel (http://www.theodin.co.uk/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * With modifications from Philipp Robbel (http://www.robbel.com/) & Patrick DW (stackoverflow)
 *
 * Revision: $Id: jquery.tweetable.js 2013-06-16 $
 *
 */
(function($) {

	jQuery.fn.tweetable = function (opts) {
		opts = $.extend({}, $.fn.tweetable.options, opts);

		return this.each(function () {

			var act = jQuery(this)
			,   tweetList = jQuery('
')[opts.position.toLowerCase() + 'To'](act)
			,   shortMonths = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
			,	api = "http://api.getmytweets.co.uk/?screenname="
			,   limitcount = "&limit="
			,	callback = "&callback=?"
			,   twitterError
			,   tweetMonth
			,   tweetMonthInt
			,   iterate
			,   element;

			// Show a loading message
			tweetList.append('
'+ opts.loading +'
');

			// Fire JSON request to twitter API
			jQuery.getJSON(api + opts.username + limitcount + opts.limit).done(function(data)
			{
				// Hide the tweet loader in favour of the response
				jQuery("#tweet_loader").remove();

				// Check for response error
				twitterError = data && data.error || null;

				if(twitterError)
				{
					tweetList.append('

'+ opts.failed +'

');
					return;
				}

				// Loop through twitter API response
				jQuery.each(data.tweets, function (i, tweet) {

					// Output tweets if less than limit
					if(i >= opts.limit)
						return;

					tweetList.append('

' + tweet.response.replace(/#(.*?)(\s|$)/g, '#$1 ').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '$& ').replace(/@(.*?)(\s|\(|\)|$)/g, '@$1 $2').replace(/:">/, ' ">').replace(/: <\/a>/, ':') + '

');

					// Display the time of tweet if required
					if (opts.time === true) {
						for(iterate=0; iterate<=12; iterate++) {
							if(shortMonths[iterate] === tweet.tweet_date.substr(4, 3)) {
								tweetMonthInt = iterate + 1;
								tweetMonth = (tweetMonthInt < 10) ? '0' + tweetMonthInt : tweetMonthInt ;
							}
						}
						// Create ISO 8601 formatted date
						var iso8601 = tweet.tweet_date.substr(26,4) + '-' + tweetMonth + '-' + tweet.tweet_date.substr(8, 2) + 'T' + tweet.tweet_date.substr(11,8) + 'Z';
						jQuery('.tweet_link_' + i).append('
<'
							+ ((opts.html5) ? 'time datetime="' + iso8601 + '"' : 'small')
							+ '> ' + tweet.tweet_date.substr(8, 2) + '/' + tweetMonth + '/' + tweet.tweet_date.substr(26,4) + ', ' + tweet.tweet_date.substr(11,5) + '</'
							+ ((opts.html5) ? 'time' : 'small') +
							'>
');
					}
				});

				// Display one tweet and retweet
				if ( opts.rotate === true ) {

					var listItem = tweetList.find('li')
					,   listLength = listItem.length || null
					,   current = 0
					,   timeout = opts.speed;

					if(!listLength)
						return

					// Rotate the tweets one at a time
					function rotateTweets() {
					   listItem.eq(current++).fadeOut(400, function(){
							current = (current === listLength) ? 0 : current;
							listItem.eq(current).fadeIn(400);
					   });
					}
					//Hide all but the first tweet
					listItem.slice(1).hide();

					//Rotate tweets at specified interval
					setInterval(rotateTweets, timeout);
				}
				opts.onComplete(tweetList);

			// Catch any failure to launch
			}).fail(function( jqxhr, textStatus, error ) {
				// Hide the tweet loader in favour of the response
				jQuery("#tweet_loader").remove();

				tweetList.append('

'+ opts.failed +'

');
				return;
			});
		});
	};

	// Define plugin defaults
	$.fn.tweetable.options = {
		limit: 5,                       // Number of tweets to show
		username: 'philipbeel',         // @username tweets to display
		time: false,                    // Display date
		rotate: false,                  // Rotate tweets
		speed: 5000,                    // Speed of rotation
		replies: false,                 // Filter out @replys
		position: 'append',             // Append position
		failed: "No tweets available",  // Twitter stream unavailable text
		loading: "Loading tweets...",	// Tweets loading message
		html5: false,                   // HTML5 Support
		retweets: false,                // Show retweets
		onComplete: function($ul) {}    // On complete callback
	};

})(jQuery);
jQuery.support.cors = true;<commit_msg>Update tweetable.jquery.js<commit_after>/*
 * tweetable 2.0 - jQuery twitter feed plugin
 *
 * Copyright (c) 2009 Philip Beel (http://www.theodin.co.uk/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * With modifications from Philipp Robbel (http://www.robbel.com/) & Patrick DW (stackoverflow)
 *
 * Revision: $Id: jquery.tweetable.js 2013-06-16 $
 *
 */
(function($) {

	jQuery.fn.tweetable = function (opts) {
		opts = $.extend({}, $.fn.tweetable.options, opts);

		return this.each(function () {

			var act = jQuery(this)
			,   tweetList = jQuery('
')[opts.position.toLowerCase() + 'To'](act)
			,   shortMonths = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
			,	api = "http://api.getmytweets.co.uk/?screenname="
			,   limitcount = "&limit="
			,	callback = "&callback=?"
			,   twitterError
			,   tweetMonth
			,   tweetMonthInt
			,   iterate
			,   element;

			// Show a loading message
			tweetList.append('
'+ opts.loading +'
');

			// Fire JSON request to twitter API
			jQuery.getJSON(api + opts.username + limitcount + opts.limit).done(function(data)
			{
				// Hide the tweet loader in favour of the response
				jQuery("#tweet_loader").remove();

				// Check for response error
				twitterError = data && data.error || null;

				if(twitterError)
				{
					tweetList.append('

'+ opts.failed +'

');
					return;
				}

				// Loop through twitter API response
				jQuery.each(data.tweets, function (i, tweet) {

					// Output tweets if less than limit
					if(i >= opts.limit)
						return;

					tweetList.append('

' + tweet.response.replace(/#(.*?)(\s|$)/g, '#$1 ').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '$& ').replace(/@(.*?)(\s|\(|\)|$)/g, '@$1 $2').replace(/:">/, ' ">').replace(/: <\/a>/, ':') + '

');

					// Display the time of tweet if required
					if (opts.time === true) {
						for(iterate=0; iterate<=12; iterate++) {
							if(shortMonths[iterate] === tweet.tweet_date.substr(4, 3)) {
								tweetMonthInt = iterate + 1;
								tweetMonth = (tweetMonthInt < 10) ? '0' + tweetMonthInt : tweetMonthInt ;
							}
						}
						// Create ISO 8601 formatted date
						var iso8601 = tweet.tweet_date.substr(26,4) + '-' + tweetMonth + '-' + tweet.tweet_date.substr(8, 2) + 'T' + tweet.tweet_date.substr(11,8) + 'Z';
						jQuery('.tweet_link_' + i).append('
<'
							+ ((opts.html5) ? 'time datetime="' + iso8601 + '"' : 'small')
							+ '> ' + tweet.tweet_date.substr(8, 2) + '/' + tweetMonth + '/' + tweet.tweet_date.substr(26,4) + ', ' + tweet.tweet_date.substr(11,5) + '</'
							+ ((opts.html5) ? 'time' : 'small') +
							'>
');
					}
				});

				// Display one tweet and retweet
				if ( opts.rotate === true ) {

					var listItem = tweetList.find('li')
					,   listLength = listItem.length || null
					,   current = 0
					,   timeout = opts.speed;

					if(!listLength)
						return

					// Rotate the tweets one at a time
					function rotateTweets() {
					   listItem.eq(current++).fadeOut(400, function(){
							current = (current === listLength) ? 0 : current;
							listItem.eq(current).fadeIn(400);
					   });
					}
					//Hide all but the first tweet
					listItem.slice(1).hide();

					//Rotate tweets at specified interval
					setInterval(rotateTweets, timeout);
				}
				opts.onComplete(tweetList);

			// Catch any failure to launch
			}).fail(function( jqxhr, textStatus, error ) {
				// Hide the tweet loader in favour of the response
				jQuery("#tweet_loader").remove();

				tweetList.append('

'+ opts.failed +'

');
				return;
			});
		});
	};

	// Define plugin defaults
	$.fn.tweetable.options = {
		limit: 4,       		                // Number of tweets to show
		username: 'oembed',             		// @username tweets to display
		time: false,    			       	// Display date
		rotate: false,                  		// Rotate tweets
		speed: 5000,                    		// Speed of rotation
		replies: false,                 		// Filter out @replys
		position: 'append',             		// Append position
		failed: "Sorry, no tweets available :-(",  	// Twitter stream unavailable text
		loading: "Loading tweets...",			// Tweets loading message
		html5: false,                   		// HTML5 Support
		retweets: false,                		// Show retweets
		onComplete: function($ul) {}    		// On complete callback
	};

})(jQuery);
jQuery.support.cors = true;
<|endoftext|>


<commit_before>$(function() {

window.onload = function() {

    var game = new Phaser.Game(1536, 864, Phaser.AUTO, '', { preload: preload, create: create, update: update });

    var jumping = "0";

    var score = 0;
    var lives = 3;

    var lookdir;

    function preload() {

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        game.load.image('background', 'assets/images/background.png');
        game.load.image('ocean', 'assets/images/ocean.png');
        cursors = game.input.keyboard.createCursorKeys();
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

    }

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');

        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');

        //score
        active = 1;
        foot = 1;

        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        //hiding this for now its in the way
        //var fatty1 = game.add.sprite(0, 0, 'fatty1');

        //Uncaught TypeError: Cannot read property 'velocity' of null
        //fatty1.body.velocity.x=20;

        ocean = game.add.sprite(0, game.world.height - 635, 'ocean');

        //fatty1 = game.add.sprite(450, game.world.height - 300, 'fatty1');
        //fatty2 = game.add.sprite(450, game.world.height - 300, 'fatty2');
        //fatty3 = game.add.sprite(450, game.world.height - 300, 'fatty3');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        ocean.body.immovable = true;

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        //Player physics properties.
        //player.body.bounce.y = 0.3;
        //player.body.gravity.y = 800;
        player.body.collideWorldBounds = true;

        //start the player looking right
        //lookdir = "right";

    }

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                player.frame = 4;
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                player.frame = 4;
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                player.frame = 4;
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                player.frame = 7;
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                player.frame = 7;
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                player.frame = 7;
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            player.frame = 2;
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
        }

    //animations

    //down
    function coroutine(f) {
        var o = f(); // instantiate the coroutine
        o.next(); // execute until the first yield
        return function(x) {
            o.next(x);
        }
    }
    var clock = coroutine(function*(_) {
        while (true) {
            yield _;
            player.frame = 0;
            yield _;
            player.frame = 1;
        }
    });
    setInterval(clock, 10000);

        } //update

};
});<commit_msg>Dur not in UPDATE!<commit_after>$(function() {

window.onload = function() {

    var game = new Phaser.Game(1536, 864, Phaser.AUTO, '', { preload: preload, create: create, update: update });

    var jumping = "0";

    var score = 0;
    var lives = 3;

    var lookdir;

    function preload() {

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        game.load.image('background', 'assets/images/background.png');
        game.load.image('ocean', 'assets/images/ocean.png');
        cursors = game.input.keyboard.createCursorKeys();
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

            function coroutine(f) {
               var o = f(); // instantiate the coroutine
               o.next(); // execute until the first yield
               return function(x) {
                   o.next(x);
               }
           }
           var clock = coroutine(function*(_) {
               while (true) {
                   yield _;
                   player.frame = 0;
                   yield _;
                   player.frame = 1;
               }
           });
           setInterval(clock, 1000);

           }

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');

        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');

        //score
        active = 1;
        foot = 1;

        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        //hiding this for now its in the way
        //var fatty1 = game.add.sprite(0, 0, 'fatty1');

        //Uncaught TypeError: Cannot read property 'velocity' of null
        //fatty1.body.velocity.x=20;

        ocean = game.add.sprite(0, game.world.height - 635, 'ocean');

        //fatty1 = game.add.sprite(450, game.world.height - 300, 'fatty1');
        //fatty2 = game.add.sprite(450, game.world.height - 300, 'fatty2');
        //fatty3 = game.add.sprite(450, game.world.height - 300, 'fatty3');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        ocean.body.immovable = true;

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        //Player physics properties.
        //player.body.bounce.y = 0.3;
        //player.body.gravity.y = 800;
        player.body.collideWorldBounds = true;

        //start the player looking right
        //lookdir = "right";

    }

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                player.frame = 4;
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                player.frame = 4;
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                player.frame = 4;
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                player.frame = 7;
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                player.frame = 7;
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                player.frame = 7;
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            player.frame = 2;
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
        }

        } //update

};
});<|endoftext|>


<commit_before>define(["js/ui/ItemsView", "js/html/HtmlElement", "underscore", "js/core/List"], function (ItemsView, HtmlElement, _, List) {

    return ItemsView.inherit("js.ui.SelectionView", {

        $defaultTemplateName: null,

        defaults: {
            /**
             * If multi selection is allowed or not
             */
            multiSelect: false,
            /**
             * The default place holder value if a placeholder template is defined
             */
            placeHolderValue: null,
            /**
             * The list of selected views
             */
            selectedViews: List,
            /**
             * The list of selected items
             */
            selectedItems: List,
            /**
             * The selected item
             */
            selectedItem: null,
            /**
             * The selected view index
             */
            selectedIndex: null,
            /**
             * If true, the first element is selected if no selectedItem is set
             */
            needsSelection: false,
            /**
             * The items
             * @type js.core.List
             * @type Array
             */
            items: [],
            /**
             * A key path for comparison of items
             */
            keyPath: null,
            /**
             * If false, elements are not selectable
             * Useful for readonly selection
             * @type Boolean
             */
            forceSelectable: true,
            /***
             * If true an element can be deselected
             * Default is false
             *
             * @type Boolean
             */
            allowDeselection: false
        },

        ctor: function () {
            this.callBase();
            this.bind('selectedItems', 'add', this._onSelectedItemAdd, this);
            this.bind('selectedItems', 'remove', this._onSelectedItemRemove, this);
            this.bind('selectedItems', 'reset', this._onSelectedItemReset, this);

            this.bind('items', 'remove', this._itemRemove, this);
            this.bind('items', 'add', this._itemAdd, this);
        },

        _onSelectedItemAdd: function (e) {
            if(this.isRendered()){
                var item;
                var $renderedItems = this.$repeat.$renderedItems;
                for (var i = 0; i < $renderedItems.length; i++) {
                    item = $renderedItems[i].item;
                    if (e.$ === item && !$renderedItems[i].component.$.selected) {
                        $renderedItems[i].component.set({selected: true}, {silent: true});
                    }
                }
            }
        },

        _itemRemove: function(e) {
            if (e.$.item === this.$.selectedItem) {
                this._checkNeedsSelection();
            }
        },

        _itemAdd: function() {
            if (!this.$.selectedItem) {
                this._checkNeedsSelection();
            }
        },

        _onSelectedItemRemove: function (e) {
            if(this.isRendered()){

                var item;
                var $renderedItems = this.$repeat.$renderedItems;
                for (var i = 0; i < $renderedItems.length; i++) {
                    item = $renderedItems[i].item;
                    if (e.$ === item && $renderedItems[i].component.$.selected) {
                        $renderedItems[i].component.set({selected: false}, {silent: true});
                    }
                }
            }
        },

        _onSelectedItemReset: function () {
            this._renderSelectedItems(this.$.selectedItems);
        },

        hasSelection: function () {
            if (!this.$.selectedItem) {
                return false;
            }
            var c,
                itemKey = this._getItemKey();
            for (var i = 0; i < this.$renderedChildren.length; i++) {
                c = this.$renderedChildren[i].get(itemKey);
                if (this._areItemsEqual(c, this.$.selectedItem)) {
                    return true;
                }
            }
            return false;
        }.onChange('selectedItem'),

        _onItemsRendered: function () {
            this.callBase();

            this._checkNeedsSelection();
        },

        _checkNeedsSelection: function() {
            if (this.$.needsSelection) {
                var items = this._getItemsArray(this.$.items);
                if (items && items.length) {
                    for (var i = 0; i < items.length; i++) {
                        if (this.$.selectedItem === items[i]) {
                            return;
                        }
                    }
                    this.set('selectedItem', items[0]);
                } else {
                    this.set('selectedItem', null);
                }
            }
        },

        _commitChangedAttributes: function ($) {
            if ($.hasOwnProperty("selectedItem") && $["selectedItem"] != null) {
                this.$.selectedItems.add($["selectedItem"]);
            }

            this.callBase();
        },

        _renderChild: function (child) {
            if (child instanceof HtmlElement) {
                var self = this;
                if (this.$.forceSelectable === true) {
                    child.set({selectable: true});
                }
                child.bind('change:selected', function (e, options) {
                    if (!e.$ && !self.$.allowDeselection) {
                        child.set('selected', true, {silent: true});
                    }
                    if (self.$.allowDeselection || (e.$ && !self.$.allowDeselection)) {
                        self._onChildSelected(e.target);
                    }
                });
            }
            this.callBase();

            // get item for child, if item is in selectedItems, select child!
            var item = child.get(this._getItemKey());
            if (item) {
                for (var i = 0; i < this.$.selectedItems.length; i++) {
                    if (this._areItemsEqual(item, this.$.selectedItems[i])) {
                        child.set({selected: true}, {silent: true});
                        break;
                    }
                }
                if (this._areItemsEqual(item, this.$.selectedItem)) {
                    child.set({selected: true}, {silent: true});
                }
            }

            if (this.$.needsSelection && !this.$.selectedItem) {
                this.set('selectedItem', child.get(this._getItemKey()));
            }

        },

        _addTemplate: function (template) {
            this.callBase();
            if (template.$.name == "placeHolder") {
                this.$hasPlaceHolder = true;
            }
        },

        _renderPlaceHolderValue: function (placeHolderValue, oldValue) {
            if (this.$placeHolder) {
                this.removeChild(this.$placeHolder);
            }

            if (this.$hasPlaceHolder) {
                var attr = {};
                attr[this._getItemKey()] = placeHolderValue;
                attr["selected"] = this.$.selectedItem === placeHolderValue;
                this.$placeHolder = this.$templates.placeHolder.createInstance(attr);

                this.addChild(this.$placeHolder, {childIndex: 0});
            }
        },

        _renderSelectedItem: function (item, oldItem) {
            var comp = this.getComponentForItem(item);
            if (this.$hasPlaceHolder && item === this.$.placeHolderValue) {
                comp = this.$placeHolder;
            }
            if (comp) {
                comp.set({selected: true}, {silent: true});
                var c;
                if (!this.$.multiSelect) {
                    for (var i = 0; i < this.$renderedChildren.length; i++) {
                        c = this.$renderedChildren[i];
                        if (c != comp && c.$.selected === true) {
                            c.set({selected: false}, {silent: true});
                        }
                    }
                }
            } else {
                if (oldItem != null && !this.$.multiSelect) {
                    comp = this.getComponentForItem(oldItem);
                    comp && comp.set({selected: false}, {silent: true});
                }
            }
        },

        _renderSelectedItems: function (list) {
            if (list && list.length) {
                var item;
                var $renderedItems = this.$repeat.$renderedItems;
                for (var i = 0; i < $renderedItems.length; i++) {
                    item = $renderedItems[i].item;
                    $renderedItems[i].component.set({selected: (list.indexOf(item) > -1)}, {silent: true});
                }
            } else if (this.$placeHolder && this.$.selectedItem == null) {
                this.$placeHolder.set({selected: true}, {silent: true});
            }
        },

        _renderSelectedIndex: function (i, oldIndex) {
            if (i !== null && i < this.$renderedChildren.length && i > -1) {
                var c = this.$renderedChildren[i];
                c.set({selected: true}, {silent: true});
            }
            if (oldIndex !== null && oldIndex < this.$renderedChildren.length && oldIndex > -1) {
                var oc = this.$renderedChildren[oldIndex];
                oc.set({selected: false}, {silent: true});
            }

        },

        _onChildSelected: function (child) {
            var c, i;
            var checkMultiSelect = (child.$.selected === true && this.$.multiSelect === false),
                correctSelection = false,
                selectedChildren = [],
                selectedItems = [],
                selectedIndex,
                selectedItem = null;

            for (i = 0; i < this.$renderedChildren.length; i++) {
                c = this.$renderedChildren[i];
                if (checkMultiSelect) {
                    if (c != child && c.$.selected === true) {
                        c.set({selected: false}, {silent: true});
                    }
                }

                if (c.$.selected === true) {
                    selectedIndex = i;
                    selectedChildren.push(c);
                    var item = c.get(this._getItemKey());
                    if (item != null) {
                        selectedItems.push(item);
                        selectedItem = item;
                    }
                }
            }

            if (!correctSelection) {
                this.set({selectedViews: selectedChildren, selectedIndex: selectedIndex, selectedItem: selectedItem});
                this.$.selectedItems.reset(selectedItems);
            }
        },

        _areItemsEqual: function (itemA, itemB) {
            if (this.$.keyPath) {
                if (!itemA || !itemB) {
                    return false;
                }
                return itemA.get(this.$.keyPath) === itemB.get(this.$.keyPath);
            } else {
                return itemA === itemB;
            }
        }
    });
});<commit_msg>fixed selectedItems in SelectionView<commit_after>define(["js/ui/ItemsView", "js/html/HtmlElement", "underscore", "js/core/List"], function (ItemsView, HtmlElement, _, List) {

    return ItemsView.inherit("js.ui.SelectionView", {

        $defaultTemplateName: null,

        defaults: {
            /**
             * If multi selection is allowed or not
             */
            multiSelect: false,
            /**
             * The default place holder value if a placeholder template is defined
             */
            placeHolderValue: null,
            /**
             * The list of selected views
             */
            selectedViews: List,
            /**
             * The list of selected items
             */
            selectedItems: List,
            /**
             * The selected item
             */
            selectedItem: null,
            /**
             * The selected view index
             */
            selectedIndex: null,
            /**
             * If true, the first element is selected if no selectedItem is set
             */
            needsSelection: false,
            /**
             * The items
             * @type js.core.List
             * @type Array
             */
            items: [],
            /**
             * A key path for comparison of items
             */
            keyPath: null,
            /**
             * If false, elements are not selectable
             * Useful for readonly selection
             * @type Boolean
             */
            forceSelectable: true,
            /***
             * If true an element can be deselected
             * Default is false
             *
             * @type Boolean
             */
            allowDeselection: false
        },

        ctor: function () {
            this.callBase();
            this.bind('selectedItems', 'add', this._onSelectedItemAdd, this);
            this.bind('selectedItems', 'remove', this._onSelectedItemRemove, this);
            this.bind('selectedItems', 'reset', this._onSelectedItemReset, this);

            this.bind('items', 'remove', this._itemRemove, this);
            this.bind('items', 'add', this._itemAdd, this);
        },

        _onSelectedItemAdd: function (e) {
            if (this.isRendered()) {
                var item;
                var $renderedItems = this.$repeat.$renderedItems;
                for (var i = 0; i < $renderedItems.length; i++) {
                    item = $renderedItems[i].item;
                    if (e.$ === item && !$renderedItems[i].component.$.selected) {
                        $renderedItems[i].component.set({selected: true}, {silent: true});
                    }
                }
            }
        },

        _itemRemove: function (e) {
            if (e.$.item === this.$.selectedItem) {
                this._checkNeedsSelection();
            }
        },

        _itemAdd: function () {
            if (!this.$.selectedItem) {
                this._checkNeedsSelection();
            }
        },

        _onSelectedItemRemove: function (e) {
            if (this.isRendered()) {

                var item;
                var $renderedItems = this.$repeat.$renderedItems;
                for (var i = 0; i < $renderedItems.length; i++) {
                    item = $renderedItems[i].item;
                    if (e.$ === item && $renderedItems[i].component.$.selected) {
                        $renderedItems[i].component.set({selected: false}, {silent: true});
                    }
                }
            }
        },

        _onSelectedItemReset: function () {
            this._renderSelectedItems(this.$.selectedItems);
        },

        hasSelection: function () {
            if (!this.$.selectedItem) {
                return false;
            }
            var c,
                itemKey = this._getItemKey();
            for (var i = 0; i < this.$renderedChildren.length; i++) {
                c = this.$renderedChildren[i].get(itemKey);
                if (this._areItemsEqual(c, this.$.selectedItem)) {
                    return true;
                }
            }
            return false;
        }.onChange('selectedItem'),

        _onItemsRendered: function () {
            this.callBase();

            this._checkNeedsSelection();
        },

        _checkNeedsSelection: function () {
            if (this.$.needsSelection) {
                var items = this._getItemsArray(this.$.items);
                if (items && items.length) {
                    for (var i = 0; i < items.length; i++) {
                        if (this.$.selectedItem === items[i]) {
                            return;
                        }
                    }
                    this.set('selectedItem', items[0]);
                } else {
                    this.set('selectedItem', null);
                }
            }
        },

        _commitChangedAttributes: function ($) {
            if ($.hasOwnProperty("selectedItem") && $["selectedItem"] != null) {
                this.$.selectedItems.reset([$["selectedItem"]]);
            }

            this.callBase();
        },

        _renderChild: function (child) {
            if (child instanceof HtmlElement) {
                var self = this;
                if (this.$.forceSelectable === true) {
                    child.set({selectable: true});
                }
                child.bind('change:selected', function (e, options) {
                    if (!e.$ && !self.$.allowDeselection) {
                        child.set('selected', true, {silent: true});
                    }
                    if (self.$.allowDeselection || (e.$ && !self.$.allowDeselection)) {
                        self._onChildSelected(e.target);
                    }
                });
            }
            this.callBase();

            // get item for child, if item is in selectedItems, select child!
            var item = child.get(this._getItemKey());
            if (item) {
                for (var i = 0; i < this.$.selectedItems.length; i++) {
                    if (this._areItemsEqual(item, this.$.selectedItems.at(i))) {
                        child.set({selected: true}, {silent: true});
                        break;
                    }
                }
                if (this._areItemsEqual(item, this.$.selectedItem)) {
                    child.set({selected: true}, {silent: true});
                }
            }

            if (this.$.needsSelection && !this.$.selectedItem) {
                this.set('selectedItem', child.get(this._getItemKey()));
            }

        },

        _addTemplate: function (template) {
            this.callBase();
            if (template.$.name == "placeHolder") {
                this.$hasPlaceHolder = true;
            }
        },

        _renderPlaceHolderValue: function (placeHolderValue, oldValue) {
            if (this.$placeHolder) {
                this.removeChild(this.$placeHolder);
            }

            if (this.$hasPlaceHolder) {
                var attr = {};
                attr[this._getItemKey()] = placeHolderValue;
                attr["selected"] = this.$.selectedItem === placeHolderValue;
                this.$placeHolder = this.$templates.placeHolder.createInstance(attr);

                this.addChild(this.$placeHolder, {childIndex: 0});
            }
        },

        _renderSelectedItem: function (item, oldItem) {
            var comp = this.getComponentForItem(item);
            if (this.$hasPlaceHolder && item === this.$.placeHolderValue) {
                comp = this.$placeHolder;
            }
            if (comp) {
                comp.set({selected: true}, {silent: true});
                var c;
                if (!this.$.multiSelect) {
                    for (var i = 0; i < this.$renderedChildren.length; i++) {
                        c = this.$renderedChildren[i];
                        if (c != comp && c.$.selected === true) {
                            c.set({selected: false}, {silent: true});
                        }
                    }
                }
            } else {
                if (oldItem != null && !this.$.multiSelect) {
                    comp = this.getComponentForItem(oldItem);
                    comp && comp.set({selected: false}, {silent: true});
                }
            }
        },

        _renderSelectedItems: function (list) {
            if (list && list.length) {
                var item,
                    $renderedItems = this.$repeat.$renderedItems,
                    selected;
                for (var i = 0; i < $renderedItems.length; i++) {
                    item = $renderedItems[i].item;
                    for (var j = 0; j < list.length; j++) {
                        selected = this._areItemsEqual(item, list.at(j));
                        if (selected) {
                            break;
                        }
                    }
                    $renderedItems[i].component.set({selected: selected}, {silent: true});
                }
            } else if (this.$placeHolder && this.$.selectedItem == null) {
                this.$placeHolder.set({selected: true}, {silent: true});
            }
        },

        _renderSelectedIndex: function (i, oldIndex) {
            if (i !== null && i < this.$renderedChildren.length && i > -1) {
                var c = this.$renderedChildren[i];
                c.set({selected: true}, {silent: true});
            }
            if (oldIndex !== null && oldIndex < this.$renderedChildren.length && oldIndex > -1) {
                var oc = this.$renderedChildren[oldIndex];
                oc.set({selected: false}, {silent: true});
            }

        },

        _onChildSelected: function (child) {
            var c, i;
            var checkMultiSelect = (child.$.selected === true && this.$.multiSelect === false),
                correctSelection = false,
                selectedChildren = [],
                selectedItems = [],
                selectedIndex,
                selectedItem = null;

            for (i = 0; i < this.$renderedChildren.length; i++) {
                c = this.$renderedChildren[i];
                if (checkMultiSelect) {
                    if (c != child && c.$.selected === true) {
                        c.set({selected: false}, {silent: true});
                    }
                }

                if (c.$.selected === true) {
                    selectedIndex = i;
                    selectedChildren.push(c);
                    var item = c.get(this._getItemKey());
                    if (item != null) {
                        selectedItems.push(item);
                        selectedItem = item;
                    }
                }
            }

            if (!correctSelection) {
                this.set({selectedViews: selectedChildren, selectedIndex: selectedIndex, selectedItem: selectedItem});
                this.$.selectedItems.reset(selectedItems);
            }
        },

        _areItemsEqual: function (itemA, itemB) {
            if (this.$.keyPath) {
                if (!itemA || !itemB) {
                    return false;
                }
                return this.get(itemA, this.$.keyPath) === this.get(itemB, this.$.keyPath);
            } else {
                return itemA === itemB;
            }
        }
    });
});<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var os = require('os');
var cluster = require('cluster');

/**
 * Cluster setup.
 */

// Setup the cluster to use app.js
cluster.setupMaster({
  exec: 'app.js'
});

// Listen for dying workers
cluster.on('exit', function(worker) {
  console.log('Worker ' + worker.id + ' died');
  // Replace the dead worker
  cluster.fork();
});

// Fork a worker for each available CPU
for (var i = 0; i < os.cpus().length; i++) {
  cluster.fork();
}
<commit_msg>Cleaned up cluster_app.js<commit_after>var os = require('os');
var cluster = require('cluster');

cluster.setupMaster({
  exec: 'app.js'
});

cluster.on('exit', function(worker) {
  console.log('worker ' + worker.id + ' died');
  cluster.fork();
});

for (var i = 0; i < os.cpus().length; i++) {
  cluster.fork();
}<|endoftext|>


<commit_before>var twitter = require('ntwitter');
var credentials = require('./credentials.js');

var t = new twitter({
    consumer_key: credentials.consumer_key,
    consumer_secret: credentials.consumer_secret,
    access_token_key: credentials.access_token_key,
    access_token_secret: credentials.access_token_secret
});

t.search('#sod13', {'page':'22'}, function(err, data) {
  console.dir(data);
});<commit_msg>updating crontrack.js with mongo structure<commit_after>var twitter = require('ntwitter');
var mongoose = require('mongoose');
var credentials = require('./credentials.js');

var twschema = new mongoose.Schema({
    tw_id : String,
    tw_text : String,
    tw_userid : String,
    tw_name : String,
    in_reply_to_status_id : String,
    in_reply_to_screen_name : String,
    tw_truncated : Boolean
  });

var t = new twitter({
    consumer_key: credentials.consumer_key,
    consumer_secret: credentials.consumer_secret,
    access_token_key: credentials.access_token_key,
    access_token_secret: credentials.access_token_secret
});

t.search('#sod13', {'page':'22'}, function(err, data) {
  console.dir(data);
});<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

var common = require('./common.js');
var schema = require('./validator/schematron.js');

var bolusCommon = schema(
  {
    deviceTime: schema().ifExists().isDeviceTime(),
  }
);

module.exports = schema(schema().oneOf(
  schema(
      common,
      bolusCommon,
      {
        normal: schema().number().min(0),
        expectedNormal: schema().ifExists().number().min(0),
        duration: schema().banned(),
        extended: schema().banned(),
        expectedExtended: schema().banned(),
        subType: schema().string().in(['normal'])
      },
      schema.with('expectedNormal', 'normal')
    ),
  schema(
      common,
      bolusCommon,
      {
        duration: schema().number().min(0),
        extended: schema().number().min(0),
        expectedExtended: schema().ifExists().number().min(0),
        normal: schema().ifExists().number().min(0),
        expectedNormal: schema().ifExists().number().min(0),
        subType: schema().string().in(['square', 'dual/square'])
      },
      schema.with('expectedNormal', 'normal'),
      schema.with('expectedExtended', ['extended', 'duration', 'expectedDuration'])
    )
  )
);<commit_msg>add expectedDuration validation on boluses where it could exist<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

var common = require('./common.js');
var schema = require('./validator/schematron.js');

var bolusCommon = schema(
  {
    deviceTime: schema().ifExists().isDeviceTime(),
  }
);

module.exports = schema(schema().oneOf(
  schema(
      common,
      bolusCommon,
      {
        normal: schema().number().min(0),
        expectedNormal: schema().ifExists().number().min(0),
        duration: schema().banned(),
        extended: schema().banned(),
        expectedExtended: schema().banned(),
        subType: schema().string().in(['normal'])
      },
      schema.with('expectedNormal', 'normal')
    ),
  schema(
      common,
      bolusCommon,
      {
        duration: schema().number().min(0),
        expectedDuration: schema().ifExists().number().min(0),
        extended: schema().number().min(0),
        expectedExtended: schema().ifExists().number().min(0),
        normal: schema().ifExists().number().min(0),
        expectedNormal: schema().ifExists().number().min(0),
        subType: schema().string().in(['square', 'dual/square'])
      },
      schema.with('expectedNormal', 'normal'),
      schema.with('expectedExtended', ['extended', 'duration', 'expectedDuration'])
    )
  )
);<|endoftext|>