<commit_before>/**
 * Saves the state of the given element. Must implement an action for
 * any element that can be saved.
 *
 * @param $elm The element for which to save the current state
 */
function saveState($elm)
{
	var $elmId = $elm[0].id;

	switch ($elmId) {

		case 'questionnaire-questions-list':
			$('body').addClass('loading');
			$('.tabs ul:first li').addClass('ui-state-default');

			var $questionnaireId = window.location.href.match(/\/id\/(\d{1,})/)[1].toString();
			var $pages = $('ul.sortable');

			$pages.each(function($key, $val) {
				var $page = $($val);
				var $data = $page.sortable('serialize') + '&page=' + (parseInt($key) + 1);
				$.post(baseUrl + '/questionnaire/order', $data, function() {
					if ($key == ($pages.length - 1)) {
						$('body').removeClass('loading');
					}
				});
			});
			break;

		case 'repository-questions':
		case 'less':
		case 'more':
		case 'subquestions':
			$('body').addClass('loading');

			var $action = $elm.closest('form').attr('action');
			var $qqId = $action.match(/\/id\/(\d{1,})/)[1].toString();

			var $list = $('#subquestions');
			var $data = $list.sortable('serialize') + '&cols=' + $('#cols').val() + '&parent=' + $qqId;
			$.post(baseUrl + '/questionnaire-question/save-state', $data, function() {
				$('body').removeClass('loading');
			});
			break;

		default:
			var $message = 'No action implemented for element with id #' + $elmId;
			console.log($message);
			break;
	}
}

function makeTabsSortable()
{
	$('ul.sortable').sortable({
		handle: 'div.handle',
		revert: 'invalid',
		start: function(event, ui) {
			$(ui.helper).css({
				width: '16px',
				height: '16px',
				overflow: 'hidden'
			});
		},
		update: function(event, ui) {
			saveState($(this));
		}
	}).disableSelection();
}

function makeTabsDroppable($tabs) {
	var $tabItems = $('ul:first li', $tabs);
	return $tabItems.droppable({
		activeClass: 'ui-state-default',
		hoverClass: 'ui-state-hover',
		accept: 'ul.sortable li',
		drop: function(event, ui) {
			var $item = $(this);
			var $list = $($item.find('a').attr('href')).find('ul.sortable');
			var $draggable = ui.draggable.clone();
			ui.draggable.remove();
			$list.prepend($('
' + $draggable.html() + '
'));
			$tabs.tabs('select', $tabItems.index($item));
		}
	});
}

function updateAnswersTab() {
	if ($('#answers-useAnswerPossibilityGroup').is(':checked')) {
		$('#answers-answerPossibilityGroup_id').removeAttr('disabled');
		$('#answers-collectionPresentationType').removeAttr('disabled');
	} else {
		$('#answers-answerPossibilityGroup_id').attr('disabled', 'disabled');
		$('#answers-collectionPresentationType').attr('disabled', 'disabled');
	}
}

function updateColWidth(action) {
	/* get and update current number of columns */
	$cols = $('#cols').val();
	if ($cols == 'NaN') $cols = 1;
	if (action == 'less' && $cols > 1) {
		$cols--;
	} else if (action == 'more' && $cols < $('#dialog #group ul#subquestions li').length) {
		$cols++;
	}
	$('#cols').val($cols);

	/* calculate and set new column width */
	$containerWidth = parseInt($('#dialog').width()) - 65;
	$newWidth = parseInt($containerWidth / $cols) - (5 * $cols);
	$.each($('#dialog #group ul#subquestions li'), function($i, $elm) {
		$($elm).width($newWidth);
	});
}

/**
 * Initialises the tab for editing sub-questions
 */
function initTabSubquestions()
{
	var $list = $('#dialog #group ul#subquestions');

	updateColWidth();

	$('#dialog #group #less').click(function() {
		updateColWidth('less');
		saveState($list);
		return false;
	});

	$('#dialog #group #more').click(function() {
		updateColWidth('more');
		saveState($list);
		return false;
	});

	$('#dialog #group ul#subquestions').sortable({
		update: function(event, ui) {
			saveState($list);
		}
	});

	$('#dialog #group ul#subquestions li a.delete').click(function() {
		$(this).closest('li').remove();
		saveState($list);
		return false;
	});
}

/**
 * Initialises the tab for editing answer-possibilities
 */
function initTabAnswerPossibilities()
{
	updateAnswersTab();
	$('#answers-useAnswerPossibilityGroup').change(function() {
		updateAnswersTab();
	});
}

function postOpenDialog(response) {

	/* tabs */
	$('.tabs').tabs();

	/* init tab sub-questions */
	if ($('#dialog #group').length > 0) {
		initTabSubquestions();
	}

	/* init tab answer-possibilities */
	if ($('#dialog #answer').length > 0) {
		initTabAnswerPossibilities();
	}

	/* add questionnaire id to the form */
	var $questionnaireId = window.location.href.match(/id\/(\d{1,})/)[1];
	$('<input type="hidden" id="questionnaire_id" name="questionnaire_id" value="' + $questionnaireId + '" />').appendTo('#dialog form');

	/* initialize filter */
	initFilter();

//	$.each($('#dialog input[type="text"]'), function($key, $val) {
//		var $elm = $($val);
//		var $name = $elm.attr('name');
//		$elm.autocomplete({
//			source: baseUrl + '/question/autocomplete/element/' + $name,
//			select: function(event, ui) {
//
//				/* replace the value by the label */
//				$(this).val(ui.item.label);
//
//				/* add question id to the form */
//				if ($('#dialog form input#question_id').length == 0) {
//					$('<input type="hidden" id="question_id" name="question_id" value="' + ui.item.value + '" />').appendTo('#dialog form');
//				} else {
//					$('#dialog form input#question_id').val(ui.item.value);
//				}
//
//				return false;
//			}
//		});
//	});

	/* hide repository questions list */
	$('#repository-questions').hide();

	/* add action to 'add subquestion' link */
	$('#group a.add').toggle(function() {
		$('#repository-questions').show();
		return false;
	}, function() {
		$('#repository-questions').hide();
		return false;
	});

	/* make repository questions list selectable */
	$('#repository-questions').selectable({
		/* add event to selection of a subquestion */
		selected: function(event, ui) {
			var $list = $('#subquestions');
			/* make sortable */
			$list.sortable();
			/* append selected subquestion to list */
			$(ui.selected)
				.removeClass('ui-widget-content')
				.removeClass('ui-selectee')
				.removeClass('ui-selected')
				.addClass('ui-state-default')
				.prepend('')
				.appendTo($list);
			if ($list.find('li').length == 1) {
				$(ui.selected).css({width: '100%'});
			} else {
				$(ui.selected).css({width: $list.find('li:first').width() + 'px'});
			}
			/* save current state of the list */
			saveState($(this));
		}
	});
}

$(function() {

	var $tabs = $('.tabs').tabs();
	makeTabsSortable();
	var $tabItems = makeTabsDroppable($tabs);

	$('.add_page').click(function() {
		var $tabs = $('div.tabs');
		var $newPageId = $tabs.tabs('length') + 1;
		var $newPage = $('#page-1').clone();

		$newPage.attr('id', 'page-' + $newPageId);
		$('ul.sortable li', $newPage).remove();
		$newPage.appendTo($tabs);

		$tabs.tabs('add', '#' + 'page-' + $newPageId, 'pagina ' + $newPageId);
		$tabs.tabs('select', $tabs.tabs('length') - 1);

		/* reset */
		makeTabsSortable();
		makeTabsDroppable($tabs);

		return false;
	});

	/* hide form for editing title if no errors */
	if ($('form#HVA_Form_Questionnaire_Edit ul.errors').length == 0) {
		$('form#HVA_Form_Questionnaire_Edit').hide();
	}

	/* show form for editing title when edit-buttons is clicked */
	$('a#edit_title').toggle(
		function() {
			$('form#HVA_Form_Questionnaire_Edit').show('slow');
			return false;
		}, function() {
			$('form#HVA_Form_Questionnaire_Edit').hide('slow');
			return false;
		}
	);

	/* hide admin options by default; show on hover */
	$('#questionnaire-questions-list li .admin .options').hide();
	$('#questionnaire-questions-list li').hover(function() {
		$(this).addClass('ui-state-highlight')
			.find('.admin .options').show();
	}, function() {
		$(this).removeClass('ui-state-highlight')
			.find('.admin .options').hide();
	});
});
<commit_msg>[4830] validatie opties alleen mogelijk als geen antwoordengroep gebruikt wordt<commit_after>/**
 * Saves the state of the given element. Must implement an action for
 * any element that can be saved.
 *
 * @param $elm The element for which to save the current state
 */
function saveState($elm)
{
	var $elmId = $elm[0].id;

	switch ($elmId) {

		case 'questionnaire-questions-list':
			$('body').addClass('loading');
			$('.tabs ul:first li').addClass('ui-state-default');

			var $questionnaireId = window.location.href.match(/\/id\/(\d{1,})/)[1].toString();
			var $pages = $('ul.sortable');

			$pages.each(function($key, $val) {
				var $page = $($val);
				var $data = $page.sortable('serialize') + '&page=' + (parseInt($key) + 1);
				$.post(baseUrl + '/questionnaire/order', $data, function() {
					if ($key == ($pages.length - 1)) {
						$('body').removeClass('loading');
					}
				});
			});
			break;

		case 'repository-questions':
		case 'less':
		case 'more':
		case 'subquestions':
			$('body').addClass('loading');

			var $action = $elm.closest('form').attr('action');
			var $qqId = $action.match(/\/id\/(\d{1,})/)[1].toString();

			var $list = $('#subquestions');
			var $data = $list.sortable('serialize') + '&cols=' + $('#cols').val() + '&parent=' + $qqId;
			$.post(baseUrl + '/questionnaire-question/save-state', $data, function() {
				$('body').removeClass('loading');
			});
			break;

		default:
			var $message = 'No action implemented for element with id #' + $elmId;
			console.log($message);
			break;
	}
}

function makeTabsSortable()
{
	$('ul.sortable').sortable({
		handle: 'div.handle',
		revert: 'invalid',
		start: function(event, ui) {
			$(ui.helper).css({
				width: '16px',
				height: '16px',
				overflow: 'hidden'
			});
		},
		update: function(event, ui) {
			saveState($(this));
		}
	}).disableSelection();
}

function makeTabsDroppable($tabs) {
	var $tabItems = $('ul:first li', $tabs);
	return $tabItems.droppable({
		activeClass: 'ui-state-default',
		hoverClass: 'ui-state-hover',
		accept: 'ul.sortable li',
		drop: function(event, ui) {
			var $item = $(this);
			var $list = $($item.find('a').attr('href')).find('ul.sortable');
			var $draggable = ui.draggable.clone();
			ui.draggable.remove();
			$list.prepend($('
' + $draggable.html() + '
'));
			$tabs.tabs('select', $tabItems.index($item));
		}
	});
}

function updateAnswersTab() {
	if ($('#answers-useAnswerPossibilityGroup').is(':checked')) {
		$('#answers-answerPossibilityGroup_id').removeAttr('disabled');
		$('#answers-collectionPresentationType').removeAttr('disabled');
	} else {
		$('#answers-answerPossibilityGroup_id').attr('disabled', 'disabled');
		$('#answers-collectionPresentationType').attr('disabled', 'disabled');
	}
}

function updateValidationTab() {
	if ($('#answers-useAnswerPossibilityGroup').is(':checked')) {
		$('#dialog #validation input[type="checkbox"]').attr('disabled', 'disabled');
	} else {
		$('#dialog #validation input[type="checkbox"]').removeAttr('disabled');
	}
}

function updateColWidth(action) {
	/* get and update current number of columns */
	$cols = $('#cols').val();
	if ($cols == 'NaN') $cols = 1;
	if (action == 'less' && $cols > 1) {
		$cols--;
	} else if (action == 'more' && $cols < $('#dialog #group ul#subquestions li').length) {
		$cols++;
	}
	$('#cols').val($cols);

	/* calculate and set new column width */
	$containerWidth = parseInt($('#dialog').width()) - 65;
	$newWidth = parseInt($containerWidth / $cols) - (5 * $cols);
	$.each($('#dialog #group ul#subquestions li'), function($i, $elm) {
		$($elm).width($newWidth);
	});
}

/**
 * Initialises the tab for editing sub-questions
 */
function initTabSubquestions()
{
	var $list = $('#dialog #group ul#subquestions');

	updateColWidth();

	$('#dialog #group #less').click(function() {
		updateColWidth('less');
		saveState($list);
		return false;
	});

	$('#dialog #group #more').click(function() {
		updateColWidth('more');
		saveState($list);
		return false;
	});

	$('#dialog #group ul#subquestions').sortable({
		update: function(event, ui) {
			saveState($list);
		}
	});

	$('#dialog #group ul#subquestions li a.delete').click(function() {
		$(this).closest('li').remove();
		saveState($list);
		return false;
	});
}

/**
 * Initialises the tab for editing answer-possibilities
 */
function initTabAnswerPossibilities()
{
	updateAnswersTab();
	$('#answers-useAnswerPossibilityGroup').change(function() {
		updateAnswersTab();
	});
}

/**
 * Initialises the tab for validation settings
 */
function initTabValidation()
{
	updateValidationTab();
	$('#answers-useAnswerPossibilityGroup').change(function() {
		updateValidationTab();
	});
}

function postOpenDialog(response) {

	/* tabs */
	$('.tabs').tabs();

	/* init tab sub-questions */
	if ($('#dialog #group').length > 0) {
		initTabSubquestions();
	}

	/* init tab answer-possibilities */
	if ($('#dialog #answer').length > 0) {
		initTabAnswerPossibilities();
		initTabValidation();
	}

	/* add questionnaire id to the form */
	var $questionnaireId = window.location.href.match(/id\/(\d{1,})/)[1];
	$('<input type="hidden" id="questionnaire_id" name="questionnaire_id" value="' + $questionnaireId + '" />').appendTo('#dialog form');

	/* initialize filter */
	initFilter();

//	$.each($('#dialog input[type="text"]'), function($key, $val) {
//		var $elm = $($val);
//		var $name = $elm.attr('name');
//		$elm.autocomplete({
//			source: baseUrl + '/question/autocomplete/element/' + $name,
//			select: function(event, ui) {
//
//				/* replace the value by the label */
//				$(this).val(ui.item.label);
//
//				/* add question id to the form */
//				if ($('#dialog form input#question_id').length == 0) {
//					$('<input type="hidden" id="question_id" name="question_id" value="' + ui.item.value + '" />').appendTo('#dialog form');
//				} else {
//					$('#dialog form input#question_id').val(ui.item.value);
//				}
//
//				return false;
//			}
//		});
//	});

	/* hide repository questions list */
	$('#repository-questions').hide();

	/* add action to 'add subquestion' link */
	$('#group a.add').toggle(function() {
		$('#repository-questions').show();
		return false;
	}, function() {
		$('#repository-questions').hide();
		return false;
	});

	/* make repository questions list selectable */
	$('#repository-questions').selectable({
		/* add event to selection of a subquestion */
		selected: function(event, ui) {
			var $list = $('#subquestions');
			/* make sortable */
			$list.sortable();
			/* append selected subquestion to list */
			$(ui.selected)
				.removeClass('ui-widget-content')
				.removeClass('ui-selectee')
				.removeClass('ui-selected')
				.addClass('ui-state-default')
				.prepend('')
				.appendTo($list);
			if ($list.find('li').length == 1) {
				$(ui.selected).css({width: '100%'});
			} else {
				$(ui.selected).css({width: $list.find('li:first').width() + 'px'});
			}
			/* save current state of the list */
			saveState($(this));
		}
	});
}

$(function() {

	var $tabs = $('.tabs').tabs();
	makeTabsSortable();
	var $tabItems = makeTabsDroppable($tabs);

	$('.add_page').click(function() {
		var $tabs = $('div.tabs');
		var $newPageId = $tabs.tabs('length') + 1;
		var $newPage = $('#page-1').clone();

		$newPage.attr('id', 'page-' + $newPageId);
		$('ul.sortable li', $newPage).remove();
		$newPage.appendTo($tabs);

		$tabs.tabs('add', '#' + 'page-' + $newPageId, 'pagina ' + $newPageId);
		$tabs.tabs('select', $tabs.tabs('length') - 1);

		/* reset */
		makeTabsSortable();
		makeTabsDroppable($tabs);

		return false;
	});

	/* hide form for editing title if no errors */
	if ($('form#HVA_Form_Questionnaire_Edit ul.errors').length == 0) {
		$('form#HVA_Form_Questionnaire_Edit').hide();
	}

	/* show form for editing title when edit-buttons is clicked */
	$('a#edit_title').toggle(
		function() {
			$('form#HVA_Form_Questionnaire_Edit').show('slow');
			return false;
		}, function() {
			$('form#HVA_Form_Questionnaire_Edit').hide('slow');
			return false;
		}
	);

	/* hide admin options by default; show on hover */
	$('#questionnaire-questions-list li .admin .options').hide();
	$('#questionnaire-questions-list li').hover(function() {
		$(this).addClass('ui-state-highlight')
			.find('.admin .options').show();
	}, function() {
		$(this).removeClass('ui-state-highlight')
			.find('.admin .options').hide();
	});
});
<|endoftext|>


<commit_before>
module.exports = {
    'ping': (message) => {
        message.reply("pong!");
    },

    'echo': (message, _, msg) => {
        if (msg) {
            message.channel.send(msg);
        }
    },

    'prefix': (message, _, __, newPrefix) => {
        if (newPrefix) {
            config.prefix = newPrefix;
            fs.writeFile("./config.json", JSON.stringify(config, null, 4), err => console.error);
            message.channel.send(`Prefix successfully set to '${newPrefix}'`)
        } else {
            message.channel.send("Please provide a prefix.");
        }
    },

    'die': (message, soupmaster) => {
        if (message.author.id === soupmaster.id) {
            message.channel.send("Emptying can...")
                .then(() => {
                    console.log("Forced to disconnect.");
                    process.exit(0);
                });
        }
    },

    'factcheck': (message, _, msg) => {
        let bool1 = (Math.random() >= 0.5)
        let bool2 = (Math.random() >= 0.5)
        let str;

        if (msg) {
            str = `${message.author}'s claim, "${msg}",`
            str = bool1 ? `${str} is obviously ${bool2.toString()}.`
                        : `${str} can't possibly be ${bool2.toString()}.`;
        } else {
            str = bool1 ? `${message.author} is totally ${bool2 ? "right" : "wrong"}.`
                        : `${message.author} is never ${bool2 ? "right" : "wrong"}.`
        }
        message.channel.send(str);
    }
}<commit_msg>Add coin and dice command<commit_after>
module.exports = {
    'ping': (message) => {
        message.reply("pong!");
    },

    'echo': (message, _, msg) => {
        if (msg) {
            message.channel.send(msg);
        }
    },

    'prefix': (message, _, __, newPrefix) => {
        if (newPrefix) {
            config.prefix = newPrefix;
            fs.writeFile("./config.json", JSON.stringify(config, null, 4), err => console.error);
            message.channel.send(`Prefix successfully set to '${newPrefix}'`)
        } else {
            message.channel.send("Please provide a prefix.");
        }
    },

    'die': (message, soupmaster) => {
        if (message.author.id === soupmaster.id) {
            message.channel.send("Emptying can...")
                .then(() => {
                    console.log("Forced to disconnect.");
                    process.exit(0);
                });
        }
    },

    'factcheck': (message, _, msg) => {
        let bool1 = (Math.random() > 0.5)
        let bool2 = (Math.random() > 0.5)
        let str;

        if (msg) {
            str = `${message.author}'s claim, "${msg}",`
            str = bool1 ? `${str} is obviously ${bool2.toString()}.`
                        : `${str} can't possibly be ${bool2.toString()}.`;
        } else {
            str = bool1 ? `${message.author} is always ${bool2 ? "right" : "wrong"}.`
                        : `${message.author} is never ${bool2 ? "right" : "wrong"}.`
        }
        message.channel.send(str);
    },

    'coin': (message) => {
        let bool = (Math.random() > 0.5);
        message.channel.send(bool ? "Heads." : "Tails.");
    },

    'dice': (message) => {
        message.channel.send(Math.floor(Math.random()*6) + 1);
    }
}<|endoftext|>


<commit_before>require('dotenv').config();
var util = require('util');

module.exports = function (context, req) {

    var statusCode = 400;
    var responseBody = "Invalid request object";

    if (typeof req.body != 'undefined' && typeof req.body == 'object') {

        statusCode = 201;
        //context.bindings.outTable = req.body;
        var myReq = req.body;
        var myToken = new oAccessToken(myReq.userid,myReq.email,guid());

        //save to document db
        context.bindings.out = myToken;

        //send mail
        sendMail(myToken.userid,myToken.email,myToken.accesstoken);

        responseBody = "Access Token Created, Email Sent";
    }

    context.res = {
        status: statusCode,
        body: responseBody
    };

    context.done();
}

function sendMail(userid,email,token) {

    console.log('Sending Notification');

    var toEmail = email;
    var userId = userid
    var userToken = token;
    var profileUrl = util.format("%s%s?access_token=%s",process.env.DashboardProfileUrl, userId, userToken);

    //console.log('------>' + profileUrl);

    var msgContent = util.format("Please view the profile here: %s", profileUrl);

    var helper = require('sendgrid').mail;

    from_email = new helper.Email(process.env.NotifyEmailFrom);
    to_email = new helper.Email(toEmail);
    subject = "Missing Children of Canada Alert";
    content = new helper.Content("text/plain", msgContent);
    mail = new helper.Mail(from_email, subject, to_email, content);

    // Set to high importance
    header = new helper.Header("Priority", "Urgent");
    mail.addHeader(header);
    header = new helper.Header("Importance", "high");
    mail.addHeader(header);

    var sg = require('sendgrid')(process.env.SendGridAPIKey);

    var requestBody = mail.toJSON();
    var emptyRequest = require('sendgrid-rest').request;
    var requestPost = JSON.parse(JSON.stringify(emptyRequest));
    requestPost.method = 'POST';
    requestPost.path = '/v3/mail/send';
    requestPost.body = requestBody;
    sg.API(requestPost, function (error, response) {
        //console.log(response.statusCode);
        // console.log(response.body);
        // console.log(response.headers);
    })

}

function storeToken(userId, access_token) {
    //store id / token to the db
}

function oAccessToken(userid,email,accesstoken) {
    this.userid = userid;
    this.email = email;
    this.accesstoken = accesstoken;
    this.expires = getCurrentDate();
}

function getCurrentDate() {
    var dateTime = require('node-datetime');
    var dt = dateTime.create();
    dt.offsetInDays(1);
    var formatted = dt.format('Y-m-d H:M:S');
    return formatted;
}

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

<commit_msg>notify_police removed unused code<commit_after>require('dotenv').config();
var util = require('util');

module.exports = function (context, req) {

    var statusCode = 400;
    var responseBody = "Invalid request object";

    if (typeof req.body != 'undefined' && typeof req.body == 'object') {

        statusCode = 201;
        //context.bindings.outTable = req.body;
        var myReq = req.body;
        var myToken = new oAccessToken(myReq.userid,myReq.email,guid());

        //save to document db
        context.bindings.out = myToken;

        //send mail
        sendMail(myToken.userid,myToken.email,myToken.accesstoken);

        responseBody = "Access Token Created, Email Sent";
    }

    context.res = {
        status: statusCode,
        body: responseBody
    };

    context.done();
}

function sendMail(userid,email,token) {

    console.log('Sending Notification');

    var toEmail = email;
    var userId = userid
    var userToken = token;
    var profileUrl = util.format("%s%s?access_token=%s",process.env.DashboardProfileUrl, userId, userToken);

    //console.log('------>' + profileUrl);

    var msgContent = util.format("Please view the profile here: %s", profileUrl);

    var helper = require('sendgrid').mail;

    from_email = new helper.Email(process.env.NotifyEmailFrom);
    to_email = new helper.Email(toEmail);
    subject = "Missing Children of Canada Alert";
    content = new helper.Content("text/plain", msgContent);
    mail = new helper.Mail(from_email, subject, to_email, content);

    // Set to high importance
    header = new helper.Header("Priority", "Urgent");
    mail.addHeader(header);
    header = new helper.Header("Importance", "high");
    mail.addHeader(header);

    var sg = require('sendgrid')(process.env.SendGridAPIKey);

    var requestBody = mail.toJSON();
    var emptyRequest = require('sendgrid-rest').request;
    var requestPost = JSON.parse(JSON.stringify(emptyRequest));
    requestPost.method = 'POST';
    requestPost.path = '/v3/mail/send';
    requestPost.body = requestBody;
    sg.API(requestPost, function (error, response) {
        //console.log(response.statusCode);
        // console.log(response.body);
        // console.log(response.headers);
    })

}

function oAccessToken(userid,email,accesstoken) {
    this.userid = userid;
    this.email = email;
    this.accesstoken = accesstoken;
    this.expires = getCurrentDate();
}

function getCurrentDate() {
    var dateTime = require('node-datetime');
    var dt = dateTime.create();
    dt.offsetInDays(1);
    var formatted = dt.format('Y-m-d H:M:S');
    return formatted;
}

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

<|endoftext|>


<commit_before>
//TODO: Add imports
import mcqTmpl from './mcq-view-mcq.html!text';
import mcqEditTmpl from './mcq-view-mcq-edit.html!text';
import mcqStart from './mcq-view-start.html!text';

const noop = () => undefined;

function mcqQuestionFactory(){
  var self = this;
  self.questions = {
    list:[],

  }
  return {
    create: function(){

    }
  }
}

export function editMcqController(initialData, challengeService, $filter,$mdDialog, urlFor, $location){
  var self = this;

  // Checks if all questions have at least one answer

  self.task = initialData.data.task;
  console.log("the initial edit data is........", initialData);
  var questions = angular.fromJson(self.task.mcqQuestions);
  var savedAnswers = angular.fromJson(initialData.savedAnswers.$value);
  self.questions = builtMCQ(questions, savedAnswers);

  function builtMCQ(questions, savedAnswers){
    for(var i = 0; i < questions.length; i ++){
      questions[i].answers = savedAnswers[i];
    }
    return questions;
  }
  self.isMcqValid = checkMCQValid();
  // Save mcq question to database.

  //todo: clean up the form before submitting. e.g. when toggled, vid entered, but toggled off
  self.save = function(questions){
    var setAnswers = [];

    for(var i = 0; i < questions.length; i ++){
      var answers = questions[i].answers;
      setAnswers.push(answers)
      delete questions[i].answers;
    }

    // Check does questions contain answers?
    console.log(questions);

    // Check answer list
    console.log(setAnswers);

    // Change questions into JSON text
    var answersJsonText = angular.toJson(questions);
    console.log(answersJsonText);

    // Save function defined in challenges.js
    // Parameters: event, taskid, task, taskType, isOpen
    var event = initialData.data.event;
    var task = self.task;
    var taskId = task.$id;
    var taskType = initialData.data.taskType;
    var isOpen = initialData.data.isOpen;
    task.mcqQuestions = answersJsonText;
    task.answers = angular.toJson(setAnswers);
    console.log(task);
    challengeService.update(event, taskId, task,taskType, isOpen);
  }

  // Add question when add question button is clicked
  self.addQuestion = function(){
    var question = {
      text:"",
      answers:[],
      options:[
        {
          text:""
        }
      ]
    }

    // Push new question object into questions list
    self.questions.push(question);
    checkMCQValid();
  }
  function checkMCQValid(){
    for (var i = 0; i < self.questions.length; i ++){
      if(self.questions[i].answers.length == 0){
        self.isMcqValid = false;

        return;
      }
    }
    self.isMcqValid = true;
  }
  self.removeQuestion = function(ev,itemIndex) {

    var confirm = $mdDialog.confirm()
        .title('Would you like to delete this question?')
        .textContent('This question and its option(s) will be deleted. Do you wish to proceed?')
        .ariaLabel('Question deletion')
        .targetEvent(ev)
        .ok('Delete')
        .cancel('Do not delete');
    $mdDialog.show(confirm).then(function() {
      if(itemIndex > -1){
        var removed = self.questions.splice(itemIndex,1);
        console.log('Removed : ', removed);
        console.log(self.questions);
        checkMCQValid();
      }
    });
  };

  // Functionality for toggleOption between single answer and multi ans functionality
  // Needs further review though..
  // Is it better to set the answers as default multiple and the users will just set 1..n answers?
  self.toggleOption = function(question, itemIndex){
    console.log('Index being deleted...', itemIndex)
    var idx = question.answers.indexOf(itemIndex);
    if(idx > -1){
      var removed = question.answers.splice(idx,1);
      console.log(removed);
    }else{
      question.answers.push(itemIndex);
    }
    console.log(question.answers);
    checkMCQValid();
  }

  // Add new option to question
  self.addOption = function (question) {
    // Get options
    question.options.push({
      text:""
    });
    checkMCQValid();
  }

  // Delete options
  self.removeOption = function(question, itemIndex) {
    question.options.splice(itemIndex,1);
    var idxOfAns = question.answers.indexOf(itemIndex);
    if(idxOfAns > -1){
      var removedAns = question.answers.splice(idxOfAns,1);
      console.log('Removed an answer: ', removedAns);
    }
    for(var i = 0; i < question.answers.length; i ++){
      var ans = question.answers[i];
      if(ans > itemIndex){
        question.answers[i] = ans - 1;
      }
    }
    console.log(question.options);
    checkMCQValid();
  }

  //todo:add back button controls here
  self.discardChanges = function (ev){
    var confirm = $mdDialog.confirm()
        .title('Would you like to discard your changes?')
        .textContent('All of the information input will be discarded. Are you sure you want to continue?')
        .ariaLabel('Discard changes')
        .targetEvent(ev)
        .ok('Cancel Editing')
        .cancel('Continue Editing');
    $mdDialog.show(confirm).then(function() {
      // decided to discard data, bring user to previous page

      //todo: link back to previous page
      //$location.path(urlFor('editEventTask', {eventId: initialData.event.$id},{taskId: task.$id}));
      $location.path(urlFor('oneEvent', {eventId: initialData.event.$id}));
    })
  }

}
editMcqController.$inject = [
    'initialData',
    'challengeService',
    '$filter',
    '$mdDialog',
    'urlFor',
    '$location'
];

export function startMcqController(initialData, challengeService, clmDataStore, $location, $mdDialog,urlFor ){
  var self = this;
  var data = initialData.data;
  var eventId = data.eventId;
  var taskId = data.taskId;
  var participant = data.participant;
  var correctAnswers = angular.fromJson(initialData.correctAnswers.$value);
  console.log(correctAnswers);
  self.task = data.task;
  var quesFromJson = angular.fromJson(self.task.mcqQuestions);
  self.questions = loadQuestions(quesFromJson);

  function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
      return 0;
    for(var i = arr1.length; i--;) {
      if(arr1[i] !== arr2[i])
        return 0;
    }

    return 1;
  }

  function markQuestions(submittedAnswers){
    console.log('Correct Answers...', correctAnswers);
    console.log('Submitted Answers...', submittedAnswers);
    var score = 0;
    for(var i = 0; i < submittedAnswers.length; i ++){
      score += arraysEqual(submittedAnswers[i], correctAnswers[i]);
    }
    return score;
  }

  function loadQuestions(quesFromJson){
    for(var i = 0; i < quesFromJson.length; i++){
      quesFromJson[i].answers = [];
    }
    return quesFromJson;
  };

  self.submit = function(){
    var submission = {};
    var userAnswers = [];
    for(var i = 0; i < self.questions.length; i++){
      userAnswers.push(self.questions[i].answers);
    }
    submission.userAnswers = userAnswers;
    var score = markQuestions(userAnswers);
    console.log(submission.score);
    var answerString = angular.toJson(submission);
    console.log(answerString);
    clmDataStore.events.submitSolution(eventId, taskId, participant.$id, answerString)
      .then(
        clmDataStore.events.saveScore(eventId, participant.$id, taskId, score)
      ).then(
      $location.path(urlFor('oneEvent',{eventId: eventId}))
    );

  }

  console.log(self.questions);

  self.toggleOption = function(question, itemIndex){
    console.log('Index being deleted...', itemIndex)
    var idx = question.answers.indexOf(itemIndex);
    if(idx > -1){
      var removed = question.answers.splice(idx,1);
      console.log(removed);
    }else{
      question.answers.push(itemIndex);
    }
    console.log(question.answers);
  }

  self.discardChanges = function (ev){
    var confirm = $mdDialog.confirm()
        .title('Would you like to discard your answers?')
        .textContent('All of your answers will be discarded. Are you sure you want to continue?')
        .ariaLabel('Discard answers')
        .targetEvent(ev)
        .ok('Cancel Answering')
        .cancel('Continue Answering');
    $mdDialog.show(confirm).then(function() {
      // decided to discard data, bring user to previous page

      //todo: link back to previous page
      $location.path(urlFor('oneEvent', {eventId: initialData.event.$id}));

    })
  }

}

startMcqController.$inject = [
  'initialData',
  'challengeService',
  'clmDataStore',
  '$location',
    '$mdDialog',
    'urlFor'
];

export function newMcqController(initialData, challengeService, $filter,$mdDialog,urlFor,$location){
  var self = this;

  console.log("the initial new data is........", initialData);

  // Checks if all questions have at least one answer
  self.isMcqValid = false;
  self.task = initialData.task;
  self.questions = [{
    text:"",
    answers:[],
    options:[
      {
        text:""
      }
    ]
  }];

  // Save mcq question to database.

  //todo: clean up the form before submitting. e.g. when toggled, vid entered, but toggled off
  self.save = function(questions){
    var setAnswers = [];

    for(var i = 0; i < questions.length; i ++){
      var answers = questions[i].answers;
      setAnswers.push(answers)
      delete questions[i].answers;
    }

    // Check does questions contain answers?
    console.log(questions);

    // Check answer list
    console.log(setAnswers);

    // Change questions into JSON text
    var answersJsonText = angular.toJson(questions);
    console.log(answersJsonText);

    // Save function defined in challenges.js
    // Parameters: event, taskid, task, taskType, isOpen
    var event = initialData.event;
    var task = initialData.task;
    var taskId = initialData.taskId;
    var taskType = initialData.taskType;
    var isOpen = initialData.isOpen;
    task.mcqQuestions = answersJsonText;
    task.answers = angular.toJson(setAnswers);
    console.log(task);
    challengeService.save(event, taskId, task,taskType, isOpen);
  }

  // Add question when add question button is clicked
  self.addQuestion = function(){
    var question = {
      text:"",
      answers:[],
      options:[
        {
          text:""
        }
      ]
    }

    // Push new question object into questions list
    self.questions.push(question);
    checkMCQValid();
  }
  function checkMCQValid(){
    for (var i = 0; i < self.questions.length; i ++){
      if(self.questions[i].answers.length == 0){
        self.isMcqValid = false;
        return;
      }
    }
    self.isMcqValid = true;
  }
  self.removeQuestion = function(ev,itemIndex) {

    var confirm = $mdDialog.confirm()
        .title('Would you like to delete this question?')
        .textContent('This question and its option(s) will be deleted. Do you wish to proceed?')
        .ariaLabel('Question deletion')
        .targetEvent(ev)
        .ok('Delete')
        .cancel('Do not delete');
    $mdDialog.show(confirm).then(function() {
      if(itemIndex > -1){
        var removed = self.questions.splice(itemIndex,1);
        console.log('Removed : ', removed);
        console.log(self.questions);
        checkMCQValid();
      }
    });
  };

  // Functionality for toggleOption between single answer and multi ans functionality
  // Needs further review though..
  // Is it better to set the answers as default multiple and the users will just set 1..n answers?
  self.toggleOption = function(question, itemIndex){
    console.log('Index being deleted...', itemIndex)
    var idx = question.answers.indexOf(itemIndex);
    if(idx > -1){
      var removed = question.answers.splice(idx,1);
      console.log(removed);
    }else{
      question.answers.push(itemIndex);
    }
    console.log(question.answers);
    checkMCQValid();
  }

  // Add new option to question
  self.addOption = function (question) {
    // Get options
    question.options.push({
      text:""
    });
    checkMCQValid();
  }

  // Delete options
  self.removeOption = function(question, itemIndex) {
    question.options.splice(itemIndex,1);
    var idxOfAns = question.answers.indexOf(itemIndex);
    if(idxOfAns > -1){
      var removedAns = question.answers.splice(idxOfAns,1);
      console.log('Removed an answer: ', removedAns);
    }
    for(var i = 0; i < question.answers.length; i ++){
      var ans = question.answers[i];
      if(ans > itemIndex){
        question.answers[i] = ans - 1;
      }
    }
    console.log(question.options);
    checkMCQValid();
  }

  //todo:back button add here
  self.discardChanges = function (ev){

    var confirm = $mdDialog.confirm()
        .title('Would you like to discard your changes?')
        .textContent('All of the information input will be discarded. Are you sure you want to continue?')
        .ariaLabel('Discard changes')
        .targetEvent(ev)
        .ok('Cancel Editing')
        .cancel('Continue Editing');
    $mdDialog.show(confirm).then(function() {
      // decided to discard data, bring user to previous page

      //todo: link back to previous page
      //$location.path(urlFor('addEventTask', {eventId: initialData.event.$id}));
      $location.path(urlFor('oneEvent', {eventId: initialData.event.$id}));

    })
  }

}
newMcqController.$inject = [
  'initialData',
  'challengeService',
  '$filter',
  '$mdDialog',
    'urlFor',
    '$location'
];

export function starMcqTmpl() {
  return mcqStart;
}
//this export function return the template when creating a new mcq challenge
export function newMcqTmpl(){
    return mcqTmpl;
}

export function editMcqTmpl(){
    return mcqEditTmpl;
}<commit_msg>fixed discardChanges bug<commit_after>
//TODO: Add imports
import mcqTmpl from './mcq-view-mcq.html!text';
import mcqEditTmpl from './mcq-view-mcq-edit.html!text';
import mcqStart from './mcq-view-start.html!text';

const noop = () => undefined;

function mcqQuestionFactory(){
  var self = this;
  self.questions = {
    list:[],

  }
  return {
    create: function(){

    }
  }
}

export function editMcqController(initialData, challengeService, $filter,$mdDialog, urlFor, $location){
  var self = this;

  // Checks if all questions have at least one answer

  self.task = initialData.data.task;
  console.log("the initial edit data is........", initialData);
  var questions = angular.fromJson(self.task.mcqQuestions);
  var savedAnswers = angular.fromJson(initialData.savedAnswers.$value);
  self.questions = builtMCQ(questions, savedAnswers);

  function builtMCQ(questions, savedAnswers){
    for(var i = 0; i < questions.length; i ++){
      questions[i].answers = savedAnswers[i];
    }
    return questions;
  }
  self.isMcqValid = checkMCQValid();
  // Save mcq question to database.

  //todo: clean up the form before submitting. e.g. when toggled, vid entered, but toggled off
  self.save = function(questions){
    var setAnswers = [];

    for(var i = 0; i < questions.length; i ++){
      var answers = questions[i].answers;
      setAnswers.push(answers)
      delete questions[i].answers;
    }

    // Check does questions contain answers?
    console.log(questions);

    // Check answer list
    console.log(setAnswers);

    // Change questions into JSON text
    var answersJsonText = angular.toJson(questions);
    console.log(answersJsonText);

    // Save function defined in challenges.js
    // Parameters: event, taskid, task, taskType, isOpen
    var event = initialData.data.event;
    var task = self.task;
    var taskId = task.$id;
    var taskType = initialData.data.taskType;
    var isOpen = initialData.data.isOpen;
    task.mcqQuestions = answersJsonText;
    task.answers = angular.toJson(setAnswers);
    console.log(task);
    challengeService.update(event, taskId, task,taskType, isOpen);
  }

  // Add question when add question button is clicked
  self.addQuestion = function(){
    var question = {
      text:"",
      answers:[],
      options:[
        {
          text:""
        }
      ]
    }

    // Push new question object into questions list
    self.questions.push(question);
    checkMCQValid();
  }
  function checkMCQValid(){
    for (var i = 0; i < self.questions.length; i ++){
      if(self.questions[i].answers.length == 0){
        self.isMcqValid = false;

        return;
      }
    }
    self.isMcqValid = true;
  }
  self.removeQuestion = function(ev,itemIndex) {

    var confirm = $mdDialog.confirm()
        .title('Would you like to delete this question?')
        .textContent('This question and its option(s) will be deleted. Do you wish to proceed?')
        .ariaLabel('Question deletion')
        .targetEvent(ev)
        .ok('Delete')
        .cancel('Do not delete');
    $mdDialog.show(confirm).then(function() {
      if(itemIndex > -1){
        var removed = self.questions.splice(itemIndex,1);
        console.log('Removed : ', removed);
        console.log(self.questions);
        checkMCQValid();
      }
    });
  };

  // Functionality for toggleOption between single answer and multi ans functionality
  // Needs further review though..
  // Is it better to set the answers as default multiple and the users will just set 1..n answers?
  self.toggleOption = function(question, itemIndex){
    console.log('Index being deleted...', itemIndex)
    var idx = question.answers.indexOf(itemIndex);
    if(idx > -1){
      var removed = question.answers.splice(idx,1);
      console.log(removed);
    }else{
      question.answers.push(itemIndex);
    }
    console.log(question.answers);
    checkMCQValid();
  }

  // Add new option to question
  self.addOption = function (question) {
    // Get options
    question.options.push({
      text:""
    });
    checkMCQValid();
  }

  // Delete options
  self.removeOption = function(question, itemIndex) {
    question.options.splice(itemIndex,1);
    var idxOfAns = question.answers.indexOf(itemIndex);
    if(idxOfAns > -1){
      var removedAns = question.answers.splice(idxOfAns,1);
      console.log('Removed an answer: ', removedAns);
    }
    for(var i = 0; i < question.answers.length; i ++){
      var ans = question.answers[i];
      if(ans > itemIndex){
        question.answers[i] = ans - 1;
      }
    }
    console.log(question.options);
    checkMCQValid();
  }

  //todo:add back button controls here
  self.discardChanges = function (ev){
    var confirm = $mdDialog.confirm()
        .title('Would you like to discard your changes?')
        .textContent('All of the information input will be discarded. Are you sure you want to continue?')
        .ariaLabel('Discard changes')
        .targetEvent(ev)
        .ok('Cancel Editing')
        .cancel('Continue Editing');
    $mdDialog.show(confirm).then(function() {
      // decided to discard data, bring user to previous page

      //todo: link back to previous page
      //$location.path(urlFor('editEventTask', {eventId: initialData.event.$id},{taskId: task.$id}));
      $location.path(urlFor('oneEvent', {eventId: initialData.event.$id}));
    })
  }

}
editMcqController.$inject = [
    'initialData',
    'challengeService',
    '$filter',
    '$mdDialog',
    'urlFor',
    '$location'
];

export function startMcqController(initialData, challengeService, clmDataStore, $location, $mdDialog,urlFor ){
  var self = this;
  var data = initialData.data;
  var eventId = data.eventId;
  var taskId = data.taskId;
  var participant = data.participant;
  var correctAnswers = angular.fromJson(initialData.correctAnswers.$value);
  console.log(correctAnswers);
  self.task = data.task;
  var quesFromJson = angular.fromJson(self.task.mcqQuestions);
  self.questions = loadQuestions(quesFromJson);

  function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
      return 0;
    for(var i = arr1.length; i--;) {
      if(arr1[i] !== arr2[i])
        return 0;
    }

    return 1;
  }

  function markQuestions(submittedAnswers){
    console.log('Correct Answers...', correctAnswers);
    console.log('Submitted Answers...', submittedAnswers);
    var score = 0;
    for(var i = 0; i < submittedAnswers.length; i ++){
      score += arraysEqual(submittedAnswers[i], correctAnswers[i]);
    }
    return score;
  }

  function loadQuestions(quesFromJson){
    for(var i = 0; i < quesFromJson.length; i++){
      quesFromJson[i].answers = [];
    }
    return quesFromJson;
  };

  self.submit = function(){
    var submission = {};
    var userAnswers = [];
    for(var i = 0; i < self.questions.length; i++){
      userAnswers.push(self.questions[i].answers);
    }
    submission.userAnswers = userAnswers;
    var score = markQuestions(userAnswers);
    console.log(submission.score);
    var answerString = angular.toJson(submission);
    console.log(answerString);
    clmDataStore.events.submitSolution(eventId, taskId, participant.$id, answerString)
      .then(
        clmDataStore.events.saveScore(eventId, participant.$id, taskId, score)
      ).then(
      $location.path(urlFor('oneEvent',{eventId: eventId}))
    );

  }

  console.log(self.questions);

  self.toggleOption = function(question, itemIndex){
    console.log('Index being deleted...', itemIndex)
    var idx = question.answers.indexOf(itemIndex);
    if(idx > -1){
      var removed = question.answers.splice(idx,1);
      console.log(removed);
    }else{
      question.answers.push(itemIndex);
    }
    console.log(question.answers);
  }

  self.discardChanges = function (ev){
    var confirm = $mdDialog.confirm()
        .title('Would you like to discard your answers?')
        .textContent('All of your answers will be discarded. Are you sure you want to continue?')
        .ariaLabel('Discard answers')
        .targetEvent(ev)
        .ok('Cancel Answering')
        .cancel('Continue Answering');
    $mdDialog.show(confirm).then(function() {
      // decided to discard data, bring user to previous page

      //todo: link back to previous page
      $location.path(urlFor('oneEvent', {eventId: eventId}));

    })
  }

}

startMcqController.$inject = [
  'initialData',
  'challengeService',
  'clmDataStore',
  '$location',
    '$mdDialog',
    'urlFor'
];

export function newMcqController(initialData, challengeService, $filter,$mdDialog,urlFor,$location){
  var self = this;

  console.log("the initial new data is........", initialData);

  // Checks if all questions have at least one answer
  self.isMcqValid = false;
  self.task = initialData.task;
  self.questions = [{
    text:"",
    answers:[],
    options:[
      {
        text:""
      }
    ]
  }];

  // Save mcq question to database.

  //todo: clean up the form before submitting. e.g. when toggled, vid entered, but toggled off
  self.save = function(questions){
    var setAnswers = [];

    for(var i = 0; i < questions.length; i ++){
      var answers = questions[i].answers;
      setAnswers.push(answers)
      delete questions[i].answers;
    }

    // Check does questions contain answers?
    console.log(questions);

    // Check answer list
    console.log(setAnswers);

    // Change questions into JSON text
    var answersJsonText = angular.toJson(questions);
    console.log(answersJsonText);

    // Save function defined in challenges.js
    // Parameters: event, taskid, task, taskType, isOpen
    var event = initialData.event;
    var task = initialData.task;
    var taskId = initialData.taskId;
    var taskType = initialData.taskType;
    var isOpen = initialData.isOpen;
    task.mcqQuestions = answersJsonText;
    task.answers = angular.toJson(setAnswers);
    console.log(task);
    challengeService.save(event, taskId, task,taskType, isOpen);
  }

  // Add question when add question button is clicked
  self.addQuestion = function(){
    var question = {
      text:"",
      answers:[],
      options:[
        {
          text:""
        }
      ]
    }

    // Push new question object into questions list
    self.questions.push(question);
    checkMCQValid();
  }
  function checkMCQValid(){
    for (var i = 0; i < self.questions.length; i ++){
      if(self.questions[i].answers.length == 0){
        self.isMcqValid = false;
        return;
      }
    }
    self.isMcqValid = true;
  }
  self.removeQuestion = function(ev,itemIndex) {

    var confirm = $mdDialog.confirm()
        .title('Would you like to delete this question?')
        .textContent('This question and its option(s) will be deleted. Do you wish to proceed?')
        .ariaLabel('Question deletion')
        .targetEvent(ev)
        .ok('Delete')
        .cancel('Do not delete');
    $mdDialog.show(confirm).then(function() {
      if(itemIndex > -1){
        var removed = self.questions.splice(itemIndex,1);
        console.log('Removed : ', removed);
        console.log(self.questions);
        checkMCQValid();
      }
    });
  };

  // Functionality for toggleOption between single answer and multi ans functionality
  // Needs further review though..
  // Is it better to set the answers as default multiple and the users will just set 1..n answers?
  self.toggleOption = function(question, itemIndex){
    console.log('Index being deleted...', itemIndex)
    var idx = question.answers.indexOf(itemIndex);
    if(idx > -1){
      var removed = question.answers.splice(idx,1);
      console.log(removed);
    }else{
      question.answers.push(itemIndex);
    }
    console.log(question.answers);
    checkMCQValid();
  }

  // Add new option to question
  self.addOption = function (question) {
    // Get options
    question.options.push({
      text:""
    });
    checkMCQValid();
  }

  // Delete options
  self.removeOption = function(question, itemIndex) {
    question.options.splice(itemIndex,1);
    var idxOfAns = question.answers.indexOf(itemIndex);
    if(idxOfAns > -1){
      var removedAns = question.answers.splice(idxOfAns,1);
      console.log('Removed an answer: ', removedAns);
    }
    for(var i = 0; i < question.answers.length; i ++){
      var ans = question.answers[i];
      if(ans > itemIndex){
        question.answers[i] = ans - 1;
      }
    }
    console.log(question.options);
    checkMCQValid();
  }

  //todo:back button add here
  self.discardChanges = function (ev){

    var confirm = $mdDialog.confirm()
        .title('Would you like to discard your changes?')
        .textContent('All of the information input will be discarded. Are you sure you want to continue?')
        .ariaLabel('Discard changes')
        .targetEvent(ev)
        .ok('Cancel Editing')
        .cancel('Continue Editing');
    $mdDialog.show(confirm).then(function() {
      // decided to discard data, bring user to previous page

      //todo: link back to previous page
      //$location.path(urlFor('addEventTask', {eventId: initialData.event.$id}));
      $location.path(urlFor('oneEvent', {eventId: initialData.event.$id}));

    })
  }

}
newMcqController.$inject = [
  'initialData',
  'challengeService',
  '$filter',
  '$mdDialog',
    'urlFor',
    '$location'
];

export function starMcqTmpl() {
  return mcqStart;
}
//this export function return the template when creating a new mcq challenge
export function newMcqTmpl(){
    return mcqTmpl;
}

export function editMcqTmpl(){
    return mcqEditTmpl;
}<|endoftext|>


<commit_before>/* global require, exports */
/* jshint -W116 */
/*eslint no-use-before-define: 0*/
"use strict";
var fs = require('fs'),
	childProcess = require('child_process'),
	gitcomment = require('./git-comment.js'),
	config = require('./config.js'),
	log = require('./logger.js'),
	scrollbackProcesses = {};

var startScrollback = function(branch, cb) {
	//process.chdir(config.baseDir + 'scrollback-' + branch);
	childProcess.execSync('rm -rf node_modules/');
	try {
		//installing npm
		log.i('installing npm module...');
		childProcess.execSync('npm install');
	} catch (err) {
		log.e(err.message);
	}
	try {
		//installingg bower
		log.i('installing bower...');
		childProcess.execSync('bower install');
	} catch (err) {
		log.e(err.message);
	}

	try {
		//running gulp files
		log.i('running gulp...');
		childProcess.execSync('gulp');
	} catch (err) {
		log.e(err.message);
	}
	//starting scrollback
	log.i('Staging your branch ' + branch);
	try {
		scrollbackProcesses[branch] = childProcess.execSync('sudo start ' + branch);
	} catch (err) {
		log.e(err.message);
	}
	log.i(scrollbackProcesses);
	cb();

};

var deleteDomain = function(branch) { //delete the directory when a pull request is closed
	process.chdir(config.baseDir);
	if (fs.existsSync(config.baseDir + 'scrollback-' + branch)) {
		try {
			childProcess.execSync('sudo service ' + branch + ' stop');
		} catch (err) {
			log.e(err.message);
		}
		childProcess.exec('rm -rf scrollback-' + branch + ' ' + branch + '.nginx.conf ' + branch + '.conf', function(err) {
			if (err) log.e(err);
			log.i('Removing the scrollback-' + branch + ' directory and all config files');
		});
		childProcess.exec('sudo rm ' + config.nginxDir + 'scrollback-' + branch, function(err) {
			if (err) log.e(err);
			log.i('Removing nginx config files');
		});
		childProcess.exec('sudo rm /etc/init/' + branch + '.conf', function(err) {
			if (err) log.e(err);
			log.i('Removing upstart config files');
		});

		childProcess.exec('sudo rm -rf /var/run/scrollback-' + branch, function(err) {
			if (err) log.e(err);
			log.i('Removing upstart config files');
		});
		if (scrollbackProcesses[branch]) {
			//			scrollbackProcesses[branch].kill();

			delete scrollbackProcesses[branch];
		} else {
			log.i("no scrollbackProcesss");
		}
	} else {
		log.i("no scrollback-" + branch + " directory present");
	}
};

var updateDomain = function(branch, pullRequestNo) { //upadate the directory
	if (fs.existsSync(config.baseDir + 'scrollback-' + branch)) {
		process.chdir(config.baseDir + 'scrollback-' + branch);
		log.i(process.cwd());
		childProcess.exec('git pull', function() {
			log.i("updating the repository");
			try {
				//running gulp files
				log.i('running gulp...');
				childProcess.execSync('gulp');
			} catch (err) {
				log.i(err.message);
				startScrollback(branch, function() {
					log.e('Restarting ' + branch + '.stage.scrollback.io ...');
				});
				return;
			}
			//starting scrollback
			log.i('Restarting ' + branch + '.stage.scrollback.io ...');
			childProcess.execSync('sudo restart ' + branch);
		});
	} else createDomain(branch, pullRequestNo);
};

var createDomain = function(branch, pullRequestNo) { //create a new directory
	var port = 7000 + pullRequestNo;
	if (fs.existsSync(config.baseDir + 'scrollback-' + branch)) {
		updateDomain(branch, pullRequestNo);
		return;
	}
	var copyFile = function(readPath, writePath, lineTransform, callback) {
		fs.readFile(readPath, function(err, data) {
			if (err) log.e(err);
			fs.writeFile(
				writePath,
				data.toString('utf-8').split("\n").map(lineTransform).join('\n'),
				function(err1) {
					if (err1) throw err1;
					callback();
				}
			);
		});
	};

	process.chdir(config.baseDir);
	childProcess.exec(
		'git clone --depth 1 --branch ' + branch +
		' https://github.com/scrollback/scrollback.git scrollback-' + branch,
		function(err1) {
			log.i("cloning ur branch...");
			if (err1 !== null) {
				log.e('Error occured while checking out ' + branch, err1.message);
				return;
			}

			var createCallback = (function() {
				var numOps = 0;
				return function() {
					numOps++;
					return function() {
						numOps--;
						if (numOps === 0) {
							nginxOp(branch, function() {
								log.i('reload nginx');
								try {
									childProcess.execSync("sudo nginx -s reload");
								} catch (err) {
									log.e(err.message);
								}
							});
							process.chdir(config.baseDir + 'scrollback-' + branch);
							startScrollback(branch, function() {
								gitcomment.gitComment(branch, pullRequestNo);
							});
						}

					};
				};
			})();

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/server-config.template.js',
				config.baseDir + 'scrollback-' + branch + '/server-config.js',
				function(line) { // line transform function
					return line.replace(/\$branch\b/g, branch).replace(/\$port\b/g, port);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/client-config.template.js',
				config.baseDir + 'scrollback-' + branch + '/client-config.js',
				function(line) { // line transform function
					return line.replace(/\$branch\b/g, branch);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/tools/nginx.conf',
				config.baseDir + branch + '.nginx.conf',
				function(line) { // line transform function
					return line.replace(/\$branch\b/g, branch).replace(/\$port\b/g, port);
					// inside the file, replace $branch with branch name and $port with port no
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/tools/scrollback.template.conf',
				config.baseDir + branch + '.conf',
				function(line) { // line transform function
					return line.replace(/\$branch\b/g, branch);
					// inside the file, replace $branch with branch name
				},

				createCallback()
			);

		});
};

exports.autostage = function(state, branch, pullRequestNo) {
	if (state === 'opened' || state === 'reopened') createDomain(branch, pullRequestNo);
	if (state === "synchronize") {
		updateDomain(branch, pullRequestNo);
		return;
	}
	if (state === 'closed') {
		deleteDomain(branch);
		return;
	}
	//gitcomment.gitComment(branch, pullRequestNo);
};

var nginxOp = function(branch, callback) {
	try {
		childProcess.exec("chmod +x autostage/./run.sh");
	} catch (err) {
		log.e(err.message);
	}
	try {
		childProcess.execSync("autostage/./run.sh " + branch);
	} catch (err) {
		log.e(err.message);
	}
	log.i("can start your server with upstart");
	callback();
};
<commit_msg>testing<commit_after>/* global require, exports */
/* jshint -W116 */
/*eslint no-use-before-define: 0*/
"use strict";
var fs = require('fs'),
	childProcess = require('child_process'),
	gitcomment = require('./git-comment.js'),
	config = require('./config.js'),
	log = require('./logger.js'),
	scrollbackProcesses = {};

var startScrollback = function(branch, cb) {
	//process.chdir(config.baseDir + 'scrollback-' + branch);
	childProcess.execSync('rm -rf node_modules/');
	try {
		//installing npm
		log.i('installing npm module...');
		childProcess.execSync('npm install');
	} catch (err) {
		log.e(err.message);
	}
	try {
		//installingg bower
		log.i('installing bower...');
		childProcess.execSync('bower install');
	} catch (err) {
		log.e(err.message);
	}

	try {
		//running gulp files
		log.i('running gulp...');
		childProcess.execSync('gulp');
	} catch (err) {
		log.e(err.message);
	}
	//starting scrollback
	log.i('Staging your branch ' + branch);
	try {
		scrollbackProcesses[branch] = childProcess.execSync('sudo start ' + branch);
	} catch (err) {
		log.e(err.message);
	}
	log.i(scrollbackProcesses[branch].toString('utf-8'));
	cb();

};

var deleteDomain = function(branch) { //delete the directory when a pull request is closed
	process.chdir(config.baseDir);
	if (fs.existsSync(config.baseDir + 'scrollback-' + branch)) {
		try {
			childProcess.execSync('sudo service ' + branch + ' stop');
		} catch (err) {
			log.e(err.message);
		}
		childProcess.exec('rm -rf scrollback-' + branch + ' ' + branch + '.nginx.conf ' + branch + '.conf', function(err) {
			if (err) log.e(err);
			log.i('Removing the scrollback-' + branch + ' directory and all config files');
		});
		childProcess.exec('sudo rm ' + config.nginxDir + 'scrollback-' + branch, function(err) {
			if (err) log.e(err);
			log.i('Removing nginx config files');
		});
		childProcess.exec('sudo rm /etc/init/' + branch + '.conf', function(err) {
			if (err) log.e(err);
			log.i('Removing upstart config files');
		});

		childProcess.exec('sudo rm -rf /var/run/scrollback-' + branch, function(err) {
			if (err) log.e(err);
			log.i('Removing upstart config files');
		});
		if (scrollbackProcesses[branch]) {
			//			scrollbackProcesses[branch].kill();

			delete scrollbackProcesses[branch];
		} else {
			log.i("no scrollbackProcesss");
		}
	} else {
		log.i("no scrollback-" + branch + " directory present");
	}
};

var updateDomain = function(branch, pullRequestNo) { //upadate the directory
	if (fs.existsSync(config.baseDir + 'scrollback-' + branch)) {
		process.chdir(config.baseDir + 'scrollback-' + branch);
		log.i(process.cwd());
		childProcess.exec('git pull', function() {
			log.i("updating the repository");
			try {
				//running gulp files
				log.i('running gulp...');
				childProcess.execSync('gulp');
			} catch (err) {
				log.i(err.message);
				startScrollback(branch, function() {
					log.e('Restarting ' + branch + '.stage.scrollback.io ...');
				});
				return;
			}
			//starting scrollback
			log.i('Restarting ' + branch + '.stage.scrollback.io ...');
			childProcess.execSync('sudo restart ' + branch);
		});
	} else createDomain(branch, pullRequestNo);
};

var createDomain = function(branch, pullRequestNo) { //create a new directory
	var port = 7000 + pullRequestNo;
	if (fs.existsSync(config.baseDir + 'scrollback-' + branch)) {
		updateDomain(branch, pullRequestNo);
		return;
	}
	var copyFile = function(readPath, writePath, lineTransform, callback) {
		fs.readFile(readPath, function(err, data) {
			if (err) log.e(err);
			fs.writeFile(
				writePath,
				data.toString('utf-8').split("\n").map(lineTransform).join('\n'),
				function(err1) {
					if (err1) throw err1;
					callback();
				}
			);
		});
	};

	process.chdir(config.baseDir);
	childProcess.exec(
		'git clone --depth 1 --branch ' + branch +
		' https://github.com/scrollback/scrollback.git scrollback-' + branch,
		function(err1) {
			log.i("cloning ur branch...");
			if (err1 !== null) {
				log.e('Error occured while checking out ' + branch, err1.message);
				return;
			}

			var createCallback = (function() {
				var numOps = 0;
				return function() {
					numOps++;
					return function() {
						numOps--;
						if (numOps === 0) {
							nginxOp(branch, function() {
								log.i('reload nginx');
								try {
									childProcess.execSync("sudo nginx -s reload");
								} catch (err) {
									log.e(err.message);
								}
							});
							process.chdir(config.baseDir + 'scrollback-' + branch);
							startScrollback(branch, function() {
								gitcomment.gitComment(branch, pullRequestNo);
							});
						}

					};
				};
			})();

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/server-config.template.js',
				config.baseDir + 'scrollback-' + branch + '/server-config.js',
				function(line) { // line transform function
					return line.replace(/\$branch\b/g, branch).replace(/\$port\b/g, port);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/client-config.template.js',
				config.baseDir + 'scrollback-' + branch + '/client-config.js',
				function(line) { // line transform function
					return line.replace(/\$branch\b/g, branch);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/tools/nginx.conf',
				config.baseDir + branch + '.nginx.conf',
				function(line) { // line transform function
					return line.replace(/\$branch\b/g, branch).replace(/\$port\b/g, port);
					// inside the file, replace $branch with branch name and $port with port no
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/tools/scrollback.template.conf',
				config.baseDir + branch + '.conf',
				function(line) { // line transform function
					return line.replace(/\$branch\b/g, branch);
					// inside the file, replace $branch with branch name
				},

				createCallback()
			);

		});
};

exports.autostage = function(state, branch, pullRequestNo) {
	if (state === 'opened' || state === 'reopened') createDomain(branch, pullRequestNo);
	if (state === "synchronize") {
		updateDomain(branch, pullRequestNo);
		return;
	}
	if (state === 'closed') {
		deleteDomain(branch);
		return;
	}
	//gitcomment.gitComment(branch, pullRequestNo);
};

var nginxOp = function(branch, callback) {
	try {
		childProcess.exec("chmod +x autostage/./run.sh");
	} catch (err) {
		log.e(err.message);
	}
	try {
		childProcess.execSync("autostage/./run.sh " + branch);
	} catch (err) {
		log.e(err.message);
	}
	log.i("can start your server with upstart");
	callback();
};
<|endoftext|>


<commit_before>import { h, Component } from 'preact';
import Map, {Marker} from 'google-maps-react';

export class Directions extends Component {
    componentDidUpdate(prevProps) {
        if ((this.props.map !== prevProps.map) ||
            (this.props.position !== prevProps.position) ||
            (this.props.points !== prevProps.points)) {
            this.renderDirections();
        }
    }

    renderDirections() {
        const directionsService = new this.props.google.maps.DirectionsService();
        const directionsDisplay = new this.props.google.maps.DirectionsRenderer();

        directionsDisplay.setMap(this.props.map);
        const request = {
            origin: this.props.points.start,
            destination: this.props.points.stop,
            travelMode: this.props.points.mode
        };

        if (request.destination && request.origin) {
            directionsService.route(request, (result, status) => {
                if (status == 'OK') {
                    directionsDisplay.setDirections(result);
                    console.log('result', result);
                }
            });
        }
    }

    render() {
        return null;
    }

}

export default Directions;<commit_msg>IP-52 Clear directions after new route<commit_after>import { h, Component } from 'preact';
import Map, {Marker} from 'google-maps-react';

export class Directions extends Component {

    constructor() {
        super();
        this.directionsService = null;
        this.directionsDisplay = null;
    }

    componentDidUpdate(prevProps) {
        if ((this.props.map !== prevProps.map) ||
            (this.props.position !== prevProps.position) ||
            (this.props.points !== prevProps.points)) {
            this.renderDirections();
        }
    }

    renderDirections() {
        if (this.directionsService === null || this.directionsDisplay === null) {
            this.directionsService = new this.props.google.maps.DirectionsService();
            this.directionsDisplay = new this.props.google.maps.DirectionsRenderer();
        }

        this.directionsDisplay.setMap(this.props.map);
        const request = {
            origin: this.props.points.start,
            destination: this.props.points.stop,
            travelMode: this.props.points.mode
        };

        if (request.destination && request.origin) {
            this.directionsService.route(request, (result, status) => {
                if (status == 'OK') {
                    this.directionsDisplay.setDirections(result);
                    console.log('result', result);
                }
            });
        }
    }

    render() {
        return null;
    }

}

export default Directions;<|endoftext|>


<commit_before>'use strict';

const fs = require('async-file');
const logger = require('heroku-logger');
const http = require('http');
const path = require('path');
const url = require('url');

const STATIC_ASSETS_PATH = '../ui/build';
const INITIAL_FILE = 'index.html';

const pickContentType = extension => {
  const contentTypes = {
    '.css': 'text/css',
    '.eot': 'application/vnd.ms-fontobject',
    '.html': 'text/html',
    '.ico': 'image/x-icon',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.map': 'application/json',
    '.svg': 'image/svg+xml',
    '.ttf': 'application/font-ttf',
    '.woff': 'application/font-woff',
    '.woff2': 'application/font-woff2'
  };

  return contentTypes[extension];
};

const responseAbend = (response, message) => {
  response.set('Content-Type', 'text/plain');
  response.statusCode = 500;
  response.send(`Internal error: ${message}`);
  response.end();
};

const streamFile = async (filename, response) => {
  const file = path.resolve(__dirname, STATIC_ASSETS_PATH, filename);

  let fd;
  try {
    fd = await fs.open(file, 'r');
  } catch (err) {
    if (err.code === 'ENOENT') {
      return false;
    }

    logger.error(`Problem while opening ${file}: ${err.message}`);
    throw err;
  }

  let stats;
  try {
    stats = await fs.fstat(fd);
  } catch (err) {
    logger.error(`Problem while gettting stats for ${file}: ${err.message}`);
    throw err;
  }

  const ext = path.extname(file);
  const contentType = pickContentType(ext);
  if (contentType === undefined) {
    const message = `Unrecognized extension ${ext} for ${file}`;
    logger.error(message);
    throw new Error(message);
  }

  response.writeHead(200, {
    'Content-Type': contentType,
    'Content-Length': stats.size
  });

  const rs = fs.createReadStream(undefined, { fd });
  rs.on('error', err => {
    rs.end();
    const message = `Problem while reading ${file}: ${err.message}`;
    logger.error(message);
    responseAbend(response, message);
  });

  logger.info(`Streaming file ${file} of size ${stats.size} with content type ${contentType}.`);
  rs.pipe(response);

  return true;
};

const streamRequest = async (pathname, response) => {
  let handled = await streamFile(pathname, response);
  if (!handled) {
    // Handle all the remaining requests so the React app can handle routing.
    handled = await streamFile(INITIAL_FILE, response);
    if (!handled) {
      const message = `Failed to serve ${INITIAL_FILE}.`;
      logger.error(message);
      throw new Error(message);
    }
  }
};

const server = http.createServer((request, response) => {
  logger.info(`HTTP request for ${request.url}.`);

  response.on('error', err => {
    const message = `Problem while writing HTTP response: ${err.message}`;
    logger.error(message);
    responseAbend(response, message);
  });

  if (request.url.startsWith('/api')) {
    response.setHeader('Content-Type', 'application/json');
    response.write('{ "message" : "Hello from the API server!" }', () => {
      response.end();
    });
  } else {
    let { pathname } = url.parse(request.url);
    if (pathname[0] === '/') {
      pathname = pathname.substring(1);
    }
    if (pathname === '') {
      pathname = INITIAL_FILE;
    }

    try {
      streamRequest(pathname, response).then();
    } catch (err) {
      responseAbend(response, err.message);
    }
  }
});

module.exports = server;
<commit_msg>Correctly handle responseAbend().<commit_after>'use strict';

const fs = require('async-file');
const logger = require('heroku-logger');
const http = require('http');
const path = require('path');
const url = require('url');

const STATIC_ASSETS_PATH = '../ui/build';
const INITIAL_FILE = 'index.html';

const pickContentType = extension => {
  const contentTypes = {
    '.css': 'text/css',
    '.eot': 'application/vnd.ms-fontobject',
    '.html': 'text/html',
    '.ico': 'image/x-icon',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.map': 'application/json',
    '.svg': 'image/svg+xml',
    '.ttf': 'application/font-ttf',
    '.woff': 'application/font-woff',
    '.woff2': 'application/font-woff2'
  };

  return contentTypes[extension];
};

const responseAbend = (response, message) => {
  response.setHeader('Content-Type', 'text/plain');
  response.statusCode = 500;
  response.end(`Internal error: ${message}`);
};

const streamFile = async (filename, response) => {
  const file = path.resolve(__dirname, STATIC_ASSETS_PATH, filename);

  let fd;
  try {
    fd = await fs.open(file, 'r');
  } catch (err) {
    if (err.code === 'ENOENT') {
      return false;
    }

    logger.error(`Problem while opening ${file}: ${err.message}`);
    throw err;
  }

  let stats;
  try {
    stats = await fs.fstat(fd);
  } catch (err) {
    logger.error(`Problem while gettting stats for ${file}: ${err.message}`);
    throw err;
  }

  const ext = path.extname(file);
  const contentType = pickContentType(ext);
  if (contentType === undefined) {
    const message = `Unrecognized extension ${ext} for ${file}`;
    logger.error(message);
    throw new Error(message);
  }

  response.writeHead(200, {
    'Content-Type': contentType,
    'Content-Length': stats.size
  });

  const rs = fs.createReadStream(undefined, { fd });
  rs.on('error', err => {
    rs.end();
    const message = `Problem while reading ${file}: ${err.message}`;
    logger.error(message);
    responseAbend(response, message);
  });

  logger.info(`Streaming file ${file} of size ${stats.size} with content type ${contentType}.`);
  rs.pipe(response);

  return true;
};

const streamRequest = async (pathname, response) => {
  let handled = await streamFile(pathname, response);
  if (!handled) {
    // Handle all the remaining requests so the React app can handle routing.
    handled = await streamFile(INITIAL_FILE, response);
    if (!handled) {
      const message = `Failed to serve ${INITIAL_FILE}.`;
      logger.error(message);
      throw new Error(message);
    }
  }
};

const server = http.createServer((request, response) => {
  logger.info(`HTTP request for ${request.url}.`);

  response.on('error', err => {
    const message = `Problem while writing HTTP response: ${err.message}`;
    logger.error(message);
    responseAbend(response, message);
  });

  if (request.url.startsWith('/api')) {
    response.setHeader('Content-Type', 'application/json');
    response.write('{ "message" : "Hello from the API server!" }', () => {
      response.end();
    });
  } else {
    let { pathname } = url.parse(request.url);
    if (pathname[0] === '/') {
      pathname = pathname.substring(1);
    }
    if (pathname === '') {
      pathname = INITIAL_FILE;
    }

    streamRequest(pathname, response).then().catch(err => responseAbend(response, err.message));
  }
});

module.exports = server;
<|endoftext|>


<commit_before>import { gt } from '@ember/object/computed';
import { computed } from '@ember/object';
import Component from '@ember/component';

export default Component.extend({
  // Public API
  result: Object.freeze({}),
  role: 'option',
  groupName: '',
  groupPosition: 0, // Index of this result in the grouped results

  module: computed('result.{project,module}', function () {
    if (this.get('result.project')) {
      return this.get('result.project');
    }
    return this.get('result.module') === 'ember-data' ? 'ember-data' : 'ember'
  }),
  // Private API
  classNames: ['ds-suggestion'],
  attributeBindings: ['role'],
  version: computed('result._tags.[]', function () {
    let versionTag = this.get('result._tags').find(_tag => _tag.indexOf('version:') > -1);
    let versionSegments = versionTag.replace('version:', '').split('.');
    return `${versionSegments[0]}.${versionSegments[1]}`;
  }),
  // Left sidebar should only be displayed for the first result in the group
  _primaryColumn: computed('groupPosition,groupName', function () {
    const { groupName, groupPosition } = this;
    return groupPosition === 0? groupName : '';
  }),
  isSecondary: gt('groupPosition', 0)

});
<commit_msg>fix searching for ember-data items<commit_after>import { gt } from '@ember/object/computed';
import { computed } from '@ember/object';
import Component from '@ember/component';

export default Component.extend({
  // Public API
  result: Object.freeze({}),
  role: 'option',
  groupName: '',
  groupPosition: 0, // Index of this result in the grouped results

  module: computed('result.{project,module}', function () {
    if (this.get('result.project')) {
      return this.get('result.project');
    }
    let module = this.get('result.module');
    if (module.includes('ember-data')) {
      return 'ember-data';
    }
    return 'ember';
  }),
  // Private API
  classNames: ['ds-suggestion'],
  attributeBindings: ['role'],
  version: computed('result._tags.[]', function () {
    let versionTag = this.get('result._tags').find(_tag => _tag.indexOf('version:') > -1);
    let versionSegments = versionTag.replace('version:', '').split('.');
    return `${versionSegments[0]}.${versionSegments[1]}`;
  }),
  // Left sidebar should only be displayed for the first result in the group
  _primaryColumn: computed('groupPosition,groupName', function () {
    const { groupName, groupPosition } = this;
    return groupPosition === 0? groupName : '';
  }),
  isSecondary: gt('groupPosition', 0)

});
<|endoftext|>


<commit_before>/**
 * Insert List.V2 View Class
 * @class View.List.V2.Insert
 * @author Bruno Santos, Jerome Vial
 */
define(function(require, exports, module) {

  var _log = __debug('view-core-listV2-insert').defineLevel();

  var Insert = new Class({

    /**
     * new info
     * @return {void}
     */
    new: function(info) {
      _log.debug('new', info);

      //handle view in arg
      if (info === this) {
        info = {};
      }

      info = info || {};

      var newInfo = {
        _id: 'new',
        type: this.options.data.type,
        nodes: []
      };

      info = Object.merge(newInfo, info);

      if (
        this.options.data &&
        this.options.data._id &&
        info.nodes.indexOf(this.options.data._id) === -1
      ) {
        info.nodes.push(this.options.data._id);
      }

      this.remove('new');
      this._setInfo(info);

      this.select('new');
    },

    /**
     * remove new info if exist
     * @return {void}
     */
    removeNew: function() {
      this.remove('new');
    },

    /**
     * set info
     * @param {Object} info
     */
    _setInfo: function(info) {
      _log.debug('_setInfo', info);

      if (this.virtualSize === undefined) {
        this._setList([]);
      }

      if (typeof info !== 'object' || this.virtualSize === undefined) {
        _log.warn('invalid info type', info);
        return;
      }

      //check if the id is in the list
      var exist = this._getInfoById(info._id);
      if (exist) {
        this.updateInfo(info);
        this.select(this.selectedId);
        return;
      }

      this.remove('new');

      this.virtualSize++;

      this.virtualList.unshift(info);

      this.renderInfo(info, 1, 'top');

      this.element.scrollTop = 0;
      this._scroll();
      //this.processInfos();
    },

    /**
     * update info
     * @param  {Object} info
     * @return {void}
     */
    updateInfo: function(info) {
      _log.debug('updateInfo', info);

      //update element
      var oldEl = this._getElById(info._id);
      var newEl = this.render(info, this);

      //update the old el if has been already rendered
      if (oldEl) {
        newEl.replaces(oldEl);
      }

      //update virtualList
      for (var i = 0; i < this.virtualList.length; i++) {
        var oldInfo = this.virtualList[i];

        if (oldInfo && oldInfo._id === info._id) {
          this.virtualList[i] = info;
          break;
        }
      }

      //update _tempCache
      if (this._tempCache.length) {
        for (var j = 0; j < this._tempCache.length; j++) {
          var oldInfo = this._tempCache[j];

          if (oldInfo && oldInfo._id === info._id) {
            this._tempCache[j] = info;
            break;
          }
        }
      }
    },

  });

  module.exports = Insert;

});
<commit_msg>fix set info method in list view: return when there is a search/filter result in the list<commit_after>/**
 * Insert List.V2 View Class
 * @class View.List.V2.Insert
 * @author Bruno Santos, Jerome Vial
 */
define(function(require, exports, module) {

  var _log = __debug('view-core-listV2-insert').defineLevel();

  var Insert = new Class({

    /**
     * new info
     * @return {void}
     */
    new: function(info) {
      _log.debug('new', info);

      //handle view in arg
      if (info === this) {
        info = {};
      }

      info = info || {};

      var newInfo = {
        _id: 'new',
        type: this.options.data.type,
        nodes: []
      };

      info = Object.merge(newInfo, info);

      if (
        this.options.data &&
        this.options.data._id &&
        info.nodes.indexOf(this.options.data._id) === -1
      ) {
        info.nodes.push(this.options.data._id);
      }

      this.remove('new');
      this._setInfo(info);

      this.select('new');
    },

    /**
     * remove new info if exist
     * @return {void}
     */
    removeNew: function() {
      this.remove('new');
    },

    /**
     * set info
     * @param {Object} info
     */
    _setInfo: function(info) {
      _log.debug('_setInfo', info);

      if (this.virtualSize === undefined) {
        this._setList([]);
      }

      if (typeof info !== 'object' || this.virtualSize === undefined) {
        _log.warn('invalid info type', info);
        return;
      }

      //check if the id is in the list
      var exist = this._getInfoById(info._id);
      if (exist) {
        this.updateInfo(info);
        this.select(this.selectedId);
        return;
      }

      // return if there is a search or filter result in the list
      // maybe the list should be updated
      // if the info is part of the search/filter result
      if (this._tempCache.length) {
        return;
      }

      this.remove('new');

      this.virtualSize++;

      this.virtualList.unshift(info);

      this.renderInfo(info, 1, 'top');

      this.element.scrollTop = 0;
      this._scroll();
    },

    /**
     * update info
     * @param  {Object} info
     * @return {void}
     */
    updateInfo: function(info) {
      _log.debug('updateInfo', info);

      //update element
      var oldEl = this._getElById(info._id);
      var newEl = this.render(info, this);

      //update the old el if has been already rendered
      if (oldEl) {
        newEl.replaces(oldEl);
      }

      //update virtualList
      for (var i = 0; i < this.virtualList.length; i++) {
        var oldInfo = this.virtualList[i];

        if (oldInfo && oldInfo._id === info._id) {
          this.virtualList[i] = info;
          break;
        }
      }

      //update _tempCache
      if (this._tempCache.length) {
        for (var j = 0; j < this._tempCache.length; j++) {
          var oldInfo = this._tempCache[j];

          if (oldInfo && oldInfo._id === info._id) {
            this._tempCache[j] = info;
            break;
          }
        }
      }
    },

  });

  module.exports = Insert;

});
<|endoftext|>


<commit_before>////////////////////////////////////////////

var express = require('express')
var app = express();
var fs = require('fs');
var request = require("request");
var marked = require('marked');
var bodyParser = require('body-parser');
var beautify = require('js-beautify').html;
var Promise = require('promise');
app.use(bodyParser.json());

marked.setOptions({
    renderer: new marked.Renderer(),
    gfm: true,
    tables: true,
    breaks: false,
    pedantic: false,
    sanitize: true,
    smartLists: true,
    smartypants: false
});

/////////////////////////////////////////////

var github_name = '';
var repo_name = '';
var post_template_url = './templates/template.html';
var contents_template_url = './templates/contents-template.html';

/////////////////////////////////////////////

var contents = new Contents();

/////////////////////////////////////////////

// construct a new post
function Post(title, body, author, author_url, author_icon_url, tags, time) {
    this.title = title;
    this.body = body;
    this.author = author;
    this.author_url = author_url;
    this.author_icon_url = author_icon_url;
    this.tags = tags;
    this.time = time;
    this.html = marked(this.body);
    this.url = './' + this.title.replaceAll(' ', '') + '.html'
}

String.prototype.replaceAll = function(searchvalue, newvalue) {
    var newstring = this
    var index = this.indexOf(searchvalue)

    while(index > -1) {
      newstring = newstring.replace(searchvalue, newvalue)
      index = newstring.indexOf(searchvalue)
    }

    return newstring
}

// write a post to file, including html templating logic (should be separated)
Post.prototype.write_to_file = function() {

    var post = this

    fs.readFile(post_template_url, function(err, data) {
        if (err) throw err;
        data = String(data);
        data = data.replaceAll('{{title}}', post.title);
        data = data.replaceAll('{{body}}', post.html);
        data = data.replaceAll('{{author_url}}', post.author_url);
        data = data.replaceAll('{{author_icon_url}}', post.author_icon_url)
        data = data.replaceAll('{{author}}', post.author)
        data = data.replaceAll('{{time}}', post.time)
        data = data.replaceAll('{{tags}}', buttons_from_tags(post.tags));

        data = beautify(data, { indent_size: 2 });

        console.log('template \'' + post_template_url + '\' read.');

        fs.writeFile(post.url, data, function(err) {
            if (err) {
                console.log(err);
            } else {
                console.log('post \'' + post.title + '\' written.');
            }
        });
    });
}

/////////////////////////////////////////////

// construct a new contents page, a set of post names
// and urls with an associated title.
function Contents() {
    this.post_names = [];
    this.post_urls = [];
}

// add a new post to the contents page, if the post already
// exists, replace it.
Contents.prototype.add_post = function(post_name, post_url) {

    var index = this.post_names.indexOf(post_name);

    if (index > -1) {
        this.post_names[index] = post_name;
        this.post_url[index] = post_url;
    } else {
        this.post_names.push(post_name);
        this.post_urls.push(post_url);
    }
}

// write the contents page to a file
Contents.prototype.write_to_file = function() {

    var contents = this;

    fs.readFile(contents_template_url, function(err, data) {
        if (err) throw err;
        data = String(data);

        var button = '{{body}}';
        var new_body = '';

        for (i in contents.post_names) {
            var post_name = contents.post_names[i];
            var post_url = contents.post_urls[i];

            var new_button = button.replace('{{body}}', post_name).replace('{{href}}', post_url);
            new_body += new_button;
        }

        data = data.replace('{{body}}', new_body);

        console.log('template \'' + contents_template_url + '\' read.');

        fs.writeFile("./contents.html", data, function(err) {
            if (err) throw err;

            console.log('contents written.');
        });
    });
}

/////////////////////////////////////////////

// generate a list of buttons from a list of tags
function buttons_from_tags(tags) {
    var row = '
{{body}}
';
    var button = '<button class="button-small button-outline" style="margin: 5px;">{{body}}</button>';
    var columns = '';

    for (i in tags) {
        var tag = tags[i];
        columns += button.replace('{{body}}', tag);
    }

    var new_row = row.replace('{{body}}', columns);

    return new_row;
}

// Convert a github issue into a post
function parse_issue(issue) {
    var post_title = issue.title.replace('/', '').replace('  ', ' '); //temp fix for 'name / name'
    var post_body = issue.body;

    var user_name = '';
    var user_url = '';
    var user_icon = '';

    if (issue.assignees.length > 0) {
        user_name = issue.assignees[0].login;
        user_url = issue.assignees[0].html_url;
        user_icon = issue.assignees[0].avatar_url;
    }

    var post_tags = [];

    var post_time = issue.updated_at;

    for (p in issue.labels) {
        post_tags.push(issue.labels[p].name);
    }

    return new Post(post_title, post_body, user_name, user_url, user_icon, post_tags, post_time);
}

// get all of the issues in a given github users repo
function get_all_issues(name, repo) {
    var options = {
        method: 'GET',
        url: 'https://api.github.com/repos/' + name + '/' + repo + '/issues',
        headers: {
            'User-Agent': name,
            'cache-control': 'no-cache'
        }
    };

    return new Promise(function(fulfill, reject) {
        request(options, function(error, response, body) {
            if (error) reject(error);
            else fulfill(JSON.parse(body));
        });
    });
}

// called on application start
function start() {

    get_all_issues(github_name, repo_name).done(function(issues) {

        for (i in issues) {
            var post = parse_issue(issues[i]);
            post.write_to_file();
            contents.add_post(post.title, post.url.replace('.html', ''));
        }

        contents.write_to_file();
    });
}

// redirect root to contents
app.get('/', function(req, res) {
    res.redirect('/contents');
});

// request to view a blog post
app.get('/:postname', function(req, res) {

    var path = './' + req.params.postname + '.html';

    if (fs.existsSync(path)) {
        var f = fs.readFileSync(path);
        res.send(String(f));
    } else {
        res.send('404 how did you even get here?');
    }
});

// webhook call from github issues
app.post('/issue', function(req, res) {

    console.log(String(req.body.action));
    console.log(req.body.issue);

    res.send('issue logged');

    var post = parse_issue(req.body.issue);
    post.write_to_file();

    contents.add_post(post.title, post.url.replace('.html', ''));
    contents.write_to_file();
});

var args = process.argv.slice(2)
if(args.length != 2) {
  console.log('usage: node gityll.js port repo-url')
  process.exit()
}

var port = args[0]
var url_split = args[1].split('/')
github_name = url_split[url_split.length - 2]
repo_name = url_split[url_split.length - 1]
console.log(github_name + ", " + repo_name)

app.listen(port);
start();
<commit_msg>added content directory for posts<commit_after>////////////////////////////////////////////

var express = require('express')
var app = express();
var fs = require('fs');
var request = require("request");
var marked = require('marked');
var bodyParser = require('body-parser');
var beautify = require('js-beautify').html;
var Promise = require('promise');
app.use(bodyParser.json());

marked.setOptions({
    renderer: new marked.Renderer(),
    gfm: true,
    tables: true,
    breaks: false,
    pedantic: false,
    sanitize: true,
    smartLists: true,
    smartypants: false
});

/////////////////////////////////////////////

var github_name = '';
var repo_name = '';
var post_template_url = './templates/template.html';
var contents_template_url = './templates/contents-template.html';
var content_url = './content/';

/////////////////////////////////////////////

var contents = new Contents();

/////////////////////////////////////////////

// construct a new post
function Post(title, body, author, author_url, author_icon_url, tags, time) {
    this.title = title;
    this.body = body;
    this.author = author;
    this.author_url = author_url;
    this.author_icon_url = author_icon_url;
    this.tags = tags;
    this.time = time;
    this.html = marked(this.body);
    this.url = this.title.replaceAll(' ', '') + '.html'
}

String.prototype.replaceAll = function(searchvalue, newvalue) {
    var newstring = this
    var index = this.indexOf(searchvalue)

    while(index > -1) {
      newstring = newstring.replace(searchvalue, newvalue)
      index = newstring.indexOf(searchvalue)
    }

    return newstring
}

// write a post to file, including html templating logic (should be separated)
Post.prototype.write_to_file = function() {

    var post = this

    fs.readFile(post_template_url, function(err, data) {
        if (err) throw err;
        data = String(data);
        data = data.replaceAll('{{title}}', post.title);
        data = data.replaceAll('{{body}}', post.html);
        data = data.replaceAll('{{author_url}}', post.author_url);
        data = data.replaceAll('{{author_icon_url}}', post.author_icon_url)
        data = data.replaceAll('{{author}}', post.author)
        data = data.replaceAll('{{time}}', post.time)
        data = data.replaceAll('{{tags}}', buttons_from_tags(post.tags));

        data = beautify(data, { indent_size: 2 });

        console.log('template \'' + post_template_url + '\' read.');

        fs.writeFile(content_url + post.url, data, function(err) {
            if (err) {
                console.log(err);
            } else {
                console.log('post \'' + post.title + '\' written.');
            }
        });
    });
}

/////////////////////////////////////////////

// construct a new contents page, a set of post names
// and urls with an associated title.
function Contents() {
    this.post_names = [];
    this.post_urls = [];
}

// add a new post to the contents page, if the post already
// exists, replace it.
Contents.prototype.add_post = function(post_name, post_url) {

    var index = this.post_names.indexOf(post_name);

    if (index > -1) {
        this.post_names[index] = post_name;
        this.post_url[index] = post_url;
    } else {
        this.post_names.push(post_name);
        this.post_urls.push(post_url);
    }
}

// write the contents page to a file
Contents.prototype.write_to_file = function() {

    var contents = this;

    fs.readFile(contents_template_url, function(err, data) {
        if (err) throw err;
        data = String(data);

        var button = '{{body}}';
        var new_body = '';

        for (i in contents.post_names) {
            var post_name = contents.post_names[i];
            var post_url = contents.post_urls[i];

            var new_button = button.replace('{{body}}', post_name).replace('{{href}}', post_url);
            new_body += new_button;
        }

        data = data.replace('{{body}}', new_body);

        console.log('template \'' + contents_template_url + '\' read.');

        fs.writeFile(content_url + "contents.html", data, function(err) {
            if (err) throw err;

            console.log('contents written.');
        });
    });
}

/////////////////////////////////////////////

// generate a list of buttons from a list of tags
function buttons_from_tags(tags) {
    var row = '
{{body}}
';
    var button = '<button class="button-small button-outline" style="margin: 5px;">{{body}}</button>';
    var columns = '';

    for (i in tags) {
        var tag = tags[i];
        columns += button.replace('{{body}}', tag);
    }

    var new_row = row.replace('{{body}}', columns);

    return new_row;
}

// Convert a github issue into a post
function parse_issue(issue) {
    var post_title = issue.title.replace('/', '').replace('  ', ' '); //temp fix for 'name / name'
    var post_body = issue.body;

    var user_name = '';
    var user_url = '';
    var user_icon = '';

    if (issue.assignees.length > 0) {
        user_name = issue.assignees[0].login;
        user_url = issue.assignees[0].html_url;
        user_icon = issue.assignees[0].avatar_url;
    }

    var post_tags = [];

    var post_time = issue.updated_at;

    for (p in issue.labels) {
        post_tags.push(issue.labels[p].name);
    }

    return new Post(post_title, post_body, user_name, user_url, user_icon, post_tags, post_time);
}

// get all of the issues in a given github users repo
function get_all_issues(name, repo) {
    var options = {
        method: 'GET',
        url: 'https://api.github.com/repos/' + name + '/' + repo + '/issues',
        headers: {
            'User-Agent': name,
            'cache-control': 'no-cache'
        }
    };

    return new Promise(function(fulfill, reject) {
        request(options, function(error, response, body) {
            if (error) reject(error);
            else fulfill(JSON.parse(body));
        });
    });
}

// called on application start
function start() {
    if(!fs.exists(content_url)) {
        fs.mkdirSync(content_url);
    }

    get_all_issues(github_name, repo_name).done(function(issues) {

        for (i in issues) {
            var post = parse_issue(issues[i]);
            post.write_to_file();
            contents.add_post(post.title, post.url.replace('.html', ''));
        }

        contents.write_to_file();
    });
}

// redirect root to contents
app.get('/', function(req, res) {
    res.redirect('/contents');
});

// request to view a blog post
app.get('/:postname', function(req, res) {

    var path = './' + content_url + req.params.postname + '.html';

    if (fs.existsSync(path)) {
        var f = fs.readFileSync(path);
        res.send(String(f));
    } else {
        res.send('404 how did you even get here?');
    }
});

// webhook call from github issues
app.post('/issue', function(req, res) {

    console.log(String(req.body.action));
    console.log(req.body.issue);

    res.send('issue logged');

    var post = parse_issue(req.body.issue);
    post.write_to_file();

    contents.add_post(post.title, post.url.replace('.html', ''));
    contents.write_to_file();
});

var args = process.argv.slice(2)
if(args.length != 2) {
  console.log('usage: node gityll.js port repo-url')
  process.exit()
}

var port = args[0]
var url_split = args[1].split('/')
github_name = url_split[url_split.length - 2]
repo_name = url_split[url_split.length - 1]
console.log(github_name + ", " + repo_name)

app.listen(port);
start();
<|endoftext|>