<commit_before>var http = require('http')
,	moment = require('../node_modules/moment');

var leagueInfo = {
	leagueName: 'NFL',
	updateURL: 'http://www.nfl.com/liveupdate/scorestrip/ss.json',
	updateURL2: 'http://www.nfl.com/liveupdate/scorestrip/scorestrip.json'
};

var getGameArray = function(next) {
	var rawOuter = '';
	var outerRequest = http.get(leagueInfo.updateURL, function(oRes) {
		oRes.on('data', function(chunk) {
			rawOuter += chunk;
		});
		oRes.on('end', function() {
			var rawInner = '';
			var innerRequest = http.get(leagueInfo.updateURL2, function(iRes) {
				iRes.on('data', function(chunk) {
					rawInner += chunk;
				});
				iRes.on('end', function() {
					rawInner = rawInner.replace(/\,\,/g,',"",');
					rawInner = rawInner.replace(/\,\,/g,',"",');
					innerArray = JSON.parse(rawInner).ss;
					var innerObj = { };
					for (var i = 0; i < innerArray.length; i++) {
						innerObj[innerArray[i][10]] = innerArray[i];
					}
					outerObj = JSON.parse(rawOuter);
					var gameArray = [];
					for (var i = 0; i < outerObj.gms.length; i++) {
						outerObj.gms[i].outer_w = outerObj.w;
						outerObj.gms[i].outer_t = outerObj.t;
						outerObj.gms[i].outer_y = outerObj.y;
						outerObj.gms[i].outer_gd = outerObj.gd;
						outerObj.gms[i].outer_bph = outerObj.bph;
						outerObj.gms[i].score_array = innerObj[outerObj.gms[i].gsis];
						gameArray.push(parseRawGame(outerObj.gms[i]));
					}
					next(gameArray);
				});
			}).on('error', function(e) {
				console.log('NFL inner http Error: ' + e.message);
			});
		});
	}).on('error', function(e) {
		console.log('NFL outer http Error: ' + e.message);
	});
};

var parseRawGame = function(rawGame) {
	var game = { };
	var gameState = '';
	var timeString = rawGame.t;
	switch(rawGame.q) {
		case 'P':
			gameState = 'Scheduled';
			break;
		case 'H':
			gameState = 'Halftime';
			break;
		case 'F':
			gameState = 'Ended';
			break;
		case 'FO':
			gameState = 'Ended';
			break;
		default:
			gameState = 'Progress';
			timeString = rawGame.score_array[3];
			break;
	}
	var endIndex = rawGame.eid.toString().length - 2;
	var dateStr = rawGame.eid.toString().substr(0,endIndex);
	var gameDate = moment(dateStr ,'YYYYMD').toDate();
	game.GameID = rawGame.eid;
	game.State = gameState;
	game.Date = gameDate;
	game.SeasonYear = rawGame.outer_y;
	game.SeasonType = rawGame.outer_t;
	game.SeasonWeek = rawGame.outer_w;
	game.Time = timeString;
	game.Quarter = rawGame.q;
	game.AwayTeamDisplayName = rawGame.v;
	game.AwayTeamName = rawGame.vnn;
	game.AwayScore = rawGame.vs;
	game.HomeTeamDisplayName = rawGame.h;
	game.HomeTeamName = rawGame.hnn;
	game.HomeScore = rawGame.hs;
	return game;
};

var gameChanged = function(oldGame, newGame) {
	return (oldGame.GameID === newGame.GameID) &&
		(	(oldGame.State !== newGame.State) ||
			(oldGame.Quarter !== newGame.Quarter) ||
			(oldGame.AwayScore !== newGame.AwayScore) ||
			(oldGame.HomeScore !== newGame.HomeScore));
};

var gameChangeString = function(oldGame, newGame) {
	var dif = [];
	if (oldGame.State !== newGame.State)
		dif.push(oldGame.State + '-' + newGame.State);
	if (oldGame.Quarter !== newGame.Quarter)
		dif.push(oldGame.Quarter + '-' + newGame.Quarter);
	if (oldGame.AwayScore !== newGame.AwayScore)
		dif.push(oldGame.AwayScore + '-' + newGame.AwayScore);
	if (oldGame.HomeScore !== newGame.HomeScore)
		dif.push(oldGame.HomeScore + '-' + newGame.HomeScore);
	return dif.join(',');
};

var makeGameLink = function(game) {
	var link = 'http://www.nfl.com/gamecenter/' +
	game.GameID + '/' + game.SeasonYear + '/' + game.SeasonType +
	game.SeasonWeek + '/' + game.AwayTeamName + '@' + game.HomeTeamName;
	return link;
};

var existsQuery = function(game) {
	var stmnt = 'Select 1 from NFLGameInstances where GameID = ?';
	var params = [game.GameID];
	return {
		sql: stmnt,
		inserts: params
	};
};

var insertGameQuery = function(game) {
	var stmnt =
		'Insert into NFLGameInstances(GameID,Date,StateID,Time,\
			SeasonYear,SeasonType,SeasonWeek,Quarter,AwayTeamID,\
			AwayScore,HomeTeamID,HomeScore)\
		Select\
			?,?,state.StateID,?,?,?,?,?,away.TeamID,?,home.TeamID,?\
		from NFLStates state\
			inner join NFLTeams away\
				on away.Name like ?\
			inner join NFLTeams home\
				on home.Name like ?\
		where state.State = ?;';
	var params = [game.GameID, game.Date, game.Time, game.SeasonYear,
		game.SeasonType, game.SeasonWeek, game.Quarter, game.AwayScore,
		game.HomeScore, game.AwayTeamName, game.HomeTeamName, game.State];
	return {
		sql: stmnt,
		inserts: params
	};
};

var lastGameInstanceQuery = function(game) {
	var stmnt =
		'Select\
			game.GameID\
		,	game.Date\
		,	state.State\
		,	game.SeasonYear\
		,	game.SeasonType\
		,	game.SeasonWeek\
		,	game.Time\
		,	game.Quarter\
		,	away.City as AwayTeamCity\
		,	away.Name as AwayTeamName\
		,	away.DisplayName as AwayTeamDisplayName\
		,	away.TwitterAccount as AwayTwitterAccount\
		,	away.TwitterHashtag as AwayTwitterHashtag\
		,	game.AwayScore\
		,	home.City as HomeTeamCity\
		,	home.Name as HomeTeamName\
		,	home.DisplayName as HomeTeamDisplayName\
		,	home.TwitterAccount as HomeTwitterAccount\
		,	home.TwitterHashtag as HomeTwitterHashtag\
		,	game.HomeScore\
		from NFLGameInstances game\
			inner join NFLStates state\
				on state.StateID = game.StateID\
			inner join NFLTeams away\
				on away.TeamID = game.AwayTeamID\
			inner join NFLTeams home\
				on home.TeamID = game.HomeTeamID\
		where GameID = ? order by ?? desc limit 1;';
	var params = [game.GameID, 'RecordedOn'];
	return {
		sql: stmnt,
		inserts: params
	};
};

module.exports.leagueInfo = leagueInfo;
module.exports.getGameArray = getGameArray;
module.exports.parseRawGame = parseRawGame;
module.exports.gameChanged = gameChanged;
module.exports.gameChangeString = gameChangeString;
module.exports.makeGameLink = makeGameLink;
module.exports.existsQuery = existsQuery;
module.exports.insertGameQuery = insertGameQuery;
module.exports.lastGameInstanceQuery = lastGameInstanceQuery;<commit_msg>fix nfl field types<commit_after>var http = require('http')
,	moment = require('../node_modules/moment');

var leagueInfo = {
	leagueName: 'NFL',
	updateURL: 'http://www.nfl.com/liveupdate/scorestrip/ss.json',
	updateURL2: 'http://www.nfl.com/liveupdate/scorestrip/scorestrip.json'
};

var getGameArray = function(next) {
	var rawOuter = '';
	var outerRequest = http.get(leagueInfo.updateURL, function(oRes) {
		oRes.on('data', function(chunk) {
			rawOuter += chunk;
		});
		oRes.on('end', function() {
			var rawInner = '';
			var innerRequest = http.get(leagueInfo.updateURL2, function(iRes) {
				iRes.on('data', function(chunk) {
					rawInner += chunk;
				});
				iRes.on('end', function() {
					rawInner = rawInner.replace(/\,\,/g,',"",');
					rawInner = rawInner.replace(/\,\,/g,',"",');
					innerArray = JSON.parse(rawInner).ss;
					var innerObj = { };
					for (var i = 0; i < innerArray.length; i++) {
						innerObj[innerArray[i][10]] = innerArray[i];
					}
					outerObj = JSON.parse(rawOuter);
					var gameArray = [];
					for (var i = 0; i < outerObj.gms.length; i++) {
						outerObj.gms[i].outer_w = outerObj.w;
						outerObj.gms[i].outer_t = outerObj.t;
						outerObj.gms[i].outer_y = outerObj.y;
						outerObj.gms[i].outer_gd = outerObj.gd;
						outerObj.gms[i].outer_bph = outerObj.bph;
						outerObj.gms[i].score_array = innerObj[outerObj.gms[i].gsis];
						gameArray.push(parseRawGame(outerObj.gms[i]));
					}
					next(gameArray);
				});
			}).on('error', function(e) {
				console.log('NFL inner http Error: ' + e.message);
			});
		});
	}).on('error', function(e) {
		console.log('NFL outer http Error: ' + e.message);
	});
};

var parseRawGame = function(rawGame) {
	var game = { };
	var gameState = '';
	var timeString = rawGame.t;
	switch(rawGame.q) {
		case 'P':
			gameState = 'Scheduled';
			break;
		case 'H':
			gameState = 'Halftime';
			break;
		case 'F':
			gameState = 'Ended';
			break;
		case 'FO':
			gameState = 'Ended';
			break;
		default:
			gameState = 'Progress';
			timeString = rawGame.score_array[3];
			break;
	}
	var endIndex = rawGame.eid.toString().length - 2;
	var dateStr = rawGame.eid.toString().substr(0,endIndex);
	var gameDate = moment(dateStr ,'YYYYMD').toDate();
	game.GameID = rawGame.eid.toString();
	game.State = gameState;
	game.Date = gameDate;
	game.SeasonYear = rawGame.outer_y;
	game.SeasonType = rawGame.outer_t;
	game.SeasonWeek = rawGame.outer_w;
	game.Time = timeString;
	game.Quarter = rawGame.q.toString();
	game.AwayTeamDisplayName = rawGame.v;
	game.AwayTeamName = rawGame.vnn;
	game.AwayScore = rawGame.vs;
	game.HomeTeamDisplayName = rawGame.h;
	game.HomeTeamName = rawGame.hnn;
	game.HomeScore = rawGame.hs;
	return game;
};

var gameChanged = function(oldGame, newGame) {
	return (oldGame.GameID === newGame.GameID) &&
		(	(oldGame.State !== newGame.State) ||
			(oldGame.Quarter !== newGame.Quarter) ||
			(oldGame.AwayScore !== newGame.AwayScore) ||
			(oldGame.HomeScore !== newGame.HomeScore));
};

var gameChangeString = function(oldGame, newGame) {
	var dif = [];
	if (oldGame.State !== newGame.State)
		dif.push(oldGame.State + '-' + newGame.State);
	if (oldGame.Quarter !== newGame.Quarter)
		dif.push(oldGame.Quarter + '-' + newGame.Quarter);
	if (oldGame.AwayScore !== newGame.AwayScore)
		dif.push(oldGame.AwayScore + '-' + newGame.AwayScore);
	if (oldGame.HomeScore !== newGame.HomeScore)
		dif.push(oldGame.HomeScore + '-' + newGame.HomeScore);
	return dif.join(',');
};

var makeGameLink = function(game) {
	var link = 'http://www.nfl.com/gamecenter/' +
	game.GameID + '/' + game.SeasonYear + '/' + game.SeasonType +
	game.SeasonWeek + '/' + game.AwayTeamName + '@' + game.HomeTeamName;
	return link;
};

var existsQuery = function(game) {
	var stmnt = 'Select 1 from NFLGameInstances where GameID = ?';
	var params = [game.GameID];
	return {
		sql: stmnt,
		inserts: params
	};
};

var insertGameQuery = function(game) {
	var stmnt =
		'Insert into NFLGameInstances(GameID,Date,StateID,Time,\
			SeasonYear,SeasonType,SeasonWeek,Quarter,AwayTeamID,\
			AwayScore,HomeTeamID,HomeScore)\
		Select\
			?,?,state.StateID,?,?,?,?,?,away.TeamID,?,home.TeamID,?\
		from NFLStates state\
			inner join NFLTeams away\
				on away.Name like ?\
			inner join NFLTeams home\
				on home.Name like ?\
		where state.State = ?;';
	var params = [game.GameID, game.Date, game.Time, game.SeasonYear,
		game.SeasonType, game.SeasonWeek, game.Quarter, game.AwayScore,
		game.HomeScore, game.AwayTeamName, game.HomeTeamName, game.State];
	return {
		sql: stmnt,
		inserts: params
	};
};

var lastGameInstanceQuery = function(game) {
	var stmnt =
		'Select\
			game.GameID\
		,	game.Date\
		,	state.State\
		,	game.SeasonYear\
		,	game.SeasonType\
		,	game.SeasonWeek\
		,	game.Time\
		,	game.Quarter\
		,	away.City as AwayTeamCity\
		,	away.Name as AwayTeamName\
		,	away.DisplayName as AwayTeamDisplayName\
		,	away.TwitterAccount as AwayTwitterAccount\
		,	away.TwitterHashtag as AwayTwitterHashtag\
		,	game.AwayScore\
		,	home.City as HomeTeamCity\
		,	home.Name as HomeTeamName\
		,	home.DisplayName as HomeTeamDisplayName\
		,	home.TwitterAccount as HomeTwitterAccount\
		,	home.TwitterHashtag as HomeTwitterHashtag\
		,	game.HomeScore\
		from NFLGameInstances game\
			inner join NFLStates state\
				on state.StateID = game.StateID\
			inner join NFLTeams away\
				on away.TeamID = game.AwayTeamID\
			inner join NFLTeams home\
				on home.TeamID = game.HomeTeamID\
		where GameID = ? order by ?? desc limit 1;';
	var params = [game.GameID, 'RecordedOn'];
	return {
		sql: stmnt,
		inserts: params
	};
};

module.exports.leagueInfo = leagueInfo;
module.exports.getGameArray = getGameArray;
module.exports.parseRawGame = parseRawGame;
module.exports.gameChanged = gameChanged;
module.exports.gameChangeString = gameChangeString;
module.exports.makeGameLink = makeGameLink;
module.exports.existsQuery = existsQuery;
module.exports.insertGameQuery = insertGameQuery;
module.exports.lastGameInstanceQuery = lastGameInstanceQuery;<|endoftext|>


<commit_before>import { expect } from 'chai'
import { defineSupportCode } from 'cucumber'

defineSupportCode(({ Given, When, Then }) => {
    Given('I visit {stringInDoubleQuotes}', (url) => browser.url(url))

    When('I click the clickable region', () => browser.click('#clickable'))

    Then('I should get the result: {int}', (num) => {
        const result = browser.getValue('#result')
        expect(result).to.be.equal(num.toString())
    })
})
<commit_msg>Fix assert on pending promise<commit_after>import { expect } from 'chai'
import { defineSupportCode } from 'cucumber'

defineSupportCode(({ Given, When, Then }) => {
    Given('I visit {stringInDoubleQuotes}', (url) => browser.url(url))

    When('I click the clickable region', () => browser.click('#clickable'))

    Then('I should get the result: {int}', (num) => {
        browser.getValue('#result').then((value) => {
            expect(value).to.be.equal(num.toString())
        })
    })
})
<|endoftext|>


<commit_before>var composebox_typeahead = (function () {

//************************************
// AN IMPORTANT NOTE ABOUT TYPEAHEADS
//************************************
// They do not do any HTML escaping, at all.
// And your input to them is rendered as though it were HTML by
// the default highlighter.
//
// So if you are not using trusted input, you MUST use the a
// highlighter that escapes (i.e. one that calls
// typeahead_helper.highlight_with_escaping).

var exports = {};

function get_pm_recipients(query_string) {
    // Assumes email addresses don't have commas or semicolons in them
    return query_string.split(/\s*[,;]\s*/);
}

// Returns an array of private message recipients, removing empty elements.
// For example, "a,,b, " => ["a", "b"]
exports.get_cleaned_pm_recipients = function (query_string) {
    var recipients = get_pm_recipients(query_string);
    recipients = $.grep(recipients, function (elem, idx) {
        return elem.match(/\S/);
    });
    return recipients;
};

function get_last_recipient_in_pm(query_string) {
    var recipients = get_pm_recipients(query_string);
    return recipients[recipients.length-1];
}

function composebox_typeahead_highlighter(item) {
    var query = this.query;
    if ($(this.$element).attr('id') === 'private_message_recipient') {
        // There could be multiple recipients in a private message,
        // we want to decide what to highlight based only on the most
        // recent one we're entering.
        query = get_last_recipient_in_pm(this.query);
    }
    return typeahead_helper.highlight_with_escaping(query, item);
}

// nextFocus is set on a keydown event to indicate where we should focus on keyup.
// We can't focus at the time of keydown because we need to wait for typeahead.
// And we can't compute where to focus at the time of keyup because only the keydown
// has reliable information about whether it was a tab or a shift+tab.
var nextFocus = false;

function handle_keydown(e) {
    var code = e.keyCode || e.which;

    if (code === 13 || (code === 9 && !e.shiftKey)) { // Enter key or tab key
        if (e.target.id === "stream" || e.target.id === "subject" || e.target.id === "private_message_recipient") {
            // For enter, prevent the form from submitting
            // For tab, prevent the focus from changing again
            e.preventDefault();
        }

        // In the new_message_content box, preventDefault() for tab but not for enter
        if (e.target.id === "new_message_content" && code !== 13) {
            e.preventDefault();
        }

        if (e.target.id === "stream") {
            nextFocus = "subject";
        } else if (e.target.id === "subject") {
            if (code === 13) e.preventDefault();
            nextFocus = "new_message_content";
        } else if (e.target.id === "private_message_recipient") {
            nextFocus = "new_message_content";
        } else if (e.target.id === "new_message_content") {
            if (code === 13) {
                nextFocus = false;
            } else {
                nextFocus = "compose-send-button";
            }
        } else {
            nextFocus = false;
        }

        // If no typeaheads are shown...
        if (!($("#subject").data().typeahead.shown ||
              $("#stream").data().typeahead.shown ||
              $("#private_message_recipient").data().typeahead.shown ||
              $("#new_message_content").data().typeahead.shown)) {

            // If no typeaheads are shown, then there's no need to wait and we can change
            // the focus right away.  Without this code to change the focus right away,
            // if the user presses enter before they fully release the tab key, the tab
            // will be lost.
            if (nextFocus) {
                ui.focus_on(nextFocus);
                nextFocus = false;
            }

            // If no typeaheads are shown and the user has configured enter to send,
            // then make enter send instead of inserting a line break.
            if (e.target.id === "new_message_content" && code === 13 && enter_sends) {
                e.preventDefault();
                compose.finish();
            }
        }

        return false;
    }
}

function handle_keyup(e) {
    var code = e.keyCode || e.which;
    if (code === 13 || (code === 9 && !e.shiftKey)) { // Enter key or tab key
        if (nextFocus) {
            ui.focus_on(nextFocus);
            nextFocus = false;
        }
    }
}

// http://stackoverflow.com/questions/3380458/looking-for-a-better-workaround-to-chrome-select-on-focus-bug
function select_on_focus(field_id) {
    $("#" + field_id).focus(function(e) {
        $("#" + field_id).select().one('mouseup', function (e) {
            e.preventDefault();
        });
    });
}

exports.split_at_cursor = function(query) {
    var cursor = $('#new_message_content').caret().start;
    return [query.slice(0, cursor), query.slice(cursor)];
};

exports.initialize = function () {
    select_on_focus("stream");
    select_on_focus("subject");
    select_on_focus("private_message_recipient");

    // These handlers are at the "form" level so that they are called after typeahead
    $("form#send_message_form").keydown(function(e) {
        handle_keydown(e);
    });
    $("form#send_message_form").keyup(function(e) {
        handle_keyup(e);
    });

    $("#enter_sends").click(function () {
        enter_sends = $("#enter_sends").is(":checked");
        return $.ajax({
            dataType: 'json',
            url: '/json/change_enter_sends',
            type: 'POST',
            data: {'enter_sends': enter_sends}
        });
    });
    $("#enter_sends").prop('checked', enter_sends);

    // limit number of items so the list doesn't fall off the screen
    $( "#stream" ).typeahead({
        source: function (query, process) {
            return subs.subscribed_streams();
        },
        items: 2,
        highlighter: composebox_typeahead_highlighter,
        sorter: typeahead_helper.sort_streams
    });

    $( "#subject" ).typeahead({
        source: function (query, process) {
            var stream_name = $("#stream").val();
            if (subject_dict.hasOwnProperty(stream_name)) {
                return subject_dict[stream_name];
            }
            return [];
        },
        items: 2,
        highlighter: composebox_typeahead_highlighter,
        sorter: typeahead_helper.sort_subjects
    });

    $( "#private_message_recipient" ).typeahead({
        source: typeahead_helper.private_message_typeahead_list,
        items: 2,
        highlighter: composebox_typeahead_highlighter,
        matcher: function (item) {
            var current_recipient = get_last_recipient_in_pm(this.query);
            // If the name is only whitespace (does not contain any non-whitespace),
            // we're between typing names; don't autocomplete anything for us.
            if (! current_recipient.match(/\S/)) {
                return false;
            }

            // Case-insensitive.
            return (item.toLowerCase().indexOf(current_recipient.toLowerCase()) !== -1);
        },
        sorter: typeahead_helper.sort_recipientbox_typeahead,
        updater: function (item) {
            var previous_recipients = exports.get_cleaned_pm_recipients(this.query);
            previous_recipients.pop();
            previous_recipients = previous_recipients.join(", ");
            if (previous_recipients.length !== 0) {
                previous_recipients += ", ";
            }
            return previous_recipients + typeahead_helper.private_message_mapped[item].email + ", ";
        },
        stopAdvance: true // Do not advance to the next field on a tab or enter
    });

    $( "#new_message_content" ).typeahead({
        source: typeahead_helper.private_message_typeahead_list,
        items: 2,
        highlighter: composebox_typeahead_highlighter,
        matcher: function (item) {
            var query = exports.split_at_cursor(this.query)[0];

            var strings = query.split(/[\s*(){}\[\]]/);
            if (strings.length < 1) {
                return false;
            }
            var current_recipient = strings[strings.length-1];
            if (current_recipient.length < 2 || current_recipient.charAt(0) !== "@") {
                return false;
            }
            current_recipient = current_recipient.substring(1);

            // Case-insensitive.
            return (item.toLowerCase().indexOf(current_recipient.toLowerCase()) !== -1);
        },
        sorter: typeahead_helper.sort_textbox_typeahead,
        updater: function (item) {
            var pieces = exports.split_at_cursor(this.query);
            var beginning = pieces[0];
            var rest = pieces[1];

            beginning = beginning.replace(/@\S+$/, "") + "@**" + typeahead_helper.private_message_mapped[item].full_name + "**";
            // Keep the cursor after the newly inserted name, as Bootstrap will call textbox.change() to overwrite the text
            // in the textbox.
            setTimeout(function () {
                $('#new_message_content').caret(beginning.length, beginning.length);
            }, 0);
            return beginning + rest;
        },
        stopAdvance: true // Do not advance to the next field on a tab or enter
    });

    $( "#private_message_recipient" ).blur(function (event) {
        var val = $(this).val();
        var recipients = exports.get_cleaned_pm_recipients(val);
        $(this).val(recipients.join(", "));
    });

    typeahead_helper.update_autocomplete();
};

return exports;

}());
<commit_msg>Cause shift-enter to insert a newline, even if enter sends.<commit_after>var composebox_typeahead = (function () {

//************************************
// AN IMPORTANT NOTE ABOUT TYPEAHEADS
//************************************
// They do not do any HTML escaping, at all.
// And your input to them is rendered as though it were HTML by
// the default highlighter.
//
// So if you are not using trusted input, you MUST use the a
// highlighter that escapes (i.e. one that calls
// typeahead_helper.highlight_with_escaping).

var exports = {};

function get_pm_recipients(query_string) {
    // Assumes email addresses don't have commas or semicolons in them
    return query_string.split(/\s*[,;]\s*/);
}

// Returns an array of private message recipients, removing empty elements.
// For example, "a,,b, " => ["a", "b"]
exports.get_cleaned_pm_recipients = function (query_string) {
    var recipients = get_pm_recipients(query_string);
    recipients = $.grep(recipients, function (elem, idx) {
        return elem.match(/\S/);
    });
    return recipients;
};

function get_last_recipient_in_pm(query_string) {
    var recipients = get_pm_recipients(query_string);
    return recipients[recipients.length-1];
}

function composebox_typeahead_highlighter(item) {
    var query = this.query;
    if ($(this.$element).attr('id') === 'private_message_recipient') {
        // There could be multiple recipients in a private message,
        // we want to decide what to highlight based only on the most
        // recent one we're entering.
        query = get_last_recipient_in_pm(this.query);
    }
    return typeahead_helper.highlight_with_escaping(query, item);
}

// nextFocus is set on a keydown event to indicate where we should focus on keyup.
// We can't focus at the time of keydown because we need to wait for typeahead.
// And we can't compute where to focus at the time of keyup because only the keydown
// has reliable information about whether it was a tab or a shift+tab.
var nextFocus = false;

function handle_keydown(e) {
    var code = e.keyCode || e.which;

    if (code === 13 || (code === 9 && !e.shiftKey)) { // Enter key or tab key
        if (e.target.id === "stream" || e.target.id === "subject" || e.target.id === "private_message_recipient") {
            // For enter, prevent the form from submitting
            // For tab, prevent the focus from changing again
            e.preventDefault();
        }

        // In the new_message_content box, preventDefault() for tab but not for enter
        if (e.target.id === "new_message_content" && code !== 13) {
            e.preventDefault();
        }

        if (e.target.id === "stream") {
            nextFocus = "subject";
        } else if (e.target.id === "subject") {
            if (code === 13) e.preventDefault();
            nextFocus = "new_message_content";
        } else if (e.target.id === "private_message_recipient") {
            nextFocus = "new_message_content";
        } else if (e.target.id === "new_message_content") {
            if (code === 13) {
                nextFocus = false;
            } else {
                nextFocus = "compose-send-button";
            }
        } else {
            nextFocus = false;
        }

        // If no typeaheads are shown...
        if (!($("#subject").data().typeahead.shown ||
              $("#stream").data().typeahead.shown ||
              $("#private_message_recipient").data().typeahead.shown ||
              $("#new_message_content").data().typeahead.shown)) {

            // If no typeaheads are shown, then there's no need to wait and we can change
            // the focus right away.  Without this code to change the focus right away,
            // if the user presses enter before they fully release the tab key, the tab
            // will be lost.
            if (nextFocus) {
                ui.focus_on(nextFocus);
                nextFocus = false;
            }

            // If no typeaheads are shown and the user has configured enter to send,
            // then make enter send instead of inserting a line break.
            // (Unless shift is being held down, which we *do* want to insert a linebreak)
            if (e.target.id === "new_message_content"
                && code === 13 && !e.shiftKey
                && enter_sends) {
                e.preventDefault();
                compose.finish();
            }
        }

        return false;
    }
}

function handle_keyup(e) {
    var code = e.keyCode || e.which;
    if (code === 13 || (code === 9 && !e.shiftKey)) { // Enter key or tab key
        if (nextFocus) {
            ui.focus_on(nextFocus);
            nextFocus = false;
        }
    }
}

// http://stackoverflow.com/questions/3380458/looking-for-a-better-workaround-to-chrome-select-on-focus-bug
function select_on_focus(field_id) {
    $("#" + field_id).focus(function(e) {
        $("#" + field_id).select().one('mouseup', function (e) {
            e.preventDefault();
        });
    });
}

exports.split_at_cursor = function(query) {
    var cursor = $('#new_message_content').caret().start;
    return [query.slice(0, cursor), query.slice(cursor)];
};

exports.initialize = function () {
    select_on_focus("stream");
    select_on_focus("subject");
    select_on_focus("private_message_recipient");

    // These handlers are at the "form" level so that they are called after typeahead
    $("form#send_message_form").keydown(function(e) {
        handle_keydown(e);
    });
    $("form#send_message_form").keyup(function(e) {
        handle_keyup(e);
    });

    $("#enter_sends").click(function () {
        enter_sends = $("#enter_sends").is(":checked");
        return $.ajax({
            dataType: 'json',
            url: '/json/change_enter_sends',
            type: 'POST',
            data: {'enter_sends': enter_sends}
        });
    });
    $("#enter_sends").prop('checked', enter_sends);

    // limit number of items so the list doesn't fall off the screen
    $( "#stream" ).typeahead({
        source: function (query, process) {
            return subs.subscribed_streams();
        },
        items: 2,
        highlighter: composebox_typeahead_highlighter,
        sorter: typeahead_helper.sort_streams
    });

    $( "#subject" ).typeahead({
        source: function (query, process) {
            var stream_name = $("#stream").val();
            if (subject_dict.hasOwnProperty(stream_name)) {
                return subject_dict[stream_name];
            }
            return [];
        },
        items: 2,
        highlighter: composebox_typeahead_highlighter,
        sorter: typeahead_helper.sort_subjects
    });

    $( "#private_message_recipient" ).typeahead({
        source: typeahead_helper.private_message_typeahead_list,
        items: 2,
        highlighter: composebox_typeahead_highlighter,
        matcher: function (item) {
            var current_recipient = get_last_recipient_in_pm(this.query);
            // If the name is only whitespace (does not contain any non-whitespace),
            // we're between typing names; don't autocomplete anything for us.
            if (! current_recipient.match(/\S/)) {
                return false;
            }

            // Case-insensitive.
            return (item.toLowerCase().indexOf(current_recipient.toLowerCase()) !== -1);
        },
        sorter: typeahead_helper.sort_recipientbox_typeahead,
        updater: function (item) {
            var previous_recipients = exports.get_cleaned_pm_recipients(this.query);
            previous_recipients.pop();
            previous_recipients = previous_recipients.join(", ");
            if (previous_recipients.length !== 0) {
                previous_recipients += ", ";
            }
            return previous_recipients + typeahead_helper.private_message_mapped[item].email + ", ";
        },
        stopAdvance: true // Do not advance to the next field on a tab or enter
    });

    $( "#new_message_content" ).typeahead({
        source: typeahead_helper.private_message_typeahead_list,
        items: 2,
        highlighter: composebox_typeahead_highlighter,
        matcher: function (item) {
            var query = exports.split_at_cursor(this.query)[0];

            var strings = query.split(/[\s*(){}\[\]]/);
            if (strings.length < 1) {
                return false;
            }
            var current_recipient = strings[strings.length-1];
            if (current_recipient.length < 2 || current_recipient.charAt(0) !== "@") {
                return false;
            }
            current_recipient = current_recipient.substring(1);

            // Case-insensitive.
            return (item.toLowerCase().indexOf(current_recipient.toLowerCase()) !== -1);
        },
        sorter: typeahead_helper.sort_textbox_typeahead,
        updater: function (item) {
            var pieces = exports.split_at_cursor(this.query);
            var beginning = pieces[0];
            var rest = pieces[1];

            beginning = beginning.replace(/@\S+$/, "") + "@**" + typeahead_helper.private_message_mapped[item].full_name + "**";
            // Keep the cursor after the newly inserted name, as Bootstrap will call textbox.change() to overwrite the text
            // in the textbox.
            setTimeout(function () {
                $('#new_message_content').caret(beginning.length, beginning.length);
            }, 0);
            return beginning + rest;
        },
        stopAdvance: true // Do not advance to the next field on a tab or enter
    });

    $( "#private_message_recipient" ).blur(function (event) {
        var val = $(this).val();
        var recipients = exports.get_cleaned_pm_recipients(val);
        $(this).val(recipients.join(", "));
    });

    typeahead_helper.update_autocomplete();
};

return exports;

}());
<|endoftext|>


<commit_before>(function() { define(['zepto', 'marked', 'db', 'list', 'status', 'uploader'], function($, marked, dbEngine, list, status, uploader) {

  var root = window.location.protocol + "//" + window.location.host;

  Date.prototype.format = function(format) {
    var o = {
      "M+" : this.getMonth()+1, //month
      "d+" : this.getDate(),    //day
      "h+" : this.getHours(),   //hour
      "m+" : this.getMinutes(), //minute
      "s+" : this.getSeconds(), //second
      "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
      "S" : this.getMilliseconds() //millisecond
    }

    if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
      (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)if(new RegExp("("+ k +")").test(format))
      format = format.replace(RegExp.$1,
        RegExp.$1.length==1 ? o[k] :
          ("00"+ o[k]).substr((""+ o[k]).length));
    return format;
  };

  var scrollTop = function() {
    var hTop = $('html').scrollTop();
    return hTop === 0 ? $('body').scrollTop() : hTop;
  };

  var range = function(el) {
    return $.parseJSON(el.attr('data-range'));
  };

  var heading = /^\s*(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/;
  var lheading = /^([^\n]+)\n *(=|-){3,} *\n*/;
  var getTitle = function(md) {
    var cap;
    if (cap = heading.exec(md)) {
      return cap[2];
    }
    if (cap = lheading.exec(md)) {
      return cap[1];
    }
    var title = md.substr(0, 64);
    if ($.trim(title) === '') {
      return new Date().format("yyyy-MM-dd h:mm:ss");
    }
    return title;
  };

  var getCMMode = (function () {
    var aliases = {
      html: "htmlmixed",
      js: "javascript",
      json: "application/json",
      c: "text/x-csrc",
      "c++": "text/x-c++src",
      java: "text/x-java",
      csharp: "text/x-csharp",
      "c#": "text/x-csharp",
      scala: "text/x-scala"
    };

    var i, modes = {}, mimes = {}, mime;

    var list = [];
    for (var m in CodeMirror.modes)
      if (CodeMirror.modes.propertyIsEnumerable(m)) list.push(m);
    for (i = 0; i < list.length; i++) {
      modes[list[i]] = list[i];
    }
    var mimesList = [];
    for (var m in CodeMirror.mimeModes)
      if (CodeMirror.mimeModes.propertyIsEnumerable(m))
        mimesList.push({mime: m, mode: CodeMirror.mimeModes[m]});
    for (i = 0; i < mimesList.length; i++) {
      mime = mimesList[i].mime;
      mimes[mime] = mimesList[i].mime;
    }

    for (var a in aliases) {
      if (aliases[a] in modes || aliases[a] in mimes)
        modes[a] = aliases[a];
    }

    return function (lang) {
      return CodeMirror.getMode({}, modes[lang]);
    };
  }());

  var setupWorker = function(met) {
    var worker = new Worker(root +"/javascripts/apps/worker.js");
    worker.addEventListener('message', function(e) {
      switch (e.data.type) {
        case 'result': {
          var doc = document.implementation.createHTMLDocument('');
          doc.documentElement.innerHTML = '
' + e.data.text + '
';
          var result = $(doc).find('#__met_dummydummy__ > .marked-block').length;
          var current = $(met.mbsa).length;
          if (result !== current) {
            met.needFullRender = true;
          }
          break;
        }
        case 'request': {
          worker.postMessage({cmd: 'parse', text: met.editor.getValue()});
          break;
        }
      }
    }, false);
    worker.postMessage({cmd: 'parse', text: met.editor.getValue()});
  };

  var MeT = function(inputArea, previewArea, inputWrapper, previewWrapper, listArea, statusArea) {
    var self = this;
    this.inputArea = inputArea;
    this.previewArea = previewArea;
    this.inputWrapper = inputWrapper;
    this.previewWrapper = previewWrapper;
    this.listArea = listArea;
    this.statusArea = statusArea;
    this.mbsa = previewArea + ' > .marked-block';
    this.area = $(inputArea)[0];
    this.preview = $(previewArea);
    this.editor = CodeMirror.fromTextArea(self.area, {
      mode: 'gfm',
      theme: 'default',
      tabSize: 2,
      autofocus: true,
      lineNumbers: false,
      lineWrapping: true,
      matchBrackets: true,
      showTrailingSpace: true,
      dragDrop: false,
      extraKeys: {
        Tab: function(cm) {
          if (cm.getSelection().length === 0) {
            var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
            cm.replaceSelection(spaces, "end", "+input");
          } else {
            CodeMirror.commands.indentMore(cm);
          }
        }
      }
    });
    this.needFullRender = false;
    this.editorMarker = null;

    var newTop = function(h1, t1, h2, t2, m) {
      // moving h1 t1 to match h2 t2
      var top = (h2 + t2) - (h1 + t1) + t1;
      return (top >= m ? m : top);
    };

    var topPadding = parseInt($(self.previewWrapper).css('padding-top'));

    var syncTwo = function(sy1, sy2) {
      var sTop = scrollTop();
      sTop = sTop - topPadding > 0 ? sTop - topPadding : sTop;
      var top = newTop(sy1.h, sy1.t, sy2.h, sy2.t, sTop);
      $(sy1.sel).animate({top: top}, 300);
    };

    var lastTrackedRange = [0,0];
    var lastTrackedCursor = -1;

    self.editor.on('cursorActivity', function(cm) {
      var pos = cm.indexFromPos(cm.getCursor());
      if (pos === lastTrackedCursor) {
        return false;
      }
      lastTrackedCursor = pos;
      $(self.mbsa).each(function (i, v) {
        var b = $(v), r = range(b);
        if (r[0] <= pos && pos <= r[1]) {
          if (lastTrackedRange[0] === r[0] && lastTrackedRange[1] === r[1]) {
            return false;
          }
          clearMarker();
          b.addClass('block-current');
          var h1 = b.position().top;
          var t1 = $(self.previewWrapper).position().top;
          var h2 = self.editor.charCoords(self.editor.posFromIndex(r[0]), 'local').top;
          var t2 = $(self.inputWrapper).position().top;
          syncTwo({h: h1, t: t1, sel: self.previewWrapper}, {h: h2, t: t2, sel: self.inputWrapper});
          lastTrackedRange = r;
          return false;
        }
      });
    });

    self.preview.on('click', 'a', function(evt) {
      window.open($(this).attr('href'), '_blank');
      evt.stopPropagation(); // Zepto doesn't work
    });

    self.preview.on('click', self.mbsa, function(evt) {
      evt.preventDefault();
      var r = range($(this));
      if (lastTrackedRange[0] === r[0] && lastTrackedRange[1] === r[1]) {
        return;
      }
      clearMarker();
      $(this).addClass('block-current');
      var posTop = self.editor.posFromIndex(r[0]);
      var posBottom = self.editor.posFromIndex(r[1]);
      var h1 = self.editor.charCoords(posTop, 'local').top;
      var t1 = $(self.inputWrapper).position().top;
      var h2 = $(this).position().top;
      var t2 = $(self.previewWrapper).position().top;
      syncTwo({h: h1, t: t1, sel: self.inputWrapper}, {h: h2, t: t2, sel: self.previewWrapper});
      lastTrackedRange = r;
      self.editorMarker = self.editor.markText(posTop, posBottom, {className: 'block-current', clearOnEnter: true});
    });

    $(document).on('scroll', function(evt) {
      evt.preventDefault();
      var sTop = scrollTop();
      var posV = $(self.previewWrapper).position().top;
      var posE = $(self.inputWrapper).position().top;
      sTop = sTop - topPadding > 0 ? sTop - topPadding : sTop;
      if ((sTop === 0 && posV < 0) || posV >= sTop) {
        $(self.previewWrapper).animate({top: sTop}, 'fast');
      }
      if ((sTop === 0 && posE < 0) || posE >= sTop) {
        $(self.inputWrapper).animate({top: sTop}, 'fast');
      }
    });

    self.preview.on('mouseenter', self.mbsa, function() {
      $(this).addClass('block-highlight');
    });
    self.preview.on('mouseleave', self.mbsa, function() {
      $(this).removeClass('block-highlight');
    });

    var clearMarker = function() {
      if (self.editorMarker !== null) self.editorMarker.clear();
      $(self.mbsa).removeClass('block-current');
    };

  };

  MeT.prototype.getEditor = function() {
    return this.editor;
  };

  MeT.prototype.loadLastPost = function(self) {
    self.currentPost = {};
    self.db.getPosts(function(posts) {
      var post = posts.slice(-1)[0];
      if (typeof post !== 'undefined') {
        self.currentPost = post;
        self.editor.setValue(self.currentPost.content);
        self.editor.clearHistory();
      } else {
        $.get(root + '/docs/index.md', function(md){
          self.editor.setValue(md);
          self.editor.clearHistory();
        });
      }
    });
  };

  MeT.prototype.newPost = function(callback) {
    this.currentPost = {};
    this.editor.setValue('');
    this.editor.clearHistory();
    callback();
  };

  MeT.prototype.loadPost = function(key, callback) {
    var self = this;
    if (key !== self.currentPost.created_at) {
      self.db.getPost({created_at: key}, function(p) {
        self.currentPost = p;
        self.editor.setValue(self.currentPost.content);
        self.editor.clearHistory();
        callback();
      });
    }
  };

  MeT.prototype.deletePost = function(key, callback) {
    var self = this;
    self.db.deletePost({created_at: key}, function() {
      self.loadLastPost(self);
      callback();
    });
  };

  MeT.prototype.saveChanges = function() {
    var self = this;
    if (self.editor.getValue() !== self.currentPost.content) {
      $.extend(self.currentPost, {
        title:  getTitle(self.editor.getValue()),
        content: self.editor.getValue()
      });
      self.db.putPost(self.currentPost, function(key) {
        self.currentPost.created_at = key;
      });
    }
  };

  MeT.prototype.met = function() {
    var self = this;
    dbEngine.init(function(db) {
      self.db = db;
      self._met();
      list(self.listArea, self);
      status(self.statusArea, self);
      uploader(self.inputWrapper, self);
    });
    return self;
  };

  MeT.prototype._met = function() {
    var self = this;
    var mbsa = self.mbsa;
    var preview = self.preview;
    var editor = self.editor;

    setupWorker(self);
    marked.setOptions({
      gfm: true,
      tables: true,
      breaks: false,
      blocks: true,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: true,
      langPrefix: 'lang-',
      highlight: function(code, lang) {
        var div = $('
');
        CodeMirror.runMode(code, getCMMode(lang), div[0]);
        return '' + div.html() + '';
      }
    });

    self.loadLastPost(self);
    editor.on('change', function(cm, change) {
      self.saveChanges();
      preview = $(self.previewArea);
      if (preview.length === 0) {
        return;
      }

      var blocks = $(mbsa);
      var from = -1, to = -1, relative = 0, baseBlock = null;

      if (self.needFullRender || blocks.length === 0) {
        preview.html(marked(cm.getValue()));
        MathJax.Hub.Queue(["Typeset",MathJax.Hub, preview[0]]);
        self.needFullRender = false;
        return;
      }

      var base = range($(blocks[0]))[0];
      if (base > 0) {
        baseBlock = $('

');
        baseBlock.hide().insertBefore($(blocks[0]));
        blocks = $(mbsa);
      }

      do {
        var removed = change.removed.join("\n");
        var text = change.text.join("\n");
        var f = cm.indexFromPos(change.from);
        var t = f + removed.length;
        if (from < 0 || from > f) from = f;
        if (to < t) to = t;
        relative += (text.length - removed.length);
      } while (change = change.next);

      var sb = -1, eb = -1;
      for (var i = 0; i < blocks.length; i++) {
        var block = $(blocks[i]);
        if (range(block)[0] <= from && from <= range(block)[1]) {
          sb = i;
        }

        if (range(block)[0] <= to && to <= range(block)[1]) {
          eb = i;
        }

        if (i === blocks.length - 1) {
          if (eb < 0) eb = i;
          if (sb < 0) sb = i;
        }

        if (sb < 0 || eb < 0) {
          continue;
        }

        if (sb - 1 >= 0) sb = sb - 1;
        if (eb + 1 < blocks.length) eb = eb + 1;
        var startBlock = $(blocks[sb]), endBlock = $(blocks[eb]);
        var md = cm.getRange(cm.posFromIndex(range(startBlock)[0]), cm.posFromIndex(range(endBlock)[1] + relative + 1));

        marked(md, {}, function(err, htmlOut) {
          if (err !== null) {
            console.log("Markdown parse error: " + err);
            return;
          }
          for (i = sb + 1; i <= eb; i++) {
            blocks[i].remove();
          }
          startBlock.replaceWith(htmlOut);
          MathJax.Hub.Queue(["Typeset",MathJax.Hub, preview[0]]); // TODO should make the changed maths reproduce only?

          blocks = $(mbsa);
          if (blocks.length !== 0) {
            $.each(blocks, function (i, v) {
              var block = $(v);
              if (i > 0) {
                var prev = $(blocks[i-1]);
                if (range(block)[0] !== range(prev)[1] + 1) {
                  var begin = range(prev)[1] + 1;
                  var end = begin - range(block)[0] + range(block)[1];
                  block.attr('data-range', '[' + [begin, end] + ']');
                }
              }
            });
          }

          if (baseBlock !== null) {
            baseBlock.remove();
          }

        });

        break;
      } // for blocks

    }); // editor.on('change')
  };

  return function(input, preview, inputWrapper, previewWrapper, listArea, statusArea) {
    return new MeT(input, preview, inputWrapper, previewWrapper, listArea, statusArea).met();
  };

}); }());
<commit_msg>Make the preview and editor top in the same line by 16 pixels<commit_after>(function() { define(['zepto', 'marked', 'db', 'list', 'status', 'uploader'], function($, marked, dbEngine, list, status, uploader) {

  var root = window.location.protocol + "//" + window.location.host;

  Date.prototype.format = function(format) {
    var o = {
      "M+" : this.getMonth()+1, //month
      "d+" : this.getDate(),    //day
      "h+" : this.getHours(),   //hour
      "m+" : this.getMinutes(), //minute
      "s+" : this.getSeconds(), //second
      "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
      "S" : this.getMilliseconds() //millisecond
    }

    if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
      (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)if(new RegExp("("+ k +")").test(format))
      format = format.replace(RegExp.$1,
        RegExp.$1.length==1 ? o[k] :
          ("00"+ o[k]).substr((""+ o[k]).length));
    return format;
  };

  var scrollTop = function() {
    var hTop = $('html').scrollTop();
    return hTop === 0 ? $('body').scrollTop() : hTop;
  };

  var range = function(el) {
    return $.parseJSON(el.attr('data-range'));
  };

  var heading = /^\s*(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/;
  var lheading = /^([^\n]+)\n *(=|-){3,} *\n*/;
  var getTitle = function(md) {
    var cap;
    if (cap = heading.exec(md)) {
      return cap[2];
    }
    if (cap = lheading.exec(md)) {
      return cap[1];
    }
    var title = md.substr(0, 64);
    if ($.trim(title) === '') {
      return new Date().format("yyyy-MM-dd h:mm:ss");
    }
    return title;
  };

  var getCMMode = (function () {
    var aliases = {
      html: "htmlmixed",
      js: "javascript",
      json: "application/json",
      c: "text/x-csrc",
      "c++": "text/x-c++src",
      java: "text/x-java",
      csharp: "text/x-csharp",
      "c#": "text/x-csharp",
      scala: "text/x-scala"
    };

    var i, modes = {}, mimes = {}, mime;

    var list = [];
    for (var m in CodeMirror.modes)
      if (CodeMirror.modes.propertyIsEnumerable(m)) list.push(m);
    for (i = 0; i < list.length; i++) {
      modes[list[i]] = list[i];
    }
    var mimesList = [];
    for (var m in CodeMirror.mimeModes)
      if (CodeMirror.mimeModes.propertyIsEnumerable(m))
        mimesList.push({mime: m, mode: CodeMirror.mimeModes[m]});
    for (i = 0; i < mimesList.length; i++) {
      mime = mimesList[i].mime;
      mimes[mime] = mimesList[i].mime;
    }

    for (var a in aliases) {
      if (aliases[a] in modes || aliases[a] in mimes)
        modes[a] = aliases[a];
    }

    return function (lang) {
      return CodeMirror.getMode({}, modes[lang]);
    };
  }());

  var setupWorker = function(met) {
    var worker = new Worker(root +"/javascripts/apps/worker.js");
    worker.addEventListener('message', function(e) {
      switch (e.data.type) {
        case 'result': {
          var doc = document.implementation.createHTMLDocument('');
          doc.documentElement.innerHTML = '
' + e.data.text + '
';
          var result = $(doc).find('#__met_dummydummy__ > .marked-block').length;
          var current = $(met.mbsa).length;
          if (result !== current) {
            met.needFullRender = true;
          }
          break;
        }
        case 'request': {
          worker.postMessage({cmd: 'parse', text: met.editor.getValue()});
          break;
        }
      }
    }, false);
    worker.postMessage({cmd: 'parse', text: met.editor.getValue()});
  };

  var MeT = function(inputArea, previewArea, inputWrapper, previewWrapper, listArea, statusArea) {
    var self = this;
    this.inputArea = inputArea;
    this.previewArea = previewArea;
    this.inputWrapper = inputWrapper;
    this.previewWrapper = previewWrapper;
    this.listArea = listArea;
    this.statusArea = statusArea;
    this.mbsa = previewArea + ' > .marked-block';
    this.area = $(inputArea)[0];
    this.preview = $(previewArea);
    this.editor = CodeMirror.fromTextArea(self.area, {
      mode: 'gfm',
      theme: 'default',
      tabSize: 2,
      autofocus: true,
      lineNumbers: false,
      lineWrapping: true,
      matchBrackets: true,
      showTrailingSpace: true,
      dragDrop: false,
      extraKeys: {
        Tab: function(cm) {
          if (cm.getSelection().length === 0) {
            var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
            cm.replaceSelection(spaces, "end", "+input");
          } else {
            CodeMirror.commands.indentMore(cm);
          }
        }
      }
    });
    this.needFullRender = false;
    this.editorMarker = null;

    var newTop = function(h1, t1, h2, t2, m) {
      // moving h1 t1 to match h2 t2
      var top = (h2 + t2) - (h1 + t1) + t1;
      return (top >= m ? m : top);
    };

    var topPadding = parseInt($(self.previewWrapper).css('padding-top'));

    var syncTwo = function(sy1, sy2) {
      var sTop = scrollTop();
      sTop = sTop - topPadding > 0 ? sTop - topPadding : sTop;
      var top = newTop(sy1.h, sy1.t, sy2.h, sy2.t, sTop);
      $(sy1.sel).animate({top: top}, 300);
    };

    var lastTrackedRange = [0,0];
    var lastTrackedCursor = -1;

    self.editor.on('cursorActivity', function(cm) {
      var pos = cm.indexFromPos(cm.getCursor());
      if (pos === lastTrackedCursor) {
        return false;
      }
      lastTrackedCursor = pos;
      $(self.mbsa).each(function (i, v) {
        var b = $(v), r = range(b);
        if (r[0] <= pos && pos <= r[1]) {
          if (lastTrackedRange[0] === r[0] && lastTrackedRange[1] === r[1]) {
            return false;
          }
          clearMarker();
          b.addClass('block-current');
          var h1 = b.position().top - 16; // use the 16 to make the preview lower
          var t1 = $(self.previewWrapper).position().top;
          var h2 = self.editor.charCoords(self.editor.posFromIndex(r[0]), 'local').top;
          var t2 = $(self.inputWrapper).position().top;
          syncTwo({h: h1, t: t1, sel: self.previewWrapper}, {h: h2, t: t2, sel: self.inputWrapper});
          lastTrackedRange = r;
          return false;
        }
      });
    });

    self.preview.on('click', 'a', function(evt) {
      window.open($(this).attr('href'), '_blank');
      evt.stopPropagation(); // Zepto doesn't work
    });

    self.preview.on('click', self.mbsa, function(evt) {
      evt.preventDefault();
      var r = range($(this));
      if (lastTrackedRange[0] === r[0] && lastTrackedRange[1] === r[1]) {
        return;
      }
      clearMarker();
      $(this).addClass('block-current');
      var posTop = self.editor.posFromIndex(r[0]);
      var posBottom = self.editor.posFromIndex(r[1]);
      var h1 = self.editor.charCoords(posTop, 'local').top;
      var t1 = $(self.inputWrapper).position().top;
      var h2 = $(this).position().top - 16;
      var t2 = $(self.previewWrapper).position().top;
      syncTwo({h: h1, t: t1, sel: self.inputWrapper}, {h: h2, t: t2, sel: self.previewWrapper});
      lastTrackedRange = r;
      self.editorMarker = self.editor.markText(posTop, posBottom, {className: 'block-current', clearOnEnter: true});
    });

    $(document).on('scroll', function(evt) {
      evt.preventDefault();
      var sTop = scrollTop();
      var posV = $(self.previewWrapper).position().top;
      var posE = $(self.inputWrapper).position().top;
      sTop = sTop - topPadding > 0 ? sTop - topPadding : sTop;
      if ((sTop === 0 && posV < 0) || posV >= sTop) {
        $(self.previewWrapper).animate({top: sTop}, 'fast');
      }
      if ((sTop === 0 && posE < 0) || posE >= sTop) {
        $(self.inputWrapper).animate({top: sTop}, 'fast');
      }
    });

    self.preview.on('mouseenter', self.mbsa, function() {
      $(this).addClass('block-highlight');
    });
    self.preview.on('mouseleave', self.mbsa, function() {
      $(this).removeClass('block-highlight');
    });

    var clearMarker = function() {
      if (self.editorMarker !== null) self.editorMarker.clear();
      $(self.mbsa).removeClass('block-current');
    };

  };

  MeT.prototype.getEditor = function() {
    return this.editor;
  };

  MeT.prototype.loadLastPost = function(self) {
    self.currentPost = {};
    self.db.getPosts(function(posts) {
      var post = posts.slice(-1)[0];
      if (typeof post !== 'undefined') {
        self.currentPost = post;
        self.editor.setValue(self.currentPost.content);
        self.editor.clearHistory();
      } else {
        $.get(root + '/docs/index.md', function(md){
          self.editor.setValue(md);
          self.editor.clearHistory();
        });
      }
    });
  };

  MeT.prototype.newPost = function(callback) {
    this.currentPost = {};
    this.editor.setValue('');
    this.editor.clearHistory();
    callback();
  };

  MeT.prototype.loadPost = function(key, callback) {
    var self = this;
    if (key !== self.currentPost.created_at) {
      self.db.getPost({created_at: key}, function(p) {
        self.currentPost = p;
        self.editor.setValue(self.currentPost.content);
        self.editor.clearHistory();
        callback();
      });
    }
  };

  MeT.prototype.deletePost = function(key, callback) {
    var self = this;
    self.db.deletePost({created_at: key}, function() {
      self.loadLastPost(self);
      callback();
    });
  };

  MeT.prototype.saveChanges = function() {
    var self = this;
    if (self.editor.getValue() !== self.currentPost.content) {
      $.extend(self.currentPost, {
        title:  getTitle(self.editor.getValue()),
        content: self.editor.getValue()
      });
      self.db.putPost(self.currentPost, function(key) {
        self.currentPost.created_at = key;
      });
    }
  };

  MeT.prototype.met = function() {
    var self = this;
    dbEngine.init(function(db) {
      self.db = db;
      self._met();
      list(self.listArea, self);
      status(self.statusArea, self);
      uploader(self.inputWrapper, self);
    });
    return self;
  };

  MeT.prototype._met = function() {
    var self = this;
    var mbsa = self.mbsa;
    var preview = self.preview;
    var editor = self.editor;

    setupWorker(self);
    marked.setOptions({
      gfm: true,
      tables: true,
      breaks: false,
      blocks: true,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: true,
      langPrefix: 'lang-',
      highlight: function(code, lang) {
        var div = $('
');
        CodeMirror.runMode(code, getCMMode(lang), div[0]);
        return '' + div.html() + '';
      }
    });

    self.loadLastPost(self);
    editor.on('change', function(cm, change) {
      self.saveChanges();
      preview = $(self.previewArea);
      if (preview.length === 0) {
        return;
      }

      var blocks = $(mbsa);
      var from = -1, to = -1, relative = 0, baseBlock = null;

      if (self.needFullRender || blocks.length === 0) {
        preview.html(marked(cm.getValue()));
        MathJax.Hub.Queue(["Typeset",MathJax.Hub, preview[0]]);
        self.needFullRender = false;
        return;
      }

      var base = range($(blocks[0]))[0];
      if (base > 0) {
        baseBlock = $('

');
        baseBlock.hide().insertBefore($(blocks[0]));
        blocks = $(mbsa);
      }

      do {
        var removed = change.removed.join("\n");
        var text = change.text.join("\n");
        var f = cm.indexFromPos(change.from);
        var t = f + removed.length;
        if (from < 0 || from > f) from = f;
        if (to < t) to = t;
        relative += (text.length - removed.length);
      } while (change = change.next);

      var sb = -1, eb = -1;
      for (var i = 0; i < blocks.length; i++) {
        var block = $(blocks[i]);
        if (range(block)[0] <= from && from <= range(block)[1]) {
          sb = i;
        }

        if (range(block)[0] <= to && to <= range(block)[1]) {
          eb = i;
        }

        if (i === blocks.length - 1) {
          if (eb < 0) eb = i;
          if (sb < 0) sb = i;
        }

        if (sb < 0 || eb < 0) {
          continue;
        }

        if (sb - 1 >= 0) sb = sb - 1;
        if (eb + 1 < blocks.length) eb = eb + 1;
        var startBlock = $(blocks[sb]), endBlock = $(blocks[eb]);
        var md = cm.getRange(cm.posFromIndex(range(startBlock)[0]), cm.posFromIndex(range(endBlock)[1] + relative + 1));

        marked(md, {}, function(err, htmlOut) {
          if (err !== null) {
            console.log("Markdown parse error: " + err);
            return;
          }
          for (i = sb + 1; i <= eb; i++) {
            blocks[i].remove();
          }
          startBlock.replaceWith(htmlOut);
          MathJax.Hub.Queue(["Typeset",MathJax.Hub, preview[0]]); // TODO should make the changed maths reproduce only?

          blocks = $(mbsa);
          if (blocks.length !== 0) {
            $.each(blocks, function (i, v) {
              var block = $(v);
              if (i > 0) {
                var prev = $(blocks[i-1]);
                if (range(block)[0] !== range(prev)[1] + 1) {
                  var begin = range(prev)[1] + 1;
                  var end = begin - range(block)[0] + range(block)[1];
                  block.attr('data-range', '[' + [begin, end] + ']');
                }
              }
            });
          }

          if (baseBlock !== null) {
            baseBlock.remove();
          }

        });

        break;
      } // for blocks

    }); // editor.on('change')
  };

  return function(input, preview, inputWrapper, previewWrapper, listArea, statusArea) {
    return new MeT(input, preview, inputWrapper, previewWrapper, listArea, statusArea).met();
  };

}); }());
<|endoftext|>


<commit_before>'use strict';

var tinto = {};

/**
 * @param {Boolean} outcome
 * @param {*} actual
 * @constructor
 */
tinto.AssertionResult = function AssertionResult(outcome, expected, actual) {
  this.outcome = outcome;
  this.expected = expected;
  this.actual = actual;
};

module.exports = tinto.AssertionResult;
<commit_msg>improved documentation<commit_after>'use strict';

var tinto = {};

/**
 * @param {Boolean} outcome
 * @param {*} expected
 * @param {*} actual
 * @constructor
 */
tinto.AssertionResult = function AssertionResult(outcome, expected, actual) {
  this.outcome = outcome;
  this.expected = expected;
  this.actual = actual;
};

module.exports = tinto.AssertionResult;
<|endoftext|>


<commit_before>describe('jquery-w3cdtf', function() {

  it('is a jquery plugin', function() {
    expect(typeof ($.fn.w3cdtf)).toBe('function');
  });

  it('hides the existing class and adds a div', function() {
    var wrapper = $('<div/>');
    $('body').append(wrapper);
    var initialElement = $('<input type="text" name="foo" value="1982"/>');
    wrapper.append(initialElement);
    expect($('input:hidden').length).toBe(0);
    expect($('div', wrapper).length).toBe(0);

    $(initialElement).w3cdtf({});

    expect($('input:hidden').length).toBe(1);
    expect($('div', wrapper).length).toBe(1);

    wrapper.remove();
  });

  describe('population behaviour', function() {
    var wrapper = null;
    var initialElement = null;

    beforeEach(function() {
      wrapper = $('<div/>');
      $('body').append(wrapper);
      initialElement = $('<input type="text" name="foo"/>');
      wrapper.append(initialElement);
    });

    it('should handle a single year', function() {
      initialElement.val('1985');
      $(initialElement).w3cdtf({});

      expect($('div select:eq(0)', wrapper).val()).toBe('1985');
      expect($('div select:eq(1)', wrapper).val()).toBe('');
      expect($('div select:eq(2)', wrapper).val()).toBe('');

      expect(initialElement.val()).toBe('1985');
    });

    it('should handle a year with a month', function() {
      initialElement.val('1983-08');
      $(initialElement).w3cdtf({});

      expect($('div select:eq(0)', wrapper).val()).toBe('1983');
      expect($('div select:eq(1)', wrapper).val()).toBe('08');
      expect($('div select:eq(2)', wrapper).val()).toBe('');

      expect(initialElement.val()).toBe('1983-08');
    });

    it('should handle a year, month & day', function() {
      initialElement.val('2001-09-11');
      $(initialElement).w3cdtf({});

      expect($('div select:eq(0)', wrapper).val()).toBe('2001');
      expect($('div select:eq(1)', wrapper).val()).toBe('09');
      expect($('div select:eq(2)', wrapper).val()).toBe('11');

      expect(initialElement.val()).toBe('2001-09-11');
    });

    afterEach(function() {
      wrapper.remove();
    });

  });

});<commit_msg>Added some a very basic minDate test. (Implementation currently only honours the minDate year.)<commit_after>describe('jquery-w3cdtf', function() {

  it('is a jquery plugin', function() {
    expect(typeof ($.fn.w3cdtf)).toBe('function');
  });

  describe('initialization', function() {
    var wrapper = null;
    var initialElement = null;

    beforeEach(function() {
      wrapper = $('<div/>');
      $('body').append(wrapper);
      initialElement = $('<input type="text" name="foo"/>');
      wrapper.append(initialElement);
    });

    it('hides the existing class and adds a div', function() {
      initialElement.val('1982');

      expect($('input:hidden').length).toBe(0);
      expect($('div', wrapper).length).toBe(0);

      $(initialElement).w3cdtf({});

      expect($('input:hidden').length).toBe(1);
      expect($('div', wrapper).length).toBe(1);
    });

    it('takes a minDate option', function() {
      initialElement.val('1945');

      $(initialElement).w3cdtf({
        minDate : new Date(1900, 0, 1, 0, 0, 0)
      });

      expect($('div select:eq(0)', wrapper).val()).toBe('1945');
      expect($('div select:eq(0) option:last', wrapper).text()).toBe('1900');
    });

    afterEach(function() {
      wrapper.remove();
    });

  });

  describe('population', function() {
    var wrapper = null;
    var initialElement = null;

    beforeEach(function() {
      wrapper = $('<div/>');
      $('body').append(wrapper);
      initialElement = $('<input type="text" name="foo"/>');
      wrapper.append(initialElement);
    });

    it('should handle a single year', function() {
      initialElement.val('1985');
      $(initialElement).w3cdtf({});

      expect($('div select:eq(0)', wrapper).val()).toBe('1985');
      expect($('div select:eq(1)', wrapper).val()).toBe('');
      expect($('div select:eq(2)', wrapper).val()).toBe('');

      expect(initialElement.val()).toBe('1985');
    });

    it('should handle a year with a month', function() {
      initialElement.val('1983-08');
      $(initialElement).w3cdtf({});

      expect($('div select:eq(0)', wrapper).val()).toBe('1983');
      expect($('div select:eq(1)', wrapper).val()).toBe('08');
      expect($('div select:eq(2)', wrapper).val()).toBe('');

      expect(initialElement.val()).toBe('1983-08');
    });

    it('should handle a year, month & day', function() {
      initialElement.val('2001-09-11');
      $(initialElement).w3cdtf({});

      expect($('div select:eq(0)', wrapper).val()).toBe('2001');
      expect($('div select:eq(1)', wrapper).val()).toBe('09');
      expect($('div select:eq(2)', wrapper).val()).toBe('11');

      expect(initialElement.val()).toBe('2001-09-11');
    });

    afterEach(function() {
      wrapper.remove();
    });

  });

});<|endoftext|>


<commit_before>function Storage() {
	this.store = null;

	this.init = function(key, store, onrequesterror, onrequestsuccess, onupgradeerror) {
		this.store = store || this.store;
		window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
		window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
		window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
		var dBOpenRequest = window.indexedDB.open(this.store, 1);

		dBOpenRequest.onerror = onrequesterror;

		dBOpenRequest.onsuccess = onrequestsuccess;

		dBOpenRequest.onupgradeneeded = function(event) {
			var db = event.target.result;

			db.onerror = onupgradeerror;

			var objectStore = db.createObjectStore(store, { keyPath: key });
		};
	};

	this.getData = function(store, onsuccess, oncomplete, onerror) {
		this.store = store || this.store;
		var transaction = db.transaction(this.store);
		var objectStore = transaction.objectStore(this.store);
		var result = [];

		transaction.oncomplete = oncomplete;

		transaction.onerror = onerror;

		objectStore.openCursor().onsuccess = function(event) {
			var cursor = event.target.result;
			if(cursor) {
				result.push(cursor.value);
				cursor.continue();
			} else if(onsuccess) {
				onsuccess(result);
			}
		};
	};

	this.setData = function(data, store, onsuccess, oncomplete, onerror) {
		this.store = store || this.store;
		var transaction = db.transaction([this.store], "readwrite");

		transaction.oncomplete = oncomplete;
		transaction.onerror = onerror;
		transaction.objectStore(this.store).add(data).onsuccess = onsuccess;
	};

	this.deleteData = function(key, store, onsuccess, oncomplete, onerror) {
		this.store = store || this.store;
		var transaction = db.transaction([this.store], "readwrite");

		transaction.onerror = onerror;
		transaction.oncomplete = oncomplete;
		transaction.objectStore(this.store).delete(key).onsuccess = onsuccess;
	};
}<commit_msg>IndexedDB<commit_after>function Storage() {
	this.store = null;
	this.db = null;

	this.init = function(key, store, onrequesterror, onrequestsuccess, onupgradeerror) {
		this.store = store || this.store;
		window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
		window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
		window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
		var dBOpenRequest = window.indexedDB.open(this.store, 1);

		dBOpenRequest.onerror = onrequesterror;

		dBOpenRequest.onsuccess = onrequestsuccess;

		dBOpenRequest.onupgradeneeded = function(event) {
			this.db = event.target.result;
			this.db.onerror = onupgradeerror;
			var objectStore = this.db.createObjectStore(store, { keyPath: key });
		};
	};

	this.getData = function(store, onsuccess, oncomplete, onerror) {
		this.store = store || this.store;
		var transaction = this.db.transaction(this.store);
		var objectStore = transaction.objectStore(this.store);
		var result = [];

		transaction.oncomplete = oncomplete;

		transaction.onerror = onerror;

		objectStore.openCursor().onsuccess = function(event) {
			var cursor = event.target.result;
			if(cursor) {
				result.push(cursor.value);
				cursor.continue();
			} else if(onsuccess) {
				onsuccess(result);
			}
		};
	};

	this.setData = function(data, store, onsuccess, oncomplete, onerror) {
		this.store = store || this.store;
		var transaction = this.db.transaction([this.store], "readwrite");

		transaction.oncomplete = oncomplete;
		transaction.onerror = onerror;
		transaction.objectStore(this.store).add(data).onsuccess = onsuccess;
	};

	this.deleteData = function(key, store, onsuccess, oncomplete, onerror) {
		this.store = store || this.store;
		var transaction = this.db.transaction([this.store], "readwrite");

		transaction.onerror = onerror;
		transaction.oncomplete = oncomplete;
		transaction.objectStore(this.store).delete(key).onsuccess = onsuccess;
	};
}<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  classNames: 'spectrum-color-picker',

  tagName: 'input',

  color: null,

  flatMode: false,

  allowEmpty: false,

  disabled: false,

  showInput: false,

  showAlpha: false,

  showInitial: false,

  showButtons: true,

  showPalette: false,

  showPaletteOnly: false,

  palette: [],

  togglePaletteOnly: false,

  showSelectionPalette: false,

  hideAfterPaletteSelect: false,

  preferredFormat: null,

  moveFiresChange: false,

  clickoutFiresChange: false,

  chooseText: 'Choose',

  cancelText: 'Cancel',

  togglePaletteMoreText: 'More',

  togglePaletteLessText: 'Less',

  appendTo: 'body',

  localStorageKey: 'spectrum-color-picker',

  updatePicker: Ember.observer('color', function () {
    this.$().spectrum('set', this.get('color'));
  }),

  updateDisabled: Ember.observer('disabled', function () {
    this.$().spectrum(this.get('disabled') ? 'disable' : 'enable');
  }),

  didInsertElement() {
    let palette = this.get('palette');
    let opts = {
      color: this.get('color'),
      flat: this.get('flatMode'),
      allowEmpty: this.get('allowEmpty'),
      disabled: this.get('disabled'),
      showInput: this.get('showInput'),
      showAlpha: this.get('showAlpha'),
      showInitial: this.get('showInitial'),
      showButtons: this.get('showButtons'),
      showPalette: this.get('showPalette'),
      showPaletteOnly: this.get('showPaletteOnly'),
      palette: (typeof(palette) === 'string') ? JSON.parse(palette) : palette,
      togglePaletteOnly: this.get('togglePaletteOnly'),
      showSelectionPalette: this.get('showSelectionPalette'),
      hideAfterPaletteSelect: this.get('hideAfterPaletteSelect'),
      preferredFormat: this.get('preferredFormat'),
      clickoutFiresChange: this.get('clickoutFiresChange'),
      chooseText: this.get('chooseText'),
      cancelText: this.get('cancelText'),
      togglePaletteMoreText: this.get('togglePaletteMoreText'),
      togglePaletteLessText: this.get('togglePaletteLessText'),
      appendTo: this.get('appendTo'),
      localStorageKey: this.get('localStorageKey')
    };
    let self = this;
    let updateFunction = function (newColor) {
      let color = newColor.toString();
      self.set('color', color);
      let onChange = this.get('onChange');
      if (onChange) {
        onChange(color);
      }
    };

    if (this.get('moveFiresChange')) {
      opts.move = updateFunction;
    } else {
      opts.change = updateFunction;
    }

    this.$().spectrum(opts);
  }
});
<commit_msg>fix use of this instead of self<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  classNames: 'spectrum-color-picker',

  tagName: 'input',

  color: null,

  flatMode: false,

  allowEmpty: false,

  disabled: false,

  showInput: false,

  showAlpha: false,

  showInitial: false,

  showButtons: true,

  showPalette: false,

  showPaletteOnly: false,

  palette: [],

  togglePaletteOnly: false,

  showSelectionPalette: false,

  hideAfterPaletteSelect: false,

  preferredFormat: null,

  moveFiresChange: false,

  clickoutFiresChange: false,

  chooseText: 'Choose',

  cancelText: 'Cancel',

  togglePaletteMoreText: 'More',

  togglePaletteLessText: 'Less',

  appendTo: 'body',

  localStorageKey: 'spectrum-color-picker',

  updatePicker: Ember.observer('color', function () {
    this.$().spectrum('set', this.get('color'));
  }),

  updateDisabled: Ember.observer('disabled', function () {
    this.$().spectrum(this.get('disabled') ? 'disable' : 'enable');
  }),

  didInsertElement() {
    let palette = this.get('palette');
    let opts = {
      color: this.get('color'),
      flat: this.get('flatMode'),
      allowEmpty: this.get('allowEmpty'),
      disabled: this.get('disabled'),
      showInput: this.get('showInput'),
      showAlpha: this.get('showAlpha'),
      showInitial: this.get('showInitial'),
      showButtons: this.get('showButtons'),
      showPalette: this.get('showPalette'),
      showPaletteOnly: this.get('showPaletteOnly'),
      palette: (typeof(palette) === 'string') ? JSON.parse(palette) : palette,
      togglePaletteOnly: this.get('togglePaletteOnly'),
      showSelectionPalette: this.get('showSelectionPalette'),
      hideAfterPaletteSelect: this.get('hideAfterPaletteSelect'),
      preferredFormat: this.get('preferredFormat'),
      clickoutFiresChange: this.get('clickoutFiresChange'),
      chooseText: this.get('chooseText'),
      cancelText: this.get('cancelText'),
      togglePaletteMoreText: this.get('togglePaletteMoreText'),
      togglePaletteLessText: this.get('togglePaletteLessText'),
      appendTo: this.get('appendTo'),
      localStorageKey: this.get('localStorageKey')
    };
    let self = this;
    let updateFunction = function (newColor) {
      let color = newColor.toString();
      self.set('color', color);
      let onChange = self.get('onChange');
      if (onChange) {
        onChange(color);
      }
    };

    if (this.get('moveFiresChange')) {
      opts.move = updateFunction;
    } else {
      opts.change = updateFunction;
    }

    this.$().spectrum(opts);
  }
});
<|endoftext|>


<commit_before>var searchApp = angular.module('searchApp');

searchApp

	.controller('searchController', function ($scope, $http, pagination, $location, $sce) {

		$scope.search = {
			words: '',
			phrase: '',
			anyWords:'',
			without:'',
			startRecord:'1',
			recordCount: '10'
		};

		var index = - 1;
		var prevNextCheck = 0;
		var baseUrl = '/csp/docsearch/rest/';
		var check = '';

		$scope.sce = $sce;
		$scope.mylocation = location.host;
		$scope.inputToggle = false;
		$scope.resultToggle = true;
		$scope.preloadToggle = false;
		$scope.prevToggle = false;
		$scope.nextToggle = false;
		$scope.checkToggle = false;
		$scope.title = "DocSearch";
		$scope.phraseShow = false;
		$scope.anyWordsShow = false;
		$scope.withoutShow = false;
		$scope.errorToggle = false;
		$scope.hintToggle = false;

		$scope.phraseClear=function(){
			$scope.search.phrase = "";
			$scope.makeSearch();
		}

		$scope.anyWordsClear=function(){
			$scope.search.anyWords = "";
			$scope.makeSearch();
		}

		$scope.withoutClear=function(){
			$scope.search.without = "";
			$scope.makeSearch();
		}
		$scope.clearAll=function(){
			$scope.search.words = "";
			$scope.search.phrase = "";
			$scope.search.anyWords = "";
			$scope.search.without = "";
		}

		$scope.change = function (){

			$http.get(baseUrl + 'GetSimilar/' + $scope.search.words)
				.then(function(response) {
					$scope.searchItems = response.data.entities;
					if ($scope.searchItems.length == 0) $scope.hintToggle = false;
					else $scope.hintToggle = true;
			});

			if ($scope.search.words == ''){
				$scope.inputToggle = false;
				}
			else {
				$scope.inputToggle = true;
				}
		}

		$scope.handleClick = function (item) {

			$scope.currrentSearchItem = item;
			$scope.search.words = $scope.currrentSearchItem.value;
			$scope.makeSearch();

			$scope.inputToggle = false;
			$scope.hintToggle = false;
		}

		$scope.handleArrows = function (event) {

			if(event.keyCode  === 40) // up
				index += 1;
			if(event.keyCode  === 38) // down
				index -= 1;

			if (index < 0)
				index = 9;
			if (index > 9)
				index = 0;
			if 	((event.keyCode === 40) || (event.keyCode === 38))
			{
				$scope.search.words = $scope.searchItems[index].value;
				$scope.currrentSearchItem = $scope.searchItems[index];
			}

			if (event.keyCode === 13)
					$scope.inputToggle = false;
		}

		$scope.makeSearch = function (){
			$scope.inputToggle = false;
			$scope.hintToggle = false;
			$scope.errorToggle = false;

			$scope.search.phrase=='' ? $scope.phraseShow=false : $scope.phraseShow=true;
			$scope.search.anyWords=='' ? $scope.anyWordsShow=false : $scope.anyWordsShow=true;
			$scope.search.without=='' ? $scope.withoutShow=false : $scope.withoutShow=true;

			$scope.title = $scope.search.words;

			if ($scope.search.words != '' || $scope.search.phrase != '' || $scope.search.anyWords != '')
			{
				$scope.showPage(0);
				$location.path("/DocResults");

			}
			else
				if ( $scope.search.without != '')
					$scope.errorToggle=true;
				else
					if ( $scope.search.without == '')
						$location.path("/DocSearch");
		}

		$scope.showPage = function (page) {

			$scope.resultToggle = true;

			$scope.currentPage = page;

			if(check != $scope.search.words)
			{
				$scope.checkToggle = true;
				check = $scope.search.words;
			}
			else
				$scope.checkToggle = false;

			$scope.preloadToggle = true;

			if(!isNaN(page))
					prevNextCheck = page;

			if (page == 'prev') {
					$scope.results = pagination.getPrevPageProducts();
					prevNextCheck -= 1;
					if (prevNextCheck < 0)
						prevNextCheck = 0;
			} else if (page == 'next') {
					$scope.results = pagination.getNextPageProducts($scope.totalCount, $scope.search.recordCount);
					prevNextCheck += 1;
					if (prevNextCheck > $scope.pagesNum - 1)
						prevNextCheck = $scope.pagesNum;
			} else {
				$scope.results = pagination.getPageProducts(page);
			}

			$scope.search.startRecord = (pagination.getCurrentPageNum()) * $scope.search.recordCount + 1;

			$http.post(baseUrl + 'Search', $scope.search)
				.then(function(response) {
					$scope.results = response.data.sources;

					$scope.totalCount = response.data.totalCount[0].total;

					if ($scope.totalCount != 0)
					{	$scope.resultToggle = true;
						$scope.pagesNum = pagination.getTotalPagesNum($scope.totalCount, $scope.search.recordCount);
						$scope.paginationList = pagination.getPaginationList($scope.currentPage, $scope.pagesNum, $scope.checkToggle);

						if (prevNextCheck != $scope.pagesNum - 1)
							$scope.nextToggle = true;
						else
							$scope.nextToggle = false;

						if ($scope.pagesNum == undefined)
							$scope.nextToggle = false;
					}
					else
						$scope.resultToggle = false;

					$scope.preloadToggle = false;
			});

			if (prevNextCheck != 0)
				$scope.prevToggle = true;
			else
				$scope.prevToggle = false;
		}

		$scope.currentPageNum = function() {

				return pagination.getCurrentPageNum();
		}

	})/* END of controller - searchController */<commit_msg>еще испраление подсказки<commit_after>var searchApp = angular.module('searchApp');

searchApp

	.controller('searchController', function ($scope, $http, pagination, $location, $sce) {

		$scope.search = {
			words: '',
			phrase: '',
			anyWords:'',
			without:'',
			startRecord:'1',
			recordCount: '10'
		};

		var index = - 1;
		var prevNextCheck = 0;
		var baseUrl = '/csp/docsearch/rest/';
		var check = '';

		$scope.sce = $sce;
		$scope.mylocation = location.host;
		$scope.inputToggle = false;
		$scope.resultToggle = true;
		$scope.preloadToggle = false;
		$scope.prevToggle = false;
		$scope.nextToggle = false;
		$scope.checkToggle = false;
		$scope.title = "DocSearch";
		$scope.phraseShow = false;
		$scope.anyWordsShow = false;
		$scope.withoutShow = false;
		$scope.errorToggle = false;
		$scope.hintToggle = false;

		$scope.phraseClear=function(){
			$scope.search.phrase = "";
			$scope.makeSearch();
		}

		$scope.anyWordsClear=function(){
			$scope.search.anyWords = "";
			$scope.makeSearch();
		}

		$scope.withoutClear=function(){
			$scope.search.without = "";
			$scope.makeSearch();
		}
		$scope.clearAll=function(){
			$scope.search.words = "";
			$scope.search.phrase = "";
			$scope.search.anyWords = "";
			$scope.search.without = "";
		}

		$scope.change = function (){

			$http.get(baseUrl + 'GetSimilar/' + $scope.search.words)
				.then(function(response) {
					$scope.searchItems = response.data.entities;
					if ($scope.searchItems.length == 0) $scope.hintToggle = false;
					else $scope.hintToggle = true;
			});

			if ($scope.search.words == ''){
				$scope.inputToggle = false;
				}
			else {
				$scope.inputToggle = true;
				}
		}

		$scope.handleClick = function (item) {

			$scope.currrentSearchItem = item;
			$scope.search.words = $scope.currrentSearchItem.value;
			$scope.makeSearch();

			$scope.inputToggle = false;
			$scope.hintToggle = false;
		}

		$scope.handleArrows = function (event) {

			if(event.keyCode  === 40) // up
				index += 1;
			if(event.keyCode  === 38) // down
				index -= 1;

			if (index < 0)
				index = 9;
			if (index > 9)
				index = 0;
			if 	((event.keyCode === 40) || (event.keyCode === 38))
			{
				$scope.search.words = $scope.searchItems[index].value;
				$scope.currrentSearchItem = $scope.searchItems[index];
			}

			if (event.keyCode === 13)
					$scope.inputToggle = false;
					$scope.hintToggle = false;
		}

		$scope.makeSearch = function (){
			$scope.inputToggle = false;
			$scope.hintToggle = false;
			$scope.errorToggle = false;

			$scope.search.phrase=='' ? $scope.phraseShow=false : $scope.phraseShow=true;
			$scope.search.anyWords=='' ? $scope.anyWordsShow=false : $scope.anyWordsShow=true;
			$scope.search.without=='' ? $scope.withoutShow=false : $scope.withoutShow=true;

			$scope.title = $scope.search.words;

			if ($scope.search.words != '' || $scope.search.phrase != '' || $scope.search.anyWords != '')
			{
				$scope.showPage(0);
				$location.path("/DocResults");

			}
			else
				if ( $scope.search.without != '')
					$scope.errorToggle=true;
				else
					if ( $scope.search.without == '')
						$location.path("/DocSearch");
		}

		$scope.showPage = function (page) {

			$scope.resultToggle = true;

			$scope.currentPage = page;

			if(check != $scope.search.words)
			{
				$scope.checkToggle = true;
				check = $scope.search.words;
			}
			else
				$scope.checkToggle = false;

			$scope.preloadToggle = true;

			if(!isNaN(page))
					prevNextCheck = page;

			if (page == 'prev') {
					$scope.results = pagination.getPrevPageProducts();
					prevNextCheck -= 1;
					if (prevNextCheck < 0)
						prevNextCheck = 0;
			} else if (page == 'next') {
					$scope.results = pagination.getNextPageProducts($scope.totalCount, $scope.search.recordCount);
					prevNextCheck += 1;
					if (prevNextCheck > $scope.pagesNum - 1)
						prevNextCheck = $scope.pagesNum;
			} else {
				$scope.results = pagination.getPageProducts(page);
			}

			$scope.search.startRecord = (pagination.getCurrentPageNum()) * $scope.search.recordCount + 1;

			$http.post(baseUrl + 'Search', $scope.search)
				.then(function(response) {
					$scope.results = response.data.sources;

					$scope.totalCount = response.data.totalCount[0].total;

					if ($scope.totalCount != 0)
					{	$scope.resultToggle = true;
						$scope.pagesNum = pagination.getTotalPagesNum($scope.totalCount, $scope.search.recordCount);
						$scope.paginationList = pagination.getPaginationList($scope.currentPage, $scope.pagesNum, $scope.checkToggle);

						if (prevNextCheck != $scope.pagesNum - 1)
							$scope.nextToggle = true;
						else
							$scope.nextToggle = false;

						if ($scope.pagesNum == undefined)
							$scope.nextToggle = false;
					}
					else
						$scope.resultToggle = false;

					$scope.preloadToggle = false;
			});

			if (prevNextCheck != 0)
				$scope.prevToggle = true;
			else
				$scope.prevToggle = false;
		}

		$scope.currentPageNum = function() {

				return pagination.getCurrentPageNum();
		}

	})/* END of controller - searchController */<|endoftext|>


<commit_before>import Ember from 'ember';
import WidgetCollection from 'ember-eureka/widget-collection';
import layout from '../templates/components/widget-collection-map';
import L from 'ember-leaflet-hurry';

export default WidgetCollection.extend({
    layout: layout,

    label: Ember.computed.alias('config.label'),

    titleProperty: Ember.computed('config.titleProperty', function() {
        return this.getWithDefault('config.titleProperty', 'title');
    }),

    latitudeProperty: Ember.computed('config.latitudeProperty', function() {
        return this.getWithDefault('config.latitudeProperty', 'latitude');
    }),

    longitudeProperty: Ember.computed('config.longitudeProperty', function() {
        return this.getWithDefault('config.longitudeProperty', 'longitude');
    }),

    zoom: Ember.computed('config.zoom', function() {
        return this.getWithDefault('config.zoom', 5);
    }),

    minZoom: Ember.computed('config.minZoom', function() {
        return this.getWithDefault('config.minZoom', 2);
    }),

    maxZoom: Ember.computed('config.maxZoom', function() {
        return this.getWithDefault('config.maxZoom', 20);
    }),

    /** mapProvider
     * see http://leaflet-extras.github.io/leaflet-providers/preview/index.html for all
     * layer available
     */
    mapProvider: Ember.computed('config.mapProvider', function() {
        // ex: 'Esri.WorldImagery'
        return this.getWithDefault('config.mapProvider', 'MapQuestOpen.OSM');
    }),

    _map: null,

    collection:  Ember.computed('routeModel.query.hasChanged', 'store', function() {
        var query = this.get('routeModel.query')._toObject();
        return this.get('store').find(query);
    }),

    renderMap: Ember.observer(
        'collection.[]', 'latitudeProperty', 'longitudeProperty',
        'titleProperty', 'zoom', 'mapProvider', function() {
        var map = this.get('_map');
        if (!map) {
            map = this.initializeMap();
            this.set('_map', map);
        } else {
            map.eachLayer(function (layer) {
                map.removeLayer(layer);
            });
        }

        var zoom = this.get('zoom');
        var mapProvider = this.get('mapProvider');

        var markers = L.markerClusterGroup();

        var latitudePropertyName = this.get('latitudeProperty');
        var longitudePropertyName = this.get('longitudeProperty');
        var titlePropertyName = this.get('titleProperty');

        var latLongs = [];
        this.get('collection').then(function(data) {
            data.forEach(function(item) {
                let latitude = Ember.get(item, latitudePropertyName);
                let longitude = Ember.get(item, longitudePropertyName);
                let title = Ember.get(item, titlePropertyName);
                if (latitude && longitude) {
                    let latLong = new L.LatLng(latitude, longitude);
                    latLongs.push(latLong);
                    let marker = L.marker(latLong, { title: title });
                    marker.bindPopup(title);
                    markers.addLayer(marker);
                }
            });

            // center the map into markers
            if (latLongs.length) {
                map.fitBounds(new L.LatLngBounds(latLongs));
                map.setZoom(zoom);
                L.tileLayer.provider(mapProvider).addTo(map);
                map.addLayer(markers);
            }
        });
    }),

    initializeMap: function() {
        var minZoom = this.get('minZoom');
        var maxZoom = this.get('maxZoom');
        var zoom = this.get('zoom');

        var map = L.map(this.$('.panel-body')[0], {
            center: [20.0, 5.0],
            zoom: zoom,
            minZoom: minZoom,
            maxZoom: maxZoom
        });

        map.scrollWheelZoom.disable();

        map.on('popupopen', function(e) {
            var px = map.project(e.popup._latlng);
            px.y -= e.popup._container.clientHeight/2;
            map.panTo(map.unproject(px),{animate: true});
        });
        return map;
    },

    tearDownMap: Ember.on('willDestroy', function() {
        if (this.get('_map')) {
            this.get('_map').remove();
            this.set('_map', null);
        }
    })

});
<commit_msg>fix marker icon issue<commit_after>import Ember from 'ember';
import WidgetCollection from 'ember-eureka/widget-collection';
import layout from '../templates/components/widget-collection-map';
import L from 'ember-leaflet-hurry';

export default WidgetCollection.extend({
    layout: layout,

    label: Ember.computed.alias('config.label'),

    titleProperty: Ember.computed('config.titleProperty', function() {
        return this.getWithDefault('config.titleProperty', 'title');
    }),

    latitudeProperty: Ember.computed('config.latitudeProperty', function() {
        return this.getWithDefault('config.latitudeProperty', 'latitude');
    }),

    longitudeProperty: Ember.computed('config.longitudeProperty', function() {
        return this.getWithDefault('config.longitudeProperty', 'longitude');
    }),

    zoom: Ember.computed('config.zoom', function() {
        return this.getWithDefault('config.zoom', 5);
    }),

    minZoom: Ember.computed('config.minZoom', function() {
        return this.getWithDefault('config.minZoom', 2);
    }),

    maxZoom: Ember.computed('config.maxZoom', function() {
        return this.getWithDefault('config.maxZoom', 20);
    }),

    /** mapProvider
     * see http://leaflet-extras.github.io/leaflet-providers/preview/index.html for all
     * layer available
     */
    mapProvider: Ember.computed('config.mapProvider', function() {
        // ex: 'Esri.WorldImagery'
        return this.getWithDefault('config.mapProvider', 'MapQuestOpen.OSM');
    }),

    _map: null,

    collection:  Ember.computed('routeModel.query.hasChanged', 'store', function() {
        var query = this.get('routeModel.query')._toObject();
        return this.get('store').find(query);
    }),

    renderMap: Ember.observer(
        'collection.[]', 'latitudeProperty', 'longitudeProperty',
        'titleProperty', 'zoom', 'mapProvider', function() {
        var map = this.get('_map');
        if (!map) {
            map = this.initializeMap();
            this.set('_map', map);
        } else {
            map.eachLayer(function (layer) {
                map.removeLayer(layer);
            });
        }

        var zoom = this.get('zoom');
        var mapProvider = this.get('mapProvider');

        var markers = L.markerClusterGroup();

        var latitudePropertyName = this.get('latitudeProperty');
        var longitudePropertyName = this.get('longitudeProperty');
        var titlePropertyName = this.get('titleProperty');

        var pinIcon = L.icon({
            iconUrl: '/images/leaflet/marker-icon.png',
            iconRetinaUrl: '/images/leaflet/marker-icon-2x.png',
            iconAnchor: [12.5, 41] // needed to position the marker correctly
        });

        var latLongs = [];
        this.get('collection').then(function(data) {
            data.forEach(function(item) {
                let latitude = Ember.get(item, latitudePropertyName);
                let longitude = Ember.get(item, longitudePropertyName);
                let title = Ember.get(item, titlePropertyName);
                if (latitude && longitude) {
                    let latLong = new L.LatLng(latitude, longitude);
                    latLongs.push(latLong);
                    let marker = L.marker(latLong, {title: title, icon: pinIcon});
                    marker.bindPopup(title);
                    markers.addLayer(marker);
                }
            });

            // center the map into markers
            if (latLongs.length) {
                map.fitBounds(new L.LatLngBounds(latLongs));
                map.setZoom(zoom);
                L.tileLayer.provider(mapProvider).addTo(map);
                map.addLayer(markers);
            }
        });
    }),

    initializeMap: function() {
        var minZoom = this.get('minZoom');
        var maxZoom = this.get('maxZoom');
        var zoom = this.get('zoom');

        var map = L.map(this.$('.panel-body')[0], {
            center: [20.0, 5.0],
            zoom: zoom,
            minZoom: minZoom,
            maxZoom: maxZoom
        });

        map.scrollWheelZoom.disable();

        map.on('popupopen', function(e) {
            var px = map.project(e.popup._latlng);
            px.y -= e.popup._container.clientHeight/2;
            map.panTo(map.unproject(px),{animate: true});
        });
        return map;
    },

    tearDownMap: Ember.on('willDestroy', function() {
        if (this.get('_map')) {
            this.get('_map').remove();
            this.set('_map', null);
        }
    })

});
<|endoftext|>


<commit_before>// Start of parsing results
function getJsonFromUrl(hashBased) {
    'use strict'
    var query;
    if (hashBased) {
        var pos = location.href.indexOf("?");
        if (pos === -1) return [];
        query = location.href.substr(pos + 1);
    } else {
        query = location.search.substr(1);
    }
    var result = {};
    query.split("&").forEach(function(part) {
        if (!part) return;
        part = part.split("+").join(" "); // replace every + with space, regexp-free version
        var eq = part.indexOf("=");
        var key = eq > -1 ? part.substr(0, eq) : part;
        var val = eq > -1 ? decodeURIComponent(part.substr(eq + 1)) : "";
        var from = key.indexOf("[");
        if (from == -1) result[decodeURIComponent(key)] = val;
        else {
            var to = key.indexOf("]");
            var index = decodeURIComponent(key.substring(from + 1, to));
            key = decodeURIComponent(key.substring(0, from));
            if (!result[key]) result[key] = [];
            if (!index) result[key].push(val);
            else result[key][index] = val;
        }
    });
    return result;
}

var resultado = [];
resultado = JSON.parse(getJsonFromUrl().test);
//End of parsing results

var i = 0;
var tableHeader1 = '
 Arranjos
';
var tableHeader = '
 Nº de Barras 	  Φ Bitola (mm) 	  Área de Aço \\(A_{s calc}\\) (cm²) 	  Taxa de Armadura 	  Espaçamento horizontal 	  Espaçamento vertical
';
MathJax.Hub.Queue(["Typeset", MathJax.Hub, tableHeader]);

$(document).ready(function() {
    // Header
    $(".project").html(resultado.project);
    $(".beam").html(resultado.beam);
    $(".h").html(resultado.h);
    $(".bw").html(resultado.bw);
    $(".concrete").html(resultado.concrete);
    $(".steel").html(resultado.steel);
    $(".diamEstForm").html(resultado.diamEstForm);
    $(".dl").html(resultado.dl);
    $(".dlc").html(resultado.dlc);
    $(".cob").html(resultado.cob);
    $(".agreg").html(resultado.agreg);
    $(".mk").html(resultado.mk);
    $(".gamac").html(resultado.gamac);
    $(".gamaf").html(resultado.gamaf);
    $(".gamas").html(resultado.gamas);

    // Section
    $("#h").html(resultado.suggestion[0].perfil.h);
    $("#bw").html(resultado.suggestion[0].perfil.dl);
    $("#cob").html(resultado.suggestion[0].perfil.area);
    $("#d").html(resultado.suggestion[0].perfil.ix);
    $("#diamEstForm").html(resultado.suggestion[0].perfil.wx);
    $(".dl").html(resultado.suggestion[0].perfil.rx);
    $(".dlc").html(resultado.suggestion[0].perfil.zx);
    $("#ac").html(resultado.suggestion[0].perfil.iy);

    // SD
    $("#md").html(resultado.md);

    //RD

    $('#suggestion_table').append('

');
    var table = $('#suggestion_table').children();
    table.append(tableHeader);
    for (i = 0; i <= resultado.arranjos.length; i += 1) {
        table.append('
' +  resultado.arranjos[i].qtd + '	' + '' +  resultado.arranjos[i].bitola + '	' + '' +  resultado.arranjos[i].as + '	' + '' +  resultado.arranjos[i].taxa + '	' + '' +  resultado.arranjos[i].ah + '	' + '' +  resultado.arranjos[i].av + '	' + '
');
    }

});
<commit_msg>Update reportDesignCSimples.js<commit_after>// Start of parsing results
function getJsonFromUrl(hashBased) {
    'use strict'
    var query;
    if (hashBased) {
        var pos = location.href.indexOf("?");
        if (pos === -1) return [];
        query = location.href.substr(pos + 1);
    } else {
        query = location.search.substr(1);
    }
    var result = {};
    query.split("&").forEach(function(part) {
        if (!part) return;
        part = part.split("+").join(" "); // replace every + with space, regexp-free version
        var eq = part.indexOf("=");
        var key = eq > -1 ? part.substr(0, eq) : part;
        var val = eq > -1 ? decodeURIComponent(part.substr(eq + 1)) : "";
        var from = key.indexOf("[");
        if (from == -1) result[decodeURIComponent(key)] = val;
        else {
            var to = key.indexOf("]");
            var index = decodeURIComponent(key.substring(from + 1, to));
            key = decodeURIComponent(key.substring(0, from));
            if (!result[key]) result[key] = [];
            if (!index) result[key].push(val);
            else result[key][index] = val;
        }
    });
    return result;
}

var resultado = [];
resultado = JSON.parse(getJsonFromUrl().test);
//End of parsing results

var i = 0;
var tableHeader1 = '
 Arranjos
';
var tableHeader = '
 Nº de Barras 	  Φ Bitola (mm) 	  Área de Aço \\(A_{s calc}\\) (cm²) 	  Taxa de Armadura 	  Espaçamento horizontal 	  Espaçamento vertical
';
MathJax.Hub.Queue(["Typeset", MathJax.Hub, tableHeader]);

$(document).ready(function() {
    // Header
    $(".project").html(resultado.project);
    $(".beam").html(resultado.beam);
    $(".h").html(resultado.h);
    $(".bw").html(resultado.bw);
    $(".concrete").html(resultado.concrete);
    $(".steel").html(resultado.steel);
    $(".diamEstForm").html(resultado.diamEstForm);
    $(".dl").html(resultado.dl);
    $(".dlc").html(resultado.dlc);
    $(".cob").html(resultado.cob);
    $(".agreg").html(resultado.agreg);
    $(".mk").html(resultado.mk);
    $(".gamac").html(resultado.gamac);
    $(".gamaf").html(resultado.gamaf);
    $(".gamas").html(resultado.gamas);

    // Section
    $("#h").html(resultado.h);
    $("#bw").html(resultado.bw);
    $("#cob").html(resultado.cob);
    $("#d").html(resultado.d);
    $("#diamEstForm").html(resultado.diamEstForm);
    $(".dl").html(resultado.dl);
    $(".dlc").html(resultado.dlc;
    $("#ac").html(ac);

    // SD
    $("#md").html(resultado.md);

    //RD

    $('#suggestion_table').append('

');
    var table = $('#suggestion_table').children();
    table.append(tableHeader);
    for (i = 0; i <= resultado.arranjos.length; i += 1) {
        table.append('
' +  resultado.arranjos[i].qtd + '	' + '' +  resultado.arranjos[i].bitola + '	' + '' +  resultado.arranjos[i].as + '	' + '' +  resultado.arranjos[i].taxa + '	' + '' +  resultado.arranjos[i].ah + '	' + '' +  resultado.arranjos[i].av + '	' + '
');
    }

});
<|endoftext|>