<commit_before>VISH.Editor.Quiz = (function(V,$,undefined){
	var maxNumMultipleChoiceOptions = 6; // maximum input options
	var choicesLetters = ['a)','b)','c)','d)','e)','f)'];

	var addQuizOptionButtonClass = "add_quiz_option_button";
	var deleteQuizOptionButtonClass = "delete_quiz_option_button";

	var init = function(){

		$(document).on('click','.add_quiz_option_button', addOptionInQuiz);
		$(document).on('click','.'+ deleteQuizOptionButtonClass, _removeOptionInQuiz);
		/*var myInput = $(document).find(".initTextDiv > font");
		//$(myInput).watermark(VISH.Editor.I18n.getTrans("i.SearchContent"));
		$(myInput).keydown(function(event) {
				V.Debugging.log("enter key detected : " + event.keyCode);

			if(event.keyCode == 13) {

				addOptionInQuiz('multiplechoice');
				//VISH.Editor.Video.Youtube.requestYoutubeData($(myInput).val());
				$(myInput).blur();
			}
		}); */

	};
	////////////
	// Tabs and fancybox
	////////////
	var onLoadTab = function (tab) {
	};

	//Function called from quiz fancybox
	var addQuiz = function(quiz_type, area, num_options) {
		var current_area;
		var current_num_options;
		if(area) {
			current_area = $("#"+area);
		}
		else {
			current_area = VISH.Editor.getCurrentArea();
		}
		if(num_options){
			current_num_options = num_options;
		}
		else {
			current_num_options = 0;

		}

		switch (quiz_type) {
			case "open":
				// _addOpenQuiz();
				 break;
			case "multiplechoice":

				_addMultipleChoiceQuiz(current_area, current_num_options);
				//hide & show fancybox elements
				VISH.Utils.loadTab('tab_quizes');
				 break;
			case "truefalse":
				// _addTrueFalseQuiz();
			 	break;
			default:
				break;
		}
		$.fancybox.close();
	};

	var drawQuiz = function(quiz_type, zone_id, question, options, quiz_id){

		var zone;
		if(zone_id) {
			zone = "#"+ zone_id;
		} else {

			zone = ".current";
		}

		switch (quiz_type) {
			case "multiplechoice":

				if (question) {
					$(zone).find(".value_multiplechoice_question_in_zone").children().remove();
					$(zone).find(".value_multiplechoice_question_in_zone").append(question);
				}
				if (options) {
					var inputs = $(zone).find(".multiplechoice_option_in_zone"); //all inputs (less or equal than options received)
					for (var i = 0;  i <= options.length - 1; i++) {
						$(inputs[i]).children().remove();
						$(inputs[i]).append(options[i].container);
					}
				}
				if(quiz_id) {
					$(zone).find('input[name="quiz_id"]').val(quiz_id);
				}
				$(zone).find(".multiplechoice_option_in_zone").attr("rows", "1");
				break;
			case "open":

			break;

			case "truefalse":

			break;

			default:

			break;
		}
	};

	var _addMultipleChoiceQuiz = function(area, num_options) {
		var current_area;
		var current_num_options;
		var quiz = VISH.Dummies.getQuizDummy("multiplechoice", V.Slides.getSlides().length);
		if(area){
			current_area = area;
		}
		else {
			//if no param
			current_area = VISH.Editor.getCurrentArea();
		}
		if (num_options) {
		 	current_num_options = num_options;
		}
		else {
			current_num_options = 0;
		}

		current_area.find(".menuselect_hide").remove();
		current_area.attr('type','quiz');
		current_area.attr('quiztype','multiplechoice');
		//add the quizDummy (empty quiz) into the area (zone)
		current_area.append(quiz);
		V.Editor.addDeleteButton(current_area);

		for (var i=0; i <= num_options ; i++) {
			addOptionInQuiz('multiplechoice', current_area);
		}
		//launchTextEditorInTextArea(current_area, "multiplechoice");

	};

	var addOptionInQuiz = function (quiz_type, area) {
		var current_area;
		var current_quiz_type;
		if(area) {
			current_area = area;
		}
		else {
			current_area = V.Editor.getCurrentArea();
		}

		if(typeof quiz_type =="string"){ //when add complete multiplechoice quiz
			current_quiz_type = quiz_type;
		}
		else if(typeof quiz_type == "object") { //when event comes from click or enter (not implemented)
			current_quiz_type = $(current_area).attr("quiztype");
		}
		else {
			V.Debugging("another type ");

		}

		switch (current_quiz_type) {

			case "multiplechoice":

				var quiz_option = VISH.Dummies.getQuizOptionDummy(current_quiz_type);

				var current_options = $(current_area).find(".li_mch_options_in_zone").size();
				var option_number;
				//remove add icon and insert remove icon
				if(current_options>0) {
						option_number = current_options;
						$($(current_area).find(".li_mch_options_in_zone")[parseInt(current_options)-1]).find(".add_quiz_option_button").hide();
						$($(current_area).find(".li_mch_options_in_zone")[parseInt(current_options)-1]).find("." +  deleteQuizOptionButtonClass).show();

				}
				//add option
				$(current_area).find(".ul_mch_options_in_zone").append(quiz_option);
				//add key
				$(current_area).find(".multiplechoice_option_in_zone:last").keydown(function(event) {

					if(event.keyCode==13) {
						$('#' + event.target.id).unbind('keydown');
						event.preventDefault();
						event.stopPropagation();
				 		addOptionInQuiz('multiplechoice', current_area);
					}
				});

				//add index letter and unique_id
				$(current_area).find(".li_mch_options_in_zone:last-child > span").text(choicesLetters[current_options]);
				$(current_area).find(".li_mch_options_in_zone:last-child > ." +deleteQuizOptionButtonClass).attr("id", current_area.attr("id") + "_delete_option_button_"+  current_options + "_id");
				$(current_area).find(".li_mch_options_in_zone:last-child > ." +addQuizOptionButtonClass).attr("id", current_area.attr("id") + "_add_option_button_"+  current_options + "_id");
				//and call launchTextEditorInTextArea for zone
				launchTextEditorInTextArea(current_area, "multiplechoice", option_number);

				$(".li_mch_options_in_zone:last").focus();
				$("#wysiwyg_" + current_area.attr("id")  + "_" + current_options).focus();
				if(current_options>0) {
					//remove default text
					$(current_area).find(".li_mch_options_in_zone > div :last").text("");
				}
					//last option (change add for delete icon and unbind keydown)
				if((current_options+1)=== maxNumMultipleChoiceOptions) {
					$($(current_area).find(".li_mch_options_in_zone")[parseInt(current_options)]).find("." + addQuizOptionButtonClass).hide();
					$($(current_area).find(".li_mch_options_in_zone")[parseInt(current_options)]).find("." + deleteQuizOptionButtonClass).show();
					$('#' + "wysiwyg_"+ current_area.attr("id") + "_" + current_options).unbind('keydown');

				}

			break;

			default:
			break;
		}
	};

	var _removeOptionInQuiz = function (event) {
		if(event.target.attributes["class"].value=== deleteQuizOptionButtonClass){
			var current_area = V.Editor.getCurrentArea();
			//remove li
			var option_number = (event.target.id).substring(27,28);

			$("#" +current_area.attr("id")).find("#"+ event.target.attributes["id"].value).parent().remove();

			//reassign index letters for remaining options & reassign id's
			$(current_area).find(".li_mch_options_in_zone").each(function(index, option_element) {
				$(option_element).find("span").text(choicesLetters[index]);
				$(option_element).find("." +deleteQuizOptionButtonClass).attr("id", current_area.attr("id") + "_delete_option_button_"+  index + "_id");
				$(option_element).find("." +addQuizOptionButtonClass).attr("id", current_area.attr("id") + "_add_option_button_"+  index + "_id");
				//reasign ids for remaining wysiwyg div's
				$(option_element).attr("id","wysiwyg_" + current_area.attr("id") + "_"+  index );

				if(index>=option_number) {

					launchTextEditorInTextArea(current_area, "multiplechoice", option_number);
				}
			});
			//for the last: if delete icon hide it and show add icon
			if ($(current_area).find(".li_mch_options_in_zone").size()===(maxNumMultipleChoiceOptions-1)) {
				$($(current_area).find(".li_mch_options_in_zone")[maxNumMultipleChoiceOptions-2]).find("." +deleteQuizOptionButtonClass).hide();
				$($(current_area).find(".li_mch_options_in_zone")[maxNumMultipleChoiceOptions-2]).find("." + addQuizOptionButtonClass).show();
			}
 		}
 		else {
 			V.Debugging.log("other event  handler");
 		}

	};

//trying to do with div instead than zone (area)
	var launchTextEditorInTextArea = function(area, type_quiz, option_number){
		if (area) {
			current_area = area;
		} else {
			current_area = V.Editor.getCurrentArea();
		}
		if (option_number!=undefined) {
				var optionWysiwygId = "wysiwyg_" + current_area.attr("id") + "_" + option_number;
	    		$($(current_area).find("."+ type_quiz + "_option_in_zone")[option_number]).attr("id", optionWysiwygId);
	    		if($($(current_area).find(".li_mch_options_in_zone")[option_number]).find(".wysiwygInstance").val() ===undefined) {
	   				$("#"+optionWysiwygId).addClass("wysiwygInstance");
	    			V.Editor.Text.getNicEditor().addInstance(optionWysiwygId);
	    		}
	    		}
		//no option number --> first so we add wysiwygInstance to the first option
		else {
		var textArea = $(current_area).find(".value_"+ type_quiz + "_question_in_zone");
		var wysiwygId = "wysiwyg_" + current_area.attr("id"); //wysiwyg_zoneX
		textArea.attr("id", wysiwygId);
		$("#"+wysiwygId).addClass("wysiwygInstance");
		V.Editor.Text.getNicEditor().addInstance(wysiwygId);
		launchTextEditorInTextArea(current_area, "multiplechoice", 0);

		}

		$(".initTextDiv").click(function(event){
    		if(event.target.tagName=="FONT"){
    			var font = $(event.target);
    			var div =  $(event.target).parent();
    		} else if(event.target.tagName=="DIV"){
    			var div = $(event.target);
    			var font = $(event.target).find("font");
    		}else if(event.target.tagName=="SPAN"){
    			var div = $(event.target).parent();
    			var font = $(event.target);
    		}
	    	if($(font).text()==="Write options here"){
	    			//Remove text
	    		$(font).text("");
	    		$(div).removeClass("initTextDiv");
	    		//$(div).parent().text("  ");
	    		$(".multiplechoice_option_in_zone").trigger("click");
	    	}
	    	else if($(font).text()==="Write question here"){
	    		//Remove text
	    		$(font).text("");
	    		$(div).removeClass("initTextDiv");
	    		//$(div).parent().text("  ");
	    		$(div).parent().trigger("click");
	    	}
    	});
	};

	return {
		init			 				: init,
		onLoadTab						: onLoadTab,
		drawQuiz						: drawQuiz,
		addQuiz							: addQuiz,
		addOptionInQuiz					:addOptionInQuiz
	};

}) (VISH, jQuery);
<commit_msg>Quiz: function clickOnQuizArea implemented<commit_after>VISH.Editor.Quiz = (function(V,$,undefined){
	var maxNumMultipleChoiceOptions = 6; // maximum input options
	var choicesLetters = ['a)','b)','c)','d)','e)','f)'];

	var addQuizOptionButtonClass = "add_quiz_option_button";
	var deleteQuizOptionButtonClass = "delete_quiz_option_button";

	var init = function(){

		$(document).on('click','.add_quiz_option_button', addOptionInQuiz);
		$(document).on('click','.'+ deleteQuizOptionButtonClass, _removeOptionInQuiz);
		$(document).on('click', '.' + 'multipleChoiceQuizContainer', _clickOnQuizArea);
		/*var myInput = $(document).find(".initTextDiv > font");
		//$(myInput).watermark(VISH.Editor.I18n.getTrans("i.SearchContent"));
		$(myInput).keydown(function(event) {
				V.Debugging.log("enter key detected : " + event.keyCode);

			if(event.keyCode == 13) {

				addOptionInQuiz('multiplechoice');
				//VISH.Editor.Video.Youtube.requestYoutubeData($(myInput).val());
				$(myInput).blur();
			}
		}); */

	};
	////////////
	// Tabs and fancybox
	////////////
	var onLoadTab = function (tab) {
	};

	//Function called from quiz fancybox
	var addQuiz = function(quiz_type, area, num_options) {
		var current_area;
		var current_num_options;
		if(area) {
			current_area = $("#"+area);
		}
		else {
			current_area = VISH.Editor.getCurrentArea();
		}
		if(num_options){
			current_num_options = num_options;
		}
		else {
			current_num_options = 0;

		}

		switch (quiz_type) {
			case "open":
				// _addOpenQuiz();
				 break;
			case "multiplechoice":

				_addMultipleChoiceQuiz(current_area, current_num_options);
				//hide & show fancybox elements
				VISH.Utils.loadTab('tab_quizes');
				 break;
			case "truefalse":
				// _addTrueFalseQuiz();
			 	break;
			default:
				break;
		}
		$.fancybox.close();
	};

	var drawQuiz = function(quiz_type, zone_id, question, options, quiz_id){

		var zone;
		if(zone_id) {
			zone = "#"+ zone_id;
		} else {

			zone = ".current";
		}

		switch (quiz_type) {
			case "multiplechoice":

				if (question) {
					$(zone).find(".value_multiplechoice_question_in_zone").children().remove();
					$(zone).find(".value_multiplechoice_question_in_zone").append(question);
				}
				if (options) {
					var inputs = $(zone).find(".multiplechoice_option_in_zone"); //all inputs (less or equal than options received)
					for (var i = 0;  i <= options.length - 1; i++) {
						$(inputs[i]).children().remove();
						$(inputs[i]).append(options[i].container);
					}
				}
				if(quiz_id) {
					$(zone).find('input[name="quiz_id"]').val(quiz_id);
				}
				$(zone).find(".multiplechoice_option_in_zone").attr("rows", "1");
				break;
			case "open":

			break;

			case "truefalse":

			break;

			default:

			break;
		}
	};
	//possible targets
	var _clickOnQuizArea = function (event) {
	//	V.Debugging.log("click on Quiz Area detected on class element: " + event.target.classList[0]);
		switch (event.target.classList[0]) {

			case "multipleChoiceQuizContainer":
				V.Editor.setCurrentArea(event.target.parentElement.id);
			break;
			case "add_quiz_option_button":
				V.Editor.setCurrentArea(event.target.parentElement.parentElement.parentElement.parentElement.id);
			break;

			case "multiplechoice_option_in_zone":
				V.Editor.setCurrentArea(event.target.parentElement.parentElement.parentElement.parentElement.id);
			break;

			case "delete_quiz_option_button":
				V.Editor.setCurrentArea(event.target.parentElement.parentElement.parentElement.parentElement.id);
			break;

			case "li_mch_options_in_zone":
			V.Editor.setCurrentArea(event.target.parentElement.parentElement.parentElement.id);
			break;

			default:

			break;

		}

	};

	var _addMultipleChoiceQuiz = function(area, num_options) {
		var current_area;
		var current_num_options;
		var quiz = VISH.Dummies.getQuizDummy("multiplechoice", V.Slides.getSlides().length);
		if(area){
			current_area = area;
		}
		else {
			//if no param
			current_area = VISH.Editor.getCurrentArea();
		}
		if (num_options) {
		 	current_num_options = num_options;
		}
		else {
			current_num_options = 0;
		}

		current_area.find(".menuselect_hide").remove();
		current_area.attr('type','quiz');
		current_area.attr('quiztype','multiplechoice');
		//add the quizDummy (empty quiz) into the area (zone)
		current_area.append(quiz);
		V.Editor.addDeleteButton(current_area);

		for (var i=0; i <= num_options ; i++) {
			addOptionInQuiz('multiplechoice', current_area);
		}
		//launchTextEditorInTextArea(current_area, "multiplechoice");

	};

	var addOptionInQuiz = function (quiz_type, area) {
		//V.Debugging.log("current area value: " + V.Editor.getCurrentArea());
		var current_area;
		var current_quiz_type;
		if(area) {
			current_area = area;
		}
		else {
			current_area = V.Editor.getCurrentArea();
		}

		if(typeof quiz_type =="string"){ //when add complete multiplechoice quiz
			current_quiz_type = quiz_type;
		}
		else if(typeof quiz_type == "object") { //when event comes from click or enter (not implemented)
			current_quiz_type = $(current_area).attr("quiztype");
		}
		else {
			V.Debugging("another type ");

		}

		switch (current_quiz_type) {

			case "multiplechoice":

				var quiz_option = VISH.Dummies.getQuizOptionDummy(current_quiz_type);

				var current_options = $(current_area).find(".li_mch_options_in_zone").size();
				var option_number;
				//remove add icon and insert remove icon
				if(current_options>0) {
						option_number = current_options;
						$($(current_area).find(".li_mch_options_in_zone")[parseInt(current_options)-1]).find(".add_quiz_option_button").hide();
						$($(current_area).find(".li_mch_options_in_zone")[parseInt(current_options)-1]).find("." +  deleteQuizOptionButtonClass).show();

				}
				//add option
				$(current_area).find(".ul_mch_options_in_zone").append(quiz_option);
				//add key
				$(current_area).find(".multiplechoice_option_in_zone:last").keydown(function(event) {

					if(event.keyCode==13) {
						$('#' + event.target.id).unbind('keydown');
						event.preventDefault();
						event.stopPropagation();
				 		addOptionInQuiz('multiplechoice', current_area);
					}
				});

				//add index letter and unique_id
				$(current_area).find(".li_mch_options_in_zone:last-child > span").text(choicesLetters[current_options]);
				$(current_area).find(".li_mch_options_in_zone:last-child > ." +deleteQuizOptionButtonClass).attr("id", current_area.attr("id") + "_delete_option_button_"+  current_options + "_id");
				$(current_area).find(".li_mch_options_in_zone:last-child > ." +addQuizOptionButtonClass).attr("id", current_area.attr("id") + "_add_option_button_"+  current_options + "_id");
				//and call launchTextEditorInTextArea for zone
				launchTextEditorInTextArea(current_area, "multiplechoice", option_number);

				$(".li_mch_options_in_zone:last").focus();
				$("#wysiwyg_" + current_area.attr("id")  + "_" + current_options).focus();
				if(current_options>0) {
					//remove default text
					$(current_area).find(".li_mch_options_in_zone > div :last").text("");
				}
					//last option (change add for delete icon and unbind keydown)
				if((current_options+1)=== maxNumMultipleChoiceOptions) {
					$($(current_area).find(".li_mch_options_in_zone")[parseInt(current_options)]).find("." + addQuizOptionButtonClass).hide();
					$($(current_area).find(".li_mch_options_in_zone")[parseInt(current_options)]).find("." + deleteQuizOptionButtonClass).show();
					$('#' + "wysiwyg_"+ current_area.attr("id") + "_" + current_options).unbind('keydown');

				}

			break;

			default:
			break;
		}
	};

	var _removeOptionInQuiz = function (event) {
		if(event.target.attributes["class"].value=== deleteQuizOptionButtonClass){
			var current_area = V.Editor.getCurrentArea();
			//remove li
			var option_number = (event.target.id).substring(27,28);

			$("#" +current_area.attr("id")).find("#"+ event.target.attributes["id"].value).parent().remove();

			//reassign index letters for remaining options & reassign id's
			$(current_area).find(".li_mch_options_in_zone").each(function(index, option_element) {
				$(option_element).find("span").text(choicesLetters[index]);
				$(option_element).find("." +deleteQuizOptionButtonClass).attr("id", current_area.attr("id") + "_delete_option_button_"+  index + "_id");
				$(option_element).find("." +addQuizOptionButtonClass).attr("id", current_area.attr("id") + "_add_option_button_"+  index + "_id");
				//reasign ids for remaining wysiwyg div's
				$(option_element).attr("id","wysiwyg_" + current_area.attr("id") + "_"+  index );

				if(index>=option_number) {

					launchTextEditorInTextArea(current_area, "multiplechoice", option_number);
				}
			});
			//for the last: if delete icon hide it and show add icon
			if ($(current_area).find(".li_mch_options_in_zone").size()===(maxNumMultipleChoiceOptions-1)) {
				$($(current_area).find(".li_mch_options_in_zone")[maxNumMultipleChoiceOptions-2]).find("." +deleteQuizOptionButtonClass).hide();
				$($(current_area).find(".li_mch_options_in_zone")[maxNumMultipleChoiceOptions-2]).find("." + addQuizOptionButtonClass).show();
			}
 		}
 		else {
 			V.Debugging.log("other event  handler");
 		}

	};

//trying to do with div instead than zone (area)
	var launchTextEditorInTextArea = function(area, type_quiz, option_number){
		if (area) {
			current_area = area;
		} else {
			current_area = V.Editor.getCurrentArea();
		}
		if (option_number!=undefined) {
				var optionWysiwygId = "wysiwyg_" + current_area.attr("id") + "_" + option_number;
	    		$($(current_area).find("."+ type_quiz + "_option_in_zone")[option_number]).attr("id", optionWysiwygId);
	    		if($($(current_area).find(".li_mch_options_in_zone")[option_number]).find(".wysiwygInstance").val() ===undefined) {
	   				$("#"+optionWysiwygId).addClass("wysiwygInstance");
	    			V.Editor.Text.getNicEditor().addInstance(optionWysiwygId);
	    		}
	    		}
		//no option number --> first so we add wysiwygInstance to the first option
		else {
		var textArea = $(current_area).find(".value_"+ type_quiz + "_question_in_zone");
		var wysiwygId = "wysiwyg_" + current_area.attr("id"); //wysiwyg_zoneX
		textArea.attr("id", wysiwygId);
		$("#"+wysiwygId).addClass("wysiwygInstance");
		V.Editor.Text.getNicEditor().addInstance(wysiwygId);
		launchTextEditorInTextArea(current_area, "multiplechoice", 0);

		}

		$(".initTextDiv").click(function(event){
    		if(event.target.tagName=="FONT"){
    			var font = $(event.target);
    			var div =  $(event.target).parent();
    		} else if(event.target.tagName=="DIV"){
    			var div = $(event.target);
    			var font = $(event.target).find("font");
    		}else if(event.target.tagName=="SPAN"){
    			var div = $(event.target).parent();
    			var font = $(event.target);
    		}
	    	if($(font).text()==="Write options here"){
	    			//Remove text
	    		$(font).text("");
	    		$(div).removeClass("initTextDiv");
	    		//$(div).parent().text("  ");
	    		$(".multiplechoice_option_in_zone").trigger("click");
	    	}
	    	else if($(font).text()==="Write question here"){
	    		//Remove text
	    		$(font).text("");
	    		$(div).removeClass("initTextDiv");
	    		//$(div).parent().text("  ");
	    		$(div).parent().trigger("click");
	    	}
    	});
	};

	return {
		init			 				: init,
		onLoadTab						: onLoadTab,
		drawQuiz						: drawQuiz,
		addQuiz							: addQuiz,
		addOptionInQuiz					:addOptionInQuiz
	};

}) (VISH, jQuery);
<|endoftext|>


<commit_before>async function hologram_app(args) {
/*
parent_hash("8638cb9c331c8f30ff92eb870eef990ee9bd2d602e2e6462adf8bb5098ca4be1")
visibility("PUBLIC")
base_component_id("hologram")
created_timestamp(-1)
display_name("3d hologram app")
is_app(true)
description('Game app, this will return the game app')
uses_javascript_librararies(["advanced_bundle"])
logo_url("/driver_icons/hologram.png")

*/

    Vue.component('hologram',{
      template: `

({{x}},{{y}}) . ({{width}},{{height}}) ,  {{view_x}}, {{view_y}}, {{videoWidth}}

                  <video
                      style="position: absolute;width:50%;height;50%;"
                      v-on:play="onPlay"
                      id="inputVideo"
                      autoplay
                      muted>
                 </video>

                  <canvas  id="overlay"
                            style="position: absolute;;width:50%;height;50%;"
                  />

      `,
      data: function() {
          return {
              msg: "Test Hologram!",
              car: 1,
              x: -1,
              y: -1,
              width: -1,
              height: -1
              ,
              view_x: 0,
              view_y: 0,
              videoWidth: 0
          }
      }
      ,

      mounted: async function() {
        console.log(faceapi.nets)
        await faceapi.nets.ssdMobilenetv1.loadFromUri('/weights')
        await faceapi.loadMtcnnModel('/weights')
        await faceapi.loadFaceRecognitionModel('/weights')
        await faceapi.nets.faceLandmark68Net.loadFromUri('/weights')
        await faceapi.nets.tinyFaceDetector.loadFromUri('/weights' );

            // Grab elements, create settings, etc.
            var video = document.getElementById('inputVideo');

            // Get access to the camera!
            if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                // Not adding `{ audio: true }` since we only want video now
                navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
                    //video.src = window.URL.createObjectURL(stream);
                    video.srcObject = stream;
                    //video.play();
                });
            }

      },
      methods:
      {
        onPlay: async function ()
        {
            let mm = this

            try {
                const mtcnnForwardParams = {
                     minFaceSize: 200
                }

                const detections = await faceapi.detectSingleFace(
                                        document.getElementById('inputVideo')
                                        ,
                                        new faceapi.TinyFaceDetectorOptions({scoreThreshold: .1,inputSize: 128})
                                        ,
                                        mtcnnForwardParams
                                        )

                //const mtcnnResults = await faceapi.mtcnn(document.getElementById('inputVideo'), mtcnnForwardParams)

                //faceapi.draw.drawDetections(document.getElementById('overlay'), detections);
                if (detections) {

                    mm.x = Math.floor(detections._box._x)
                    mm.y = Math.floor(detections._box._y)
                    mm.width = Math.floor(detections._box._width)
                    mm.height = Math.floor(detections._box._height)

                    mm.videoWidth = mm.getInnerWidth(document.getElementById("inputVideo"))

                    mm.view_x =  1 + (parseFloat((1 / mm.videoWidth).toFixed(3)) * mm.x * -3)
                    //mm.view_y = -35 + ((1 / mm.height) * mm.y * 30)
                    //console.log(JSON.stringify(mm.view_y,null,2))

                }
                //console.log(mm.car++)

            } catch (err) {

            }

            setTimeout(() => mm.onPlay())
        }
        ,

        getInnerWidth: function(elem) {
            return elem.getBoundingClientRect().width
        }

      }

    })
}
<commit_msg>Revert "make the hologram a bit smoother"<commit_after>async function hologram_app(args) {
/*
visibility("PUBLIC")
base_component_id("hologram")
created_timestamp(-1)
display_name("3d hologram app")
is_app(true)
description('Game app, this will return the game app')
uses_javascript_librararies(["advanced_bundle"])
logo_url("/driver_icons/hologram.png")

*/

    Vue.component('hologram',{
      template: `

({{x}},{{y}}) . ({{width}},{{height}}) ,  {{view_x}}, {{view_y}}, {{videoWidth}}

                  <video
                      style="position: absolute;width:50%;height;50%;"
                      v-on:play="onPlay"
                      id="inputVideo"
                      autoplay
                      muted>
                 </video>

                  <canvas  id="overlay"
                            style="position: absolute;;width:50%;height;50%;"
                  />

      `,
      data: function() {
          return {
              msg: "Test Hologram!",
              car: 1,
              x: -1,
              y: -1,
              width: -1,
              height: -1
              ,
              view_x: 0,
              view_y: 0,
              videoWidth: 0
          }
      }
      ,

      mounted: async function() {
        console.log(faceapi.nets)
        await faceapi.nets.ssdMobilenetv1.loadFromUri('/weights')
        await faceapi.loadMtcnnModel('/weights')
        await faceapi.loadFaceRecognitionModel('/weights')
        await faceapi.nets.faceLandmark68Net.loadFromUri('/weights')
        await faceapi.nets.tinyFaceDetector.loadFromUri('/weights' );

            // Grab elements, create settings, etc.
            var video = document.getElementById('inputVideo');

            // Get access to the camera!
            if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                // Not adding `{ audio: true }` since we only want video now
                navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
                    //video.src = window.URL.createObjectURL(stream);
                    video.srcObject = stream;
                    //video.play();
                });
            }

      },
      methods:
      {
        onPlay: async function ()
        {
            let mm = this

            try {
                const mtcnnForwardParams = {
                     minFaceSize: 200
                }

                const detections = await faceapi.detectSingleFace(
                                        document.getElementById('inputVideo')
                                        ,
                                        new faceapi.TinyFaceDetectorOptions({scoreThreshold: .1,inputSize: 128})
                                        ,
                                        mtcnnForwardParams
                                        )

                //const mtcnnResults = await faceapi.mtcnn(document.getElementById('inputVideo'), mtcnnForwardParams)

                //faceapi.draw.drawDetections(document.getElementById('overlay'), detections);
                if (detections) {

                    mm.x = Math.floor(detections._box._x)
                    mm.y = Math.floor(detections._box._y)
                    mm.width = Math.floor(detections._box._width)
                    mm.height = Math.floor(detections._box._height)

                    mm.videoWidth = mm.getInnerWidth(document.getElementById("inputVideo"))

                    mm.view_x = -30 + ((1 / mm.videoWidth) * mm.x * 120)
                    //mm.view_y = -35 + ((1 / mm.height) * mm.y * 30)
                    //console.log(JSON.stringify(mm.view_y,null,2))

                }
                //console.log(mm.car++)

            } catch (err) {

            }

            setTimeout(() => mm.onPlay())
        }
        ,

        getInnerWidth: function(elem) {
            return elem.getBoundingClientRect().width
        }

      }

    })
}
<|endoftext|>


<commit_before>// tools.js
// ========
module.exports = {
    parse: function (options, client, argumentString, politician, guild) {

        var feedback = require('./feedback');

        var argumentList = getArguments(argumentString);

        for (a = 0; a < argumentList.length; a++) {

            var argument = argumentList[a].trim();

            console.log("Argument: " + argument);

            // help-message
            if (argument == "--help" || argument == "-h") {

                /*
                print help and exit
                 */
                options.message += feedback.helpText;
                options.play = false;

                /*
                custom channel
                 */
            } else if (argument.startsWith("--channel ") || argument.startsWith("-c ")) {

                var value = argument.substring(argument.indexOf(" ") + 1);
                var found = false;

                var channels = Array.from(guild.channels.values());

                // iterate through available channels to find the specified channel
                for (i = 0; i < channels.length; i++) {

                    var channel = channels[i];

                    if (channel.type == "voice" && channel.name.toLowerCase() == value) {
                        options.voiceChannel = channel;
                        options.play = true;
                        found = true;
                        break;
                    }

                }

                /*
                if no channel was found
                 */
                if (!found) {

                    // invalid channel, report and exit
                    options.message += "I could not find the voice-channel you specified. Select one of the following:\n"
                        + getVoiceChannelList(channels);
                    options.play = false;
                }

                /*
                custom sound file
                 */
            } else if (argument.startsWith("--file ") || argument.startsWith("-f ")) {

                var value = argument.substring(argument.indexOf(" ") + 1);

                // get list of matching files
                var candidates = getAudio(politician, value);

                if (candidates.length == 0) {

                    // no match found, cant continue. report and exit
                    options.message += "I could not find a filename matching the pattern you specified.";
                    options.play = false;
                } else if (candidates.length > 1) {

                    // multiple matches
                    options.message += "I found multiple audios matching your pattern. Please select one of the following:\n\n"
                        + candidates.join("\n");
                    options.play = false;

                } else {

                    // set the only match as desired audio
                    options.file = candidates[0];
                    options.play = true;
                }

                /*
                 list all sounds
                */
            } else if (argument == "--sounds") {

                //feedback.printSounds(client, textChannel);
                options.message += getSounds(politician);
                options.play = false;

                /*
                 print stats to channel
                */
            } else if (argument == "--stats" || argument == "--statistics") {
                //feedback.printStats(client, textChannel);
                options.message += getStats(client);
                options.play = false;
            } else if (argument == "--leave") {
                options.leave = true;
                options.play = false;
            } else {
                // unknown argument, print help and exit
                options.message += "You entered an unknown argument.";
                options.play = false;
            }
        }

        return JSON.stringify(options);
    }

};

function getArguments(argumentString) {

    argumentString = argumentString.split(" -").join(" --").split(" -");

    return argumentString;
}

function getVoiceChannelList(channels) {

    var voiceChannels = "";

    for (i = 0; i < channels.length; i++) {

        var channel = channels[i];

        if (channel.type == "voice") {
            voiceChannels += channel.name + "\n";
        }

    }

    return voiceChannels.trim();

}

function getStats(client) {
    const stats = require('../stats.json');

    // online for x milliseconds
    var milliseconds = client.uptime;

    var seconds = Math.floor((milliseconds / 1000) % 60);
    var minutes = Math.floor((milliseconds / (1000 * 60)) % 60);
    var hours = Math.floor(((milliseconds / (1000 * 60 * 60)) % 24));
    var days = Math.floor(((milliseconds / (1000 * 60 * 60 * 24)) % 30));

    var uptimeString = days + "d " + hours + "h " + minutes + "m " + seconds + "s";

    var seconds = Math.floor((milliseconds / 1000) % 60);
    var minutes = Math.floor((milliseconds / (1000 * 60)) % 60);
    var hours = Math.floor(((milliseconds / (1000 * 60 * 60)) % 24));
    var days = Math.floor(((milliseconds / (1000 * 60 * 60 * 24)) % 30));

    var date = new Date(Date.now() - client.uptime);

    var dateString = date.getFullYear() + "/" + date.getMonth() + 1 + "/" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

    return "Current stats:\n"
        + "```"
        + "Activated:                \t"
        + stats.played
        + "\n"
        + "  ∟-- Trump:              \t"
        + stats.trump
        + "\n"
        + "  ∟-- Clinton:            \t"
        + stats.clinton
        + "\n"
        + "  ∟-- Merkel:             \t"
        + stats.merkel
        + "\n"
        + "Uptime of current session:\t"
        + uptimeString
        + "\n"
        + "                          \t(" + dateString + ")"
        + "\n"
        + "Currently active guilds:  \t"
        + client.guilds.size
        + "```";
}

function getAudio(politician, pattern) {

    var fs = require('fs');

    var folder = "./audio/" + politician;
    var files = fs.readdirSync(folder);

    var candidates = [];
    // "^.*" + pattern + ".*";
    var regex = "^" + pattern.split("*").join(".*");

    // iterate through available files to find matching ones
    for (i = 0; i < files.length; i++) {

        var file = files[i];

        // get matches
        if (file.match(regex)) {

            console.log(file + " matches!");
            candidates.push(folder + "/" + file);
        }
    }

    return candidates;
}

function getSounds(politician) {

    var fs = require('fs');
    var folder = "./audio/" + politician;
    var files = fs.readdirSync(folder);

    return files.join("\n");
}
<commit_msg>Fixed every message having 'undefined' at the beginning<commit_after>// tools.js
// ========
module.exports = {
    parse: function (options, client, argumentString, politician, guild) {

        var feedback = require('./feedback');

        var argumentList = getArguments(argumentString);

        for (a = 0; a < argumentList.length; a++) {

            var argument = argumentList[a].trim();

            console.log("Argument: " + argument);

            // help-message
            if (argument == "--help" || argument == "-h") {

                /*
                print help and exit
                 */
                options.message = feedback.helpText;
                options.play = false;

                /*
                custom channel
                 */
            } else if (argument.startsWith("--channel ") || argument.startsWith("-c ")) {

                var value = argument.substring(argument.indexOf(" ") + 1);
                var found = false;

                var channels = Array.from(guild.channels.values());

                // iterate through available channels to find the specified channel
                for (i = 0; i < channels.length; i++) {

                    var channel = channels[i];

                    if (channel.type == "voice" && channel.name.toLowerCase() == value) {
                        options.voiceChannel = channel;
                        options.play = true;
                        found = true;
                        break;
                    }

                }

                /*
                if no channel was found
                 */
                if (!found) {

                    // invalid channel, report and exit
                    options.message = "I could not find the voice-channel you specified. Select one of the following:\n"
                        + getVoiceChannelList(channels);
                    options.play = false;
                }

                /*
                custom sound file
                 */
            } else if (argument.startsWith("--file ") || argument.startsWith("-f ")) {

                var value = argument.substring(argument.indexOf(" ") + 1);

                // get list of matching files
                var candidates = getAudio(politician, value);

                if (candidates.length == 0) {

                    // no match found, cant continue. report and exit
                    options.message = "I could not find a filename matching the pattern you specified.";
                    options.play = false;
                } else if (candidates.length > 1) {

                    // multiple matches
                    options.message = "I found multiple audios matching your pattern. Please select one of the following:\n\n"
                        + candidates.join("\n");
                    options.play = false;

                } else {

                    // set the only match as desired audio
                    options.file = candidates[0];
                    options.play = true;
                }

                /*
                 list all sounds
                */
            } else if (argument == "--sounds") {

                //feedback.printSounds(client, textChannel);
                options.message = getSounds(politician);
                options.play = false;

                /*
                 print stats to channel
                */
            } else if (argument == "--stats" || argument == "--statistics") {
                //feedback.printStats(client, textChannel);
                options.message = getStats(client);
                options.play = false;
            } else if (argument == "--leave") {
                options.leave = true;
                options.play = false;
            } else {
                // unknown argument, print help and exit
                options.message = "You entered an unknown argument.";
                options.play = false;
            }
        }

        return JSON.stringify(options);
    }

};

function getArguments(argumentString) {

    argumentString = argumentString.split(" -").join(" --").split(" -");

    return argumentString;
}

function getVoiceChannelList(channels) {

    var voiceChannels = "";

    for (i = 0; i < channels.length; i++) {

        var channel = channels[i];

        if (channel.type == "voice") {
            voiceChannels += channel.name + "\n";
        }

    }

    return voiceChannels.trim();

}

function getStats(client) {
    const stats = require('../stats.json');

    // online for x milliseconds
    var milliseconds = client.uptime;

    var seconds = Math.floor((milliseconds / 1000) % 60);
    var minutes = Math.floor((milliseconds / (1000 * 60)) % 60);
    var hours = Math.floor(((milliseconds / (1000 * 60 * 60)) % 24));
    var days = Math.floor(((milliseconds / (1000 * 60 * 60 * 24)) % 30));

    var uptimeString = days + "d " + hours + "h " + minutes + "m " + seconds + "s";

    var seconds = Math.floor((milliseconds / 1000) % 60);
    var minutes = Math.floor((milliseconds / (1000 * 60)) % 60);
    var hours = Math.floor(((milliseconds / (1000 * 60 * 60)) % 24));
    var days = Math.floor(((milliseconds / (1000 * 60 * 60 * 24)) % 30));

    var date = new Date(Date.now() - client.uptime);

    var dateString = date.getFullYear() + "/" + date.getMonth() + 1 + "/" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

    return "Current stats:\n"
        + "```"
        + "Activated:                \t"
        + stats.played
        + "\n"
        + "  ∟-- Trump:              \t"
        + stats.trump
        + "\n"
        + "  ∟-- Clinton:            \t"
        + stats.clinton
        + "\n"
        + "  ∟-- Merkel:             \t"
        + stats.merkel
        + "\n"
        + "Uptime of current session:\t"
        + uptimeString
        + "\n"
        + "                          \t(" + dateString + ")"
        + "\n"
        + "Currently active guilds:  \t"
        + client.guilds.size
        + "```";
}

function getAudio(politician, pattern) {

    var fs = require('fs');

    var folder = "./audio/" + politician;
    var files = fs.readdirSync(folder);

    var candidates = [];
    // "^.*" + pattern + ".*";
    var regex = "^" + pattern.split("*").join(".*");

    // iterate through available files to find matching ones
    for (i = 0; i < files.length; i++) {

        var file = files[i];

        // get matches
        if (file.match(regex)) {

            console.log(file + " matches!");
            candidates.push(folder + "/" + file);
        }
    }

    return candidates;
}

function getSounds(politician) {

    var fs = require('fs');
    var folder = "./audio/" + politician;
    var files = fs.readdirSync(folder);

    return files.join("\n");
}
<|endoftext|>


<commit_before>steal('can/observe',
	'can/util/json.js',
	'can/control',
function(){

		Observer = can.Control({
			defaults: {
				observeName : "observe",
				end : function(){
					return "                          "
				}
			}
		},{
			init : function(){
				// draw
				var data = this.options.observe.attr()
				this.options.obs = new can.Observe(data);
				this.on();
				this.render();
			},
			render : function(){
				var frag =  this.draw(0,undefined,this.options.obs)
				this.element.html(frag).find(".end").eq(-1).replaceWith(
					"})" +this.options.end.call(this)+"");
			},
			draw : function(indent, name, value){
				indent = indent || 0;
				var space = new Array(indent*4).join(" "),
					frag = document.createDocumentFragment();

				var self = this,
					namePart;
				if(!name && indent === 0){
					if(this.options.fullName){
						namePart =  this.options.fullName
					} else {
						namePart =  this.options.observeName+".attr("
					}

				} else if(typeof name === 'string'){
					namePart = ""+name+""+" : "
				} else {
					namePart = ""+""+""
				}

				if(namePart){
					var propName = $("").html(
						(!name && indent === 0 ? "" : "\n")+
						""+space+""+
						namePart
						);
					if(name !== undefined){
						propName.addClass('propName')
							.data("propName", name)
					}

				}

				frag.appendChild( propName[0] )

				if(value instanceof can.Observe) {
					var isList = value instanceof can.Observe.List,
						obs = $(""+
							(isList ? "[" : "{")
						+"")
						.addClass("observe")
						.data("observe",value)
						.data("indent",indent+1);

					var children = $()
					value.each(function(val, name){
						var section = self.draw(indent+1, /*isList ? undefined :*/ name, val);
						children.push(section);
					})
					// remove the last ","

					if(!children.length){
						obs.append(""+
							(isList ? "]" : "}") +",                    ")

					} else {
						// remove the last ","
						if(children.eq(-1)[0].lastChild.className === 'comma'){
							$(children.eq(-1)[0].lastChild).remove()
						} else if(children.eq(-1)[0].lastChild.className === 'observe'){
							var end = $(children.eq(-1)[0].lastChild).children('.end');
							end[0].firstChild.nodeValue
								= end[0].firstChild.nodeValue.replace(",","")
						}

						obs.append(children)
						obs.append("\n"+space+""+
							(isList ? "]" : "}") +",                        ")
					}
					frag.appendChild(obs[0])
				} else {
					var val = $("")
						.addClass("value")
						.data("propValue", value)
						.text( can.toJSON(value) )

					frag.appendChild(val[0])
					frag.appendChild($(',')[0])
				}
				return frag;
			},
			".name mouseenter" : function(el, ev){
				if(ev.relatedTarget && ev.relatedTarget.nodeName === "INPUT") {
					return;
				}
				this.newEditInput(el)
				ev.stopImmediatePropagation();
				this.editing = this.getObserveAndName(el);
			},
			"{editOverInput} destroyed" : function(){
				if(this.editing.inserting && !this.dontRemoveTemp){
					this.element.find('.temp').remove();
				}
				this.revert();
			},
			"{editOverInput} keypress" : function(el, ev){
				if(ev.keyCode === 9){
					ev.preventDefault();

					if(this.editing.inserting){
						this.editing.name = this.options.editOverInput.val();
						this.dontRemoveTemp = true;
						this.options.editOverInput.remove();

						this.editing.naming = $(" ");
						this.editing.inserting.parent().append(this.editing.naming)
						this.newEditInput(this.editing.naming)
						this.dontRemoveTemp = false;
					}

				} else if(ev.keyCode === 13){
					if(this.editing.inserting){

						if(this.editing.naming && this.options.editOverInput.val()) {
							try{
								var value = can.evalJSON(this.options.editOverInput.val())
								this.editing.observe.attr(this.editing.name, value);

								this.commit();
								this.options.editOverInput.remove();
							} catch(e){
								console.log("bad formatted",e)
							}
							return;
						}

					}
					this.commit();
					this.options.editOverInput.remove()
				}
			},
			"{editOverInput} keyup" : function(el, ev){
				//submitting

				if(!this.options.editOverInput.val() || ev.keyCode === 9){
					return;
				}

				if(this.editing.inserting){

					// do nothing ...
					if(this.editing.isList){

						try{
							var value = can.evalJSON(this.options.editOverInput.val())
							console.log(this.editing.index, value)
							this.editing.observe.attr(this.editing.index, value)
						} catch(e){
							console.log("bad formatted")
						}

					} else if(!this.editing.naming){
						this.editing.inserting.text(this.options.editOverInput.val());
					} else {
						// make naming right ...
						this.editing.naming.text(this.options.editOverInput.val())
						try{
							var value = can.evalJSON(this.options.editOverInput.val())
							this.editing.observe.attr(this.editing.name, value)
						} catch(e){
							console.log("bad formatted")
						}
					}

				} else if(this.editing.value){

					try{
						var value = can.evalJSON(this.options.editOverInput.val())
						this.editing.observe.attr(this.editing.name, value)
					} catch(e){
						console.log("bad formatted")
					}
				} else {
					var data = this.editing.observe.attr();
					var ordered = {};
					for(var name in data) {
						if(name === this.editing.name){
							ordered[this.options.editOverInput.val()] = data[name]
						} else {
							ordered[name] = data[name]
						}
					}
					this.editing.name = this.options.editOverInput.val();
					this.editing.observe.attr({}, true);
					this.editing.observe.attr(ordered);

				}

			},
			newEditInput : function(el){
				this.options.editOverInput && this.options.editOverInput.remove();
				this.options.editOverInput = $("<input type='text'>");
				new EditOver(this.options.editOverInput,{
					el : el
				})
				this.on();
			},
			".value mouseenter" : function(el, ev){
				if(ev.relatedTarget && ev.relatedTarget.nodeName === "INPUT") {
					return;
				}
				this.newEditInput(el)

				this.editing = this.getObserveAndName( el.prev().children().eq(0) );
				this.editing.value = true;

				ev.stopImmediatePropagation();
			},
			getObserveAndName : function(el){
				var propParent = el.closest('.propName')
					propName = propParent.data("propName")
				//get the observe
				var observe = propParent.closest(".observe").data("observe")
					|| this.options.obs;
				return {
					observe: observe,
					name: propName,
					oldName: propName
				}
			},
			".remove click": function(el, ev){
				// get the propName
				var propParent = el.closest('.propName')
					propName = propParent.data("propName")
				//get the observe
				var observe = propParent.parent(".observe").data("observe")
					|| this.options.obs;

				// remove the property
				observe.removeAttr(propName);

				this.options.editOverInput && this.options.editOverInput.remove();
				ev.stopImmediatePropagation();
			},
			".end click" : function(el, ev){
				//this.options.editOverInput && this.options.editOverInput.remove();

				var obsEl = el.closest(".observe")
					indent = obsEl.data("indent") || 0,
					space = new Array(indent*4).join(" "),
					observe = observe = obsEl.data("observe") || this.options.obs,
					isList = observe instanceof can.Observe.List;
				// get the element before end ... ad an input
				el.prev().after("\n"+space+" "
					+(isList ? "" : " : ")+"");

				var insert = el.prev('.temp').find('.insert');
				this.newEditInput(insert);

				this.editing = {
					observe : observe,
					inserting: insert,
					isList : isList
				};
				if(isList){
					this.editing.index = observe.length;
				}

				ev.stopImmediatePropagation();
			},
			"{obs} change" : function(){
				// redraw
				var self = this;
				clearTimeout(this.updateTimer);
				this.updateTimer = setTimeout(function(){
					self.render();
				},1)

			},
			"{observe} change" : function(){

				console.log("changed")
				var data = this.options.observe.attr();
				this.options.obs.attr(data, true)
			},
			commit : function(){
				var data = this.options.obs.attr();
				this.options.observe.attr(data, true)
			},
			revert : function(){
				var data = this.options.observe.attr();
				this.options.obs.attr(data, true)
			}
		})

		function setEnd(txt) {
	      if (txt.createTextRange) {
	       //IE
	       var fieldRange = txt.createTextRange();
	       fieldRange.moveStart('character', txt.value.length);
	       fieldRange.collapse();
	       fieldRange.select();
	       }
	      else {
	       //Firefox and Opera
	       txt.focus();
	       var length = txt.value.length;
	       txt.setSelectionRange(length, length);
	      }
	    }

		// draws an input element over some other element
		EditOver = can.Control({
			init : function(){
				this.element.addClass("edit-over")
				this.element.val(this.options.el.text())
				this.element.appendTo(document.body)

				var offset = this.options.el.offset();
				offset.top--;
				offset.left -= 3;

				this.element.width(this.options.el.width()+6)
				this.element.height(this.options.el.height()+2)
				var css = {
					fontSize : this.options.el.css("fontSize"),
					fontFamily : this.options.el.css("fontFamily"),
					position: "absolute"
				}
				this.element.css(css)

				this.element.offset(offset)
				if(this.options.focus){
					this.element[0].focus()
					setEnd(this.element[0])
				} else {
					this.element[0].select();
				}

				var self = this;
				setTimeout(function(){
					self.ready = true;
				},10)
				this.measure = $('').css(css).text(this.element.val())
				this.measure.appendTo(document.body)
				this.measure.css({left: "0px", top: "-1000px"})
			},
			"{window} click" : function(el, ev){
				if(this.ready && ev.target !== this.element[0]){
					this.element.remove();
				}
			},
			"keypress" : function(el, ev){
				if(ev.charCode){
					this.measure.text(this.element.val()+"W")
					this.element.width(this.measure.width()+6)
				}
			},
			"keyup" : function(el, ev){
				this.measure.text(this.element.val())
				this.element.width(this.measure.width()+6)
			},
			destroy : function(){
				this.measure.remove();
				can.Control.prototype.destroy.apply(this, arguments)
			}
		})

})
<commit_msg>Remove console.log<commit_after>steal('can/observe',
	'can/util/json.js',
	'can/control',
function(){

		Observer = can.Control({
			defaults: {
				observeName : "observe",
				end : function(){
					return "                          "
				}
			}
		},{
			init : function(){
				// draw
				var data = this.options.observe.attr()
				this.options.obs = new can.Observe(data);
				this.on();
				this.render();
			},
			render : function(){
				var frag =  this.draw(0,undefined,this.options.obs)
				this.element.html(frag).find(".end").eq(-1).replaceWith(
					"})" +this.options.end.call(this)+"");
			},
			draw : function(indent, name, value){
				indent = indent || 0;
				var space = new Array(indent*4).join(" "),
					frag = document.createDocumentFragment();

				var self = this,
					namePart;
				if(!name && indent === 0){
					if(this.options.fullName){
						namePart =  this.options.fullName
					} else {
						namePart =  this.options.observeName+".attr("
					}

				} else if(typeof name === 'string'){
					namePart = ""+name+""+" : "
				} else {
					namePart = ""+""+""
				}

				if(namePart){
					var propName = $("").html(
						(!name && indent === 0 ? "" : "\n")+
						""+space+""+
						namePart
						);
					if(name !== undefined){
						propName.addClass('propName')
							.data("propName", name)
					}

				}

				frag.appendChild( propName[0] )

				if(value instanceof can.Observe) {
					var isList = value instanceof can.Observe.List,
						obs = $(""+
							(isList ? "[" : "{")
						+"")
						.addClass("observe")
						.data("observe",value)
						.data("indent",indent+1);

					var children = $()
					value.each(function(val, name){
						var section = self.draw(indent+1, /*isList ? undefined :*/ name, val);
						children.push(section);
					})
					// remove the last ","

					if(!children.length){
						obs.append(""+
							(isList ? "]" : "}") +",                    ")

					} else {
						// remove the last ","
						if(children.eq(-1)[0].lastChild.className === 'comma'){
							$(children.eq(-1)[0].lastChild).remove()
						} else if(children.eq(-1)[0].lastChild.className === 'observe'){
							var end = $(children.eq(-1)[0].lastChild).children('.end');
							end[0].firstChild.nodeValue
								= end[0].firstChild.nodeValue.replace(",","")
						}

						obs.append(children)
						obs.append("\n"+space+""+
							(isList ? "]" : "}") +",                        ")
					}
					frag.appendChild(obs[0])
				} else {
					var val = $("")
						.addClass("value")
						.data("propValue", value)
						.text( can.toJSON(value) )

					frag.appendChild(val[0])
					frag.appendChild($(',')[0])
				}
				return frag;
			},
			".name mouseenter" : function(el, ev){
				if(ev.relatedTarget && ev.relatedTarget.nodeName === "INPUT") {
					return;
				}
				this.newEditInput(el)
				ev.stopImmediatePropagation();
				this.editing = this.getObserveAndName(el);
			},
			"{editOverInput} destroyed" : function(){
				if(this.editing.inserting && !this.dontRemoveTemp){
					this.element.find('.temp').remove();
				}
				this.revert();
			},
			"{editOverInput} keypress" : function(el, ev){
				if(ev.keyCode === 9){
					ev.preventDefault();

					if(this.editing.inserting){
						this.editing.name = this.options.editOverInput.val();
						this.dontRemoveTemp = true;
						this.options.editOverInput.remove();

						this.editing.naming = $(" ");
						this.editing.inserting.parent().append(this.editing.naming)
						this.newEditInput(this.editing.naming)
						this.dontRemoveTemp = false;
					}

				} else if(ev.keyCode === 13){
					if(this.editing.inserting){

						if(this.editing.naming && this.options.editOverInput.val()) {
							try{
								var value = can.evalJSON(this.options.editOverInput.val())
								this.editing.observe.attr(this.editing.name, value);

								this.commit();
								this.options.editOverInput.remove();
							} catch(e){
								console.log("bad formatted",e)
							}
							return;
						}

					}
					this.commit();
					this.options.editOverInput.remove()
				}
			},
			"{editOverInput} keyup" : function(el, ev){
				//submitting

				if(!this.options.editOverInput.val() || ev.keyCode === 9){
					return;
				}

				if(this.editing.inserting){

					// do nothing ...
					if(this.editing.isList){

						try{
							var value = can.evalJSON(this.options.editOverInput.val())
							console.log(this.editing.index, value)
							this.editing.observe.attr(this.editing.index, value)
						} catch(e){
							console.log("bad formatted")
						}

					} else if(!this.editing.naming){
						this.editing.inserting.text(this.options.editOverInput.val());
					} else {
						// make naming right ...
						this.editing.naming.text(this.options.editOverInput.val())
						try{
							var value = can.evalJSON(this.options.editOverInput.val())
							this.editing.observe.attr(this.editing.name, value)
						} catch(e){
							console.log("bad formatted")
						}
					}

				} else if(this.editing.value){

					try{
						var value = can.evalJSON(this.options.editOverInput.val())
						this.editing.observe.attr(this.editing.name, value)
					} catch(e){
						console.log("bad formatted")
					}
				} else {
					var data = this.editing.observe.attr();
					var ordered = {};
					for(var name in data) {
						if(name === this.editing.name){
							ordered[this.options.editOverInput.val()] = data[name]
						} else {
							ordered[name] = data[name]
						}
					}
					this.editing.name = this.options.editOverInput.val();
					this.editing.observe.attr({}, true);
					this.editing.observe.attr(ordered);

				}

			},
			newEditInput : function(el){
				this.options.editOverInput && this.options.editOverInput.remove();
				this.options.editOverInput = $("<input type='text'>");
				new EditOver(this.options.editOverInput,{
					el : el
				})
				this.on();
			},
			".value mouseenter" : function(el, ev){
				if(ev.relatedTarget && ev.relatedTarget.nodeName === "INPUT") {
					return;
				}
				this.newEditInput(el)

				this.editing = this.getObserveAndName( el.prev().children().eq(0) );
				this.editing.value = true;

				ev.stopImmediatePropagation();
			},
			getObserveAndName : function(el){
				var propParent = el.closest('.propName')
					propName = propParent.data("propName")
				//get the observe
				var observe = propParent.closest(".observe").data("observe")
					|| this.options.obs;
				return {
					observe: observe,
					name: propName,
					oldName: propName
				}
			},
			".remove click": function(el, ev){
				// get the propName
				var propParent = el.closest('.propName')
					propName = propParent.data("propName")
				//get the observe
				var observe = propParent.parent(".observe").data("observe")
					|| this.options.obs;

				// remove the property
				observe.removeAttr(propName);

				this.options.editOverInput && this.options.editOverInput.remove();
				ev.stopImmediatePropagation();
			},
			".end click" : function(el, ev){
				//this.options.editOverInput && this.options.editOverInput.remove();

				var obsEl = el.closest(".observe")
					indent = obsEl.data("indent") || 0,
					space = new Array(indent*4).join(" "),
					observe = observe = obsEl.data("observe") || this.options.obs,
					isList = observe instanceof can.Observe.List;
				// get the element before end ... ad an input
				el.prev().after("\n"+space+" "
					+(isList ? "" : " : ")+"");

				var insert = el.prev('.temp').find('.insert');
				this.newEditInput(insert);

				this.editing = {
					observe : observe,
					inserting: insert,
					isList : isList
				};
				if(isList){
					this.editing.index = observe.length;
				}

				ev.stopImmediatePropagation();
			},
			"{obs} change" : function(){
				// redraw
				var self = this;
				clearTimeout(this.updateTimer);
				this.updateTimer = setTimeout(function(){
					self.render();
				},1)

			},
			"{observe} change" : function(){

				var data = this.options.observe.attr();
				this.options.obs.attr(data, true)
			},
			commit : function(){
				var data = this.options.obs.attr();
				this.options.observe.attr(data, true)
			},
			revert : function(){
				var data = this.options.observe.attr();
				this.options.obs.attr(data, true)
			}
		})

		function setEnd(txt) {
	      if (txt.createTextRange) {
	       //IE
	       var fieldRange = txt.createTextRange();
	       fieldRange.moveStart('character', txt.value.length);
	       fieldRange.collapse();
	       fieldRange.select();
	       }
	      else {
	       //Firefox and Opera
	       txt.focus();
	       var length = txt.value.length;
	       txt.setSelectionRange(length, length);
	      }
	    }

		// draws an input element over some other element
		EditOver = can.Control({
			init : function(){
				this.element.addClass("edit-over")
				this.element.val(this.options.el.text())
				this.element.appendTo(document.body)

				var offset = this.options.el.offset();
				offset.top--;
				offset.left -= 3;

				this.element.width(this.options.el.width()+6)
				this.element.height(this.options.el.height()+2)
				var css = {
					fontSize : this.options.el.css("fontSize"),
					fontFamily : this.options.el.css("fontFamily"),
					position: "absolute"
				}
				this.element.css(css)

				this.element.offset(offset)
				if(this.options.focus){
					this.element[0].focus()
					setEnd(this.element[0])
				} else {
					this.element[0].select();
				}

				var self = this;
				setTimeout(function(){
					self.ready = true;
				},10)
				this.measure = $('').css(css).text(this.element.val())
				this.measure.appendTo(document.body)
				this.measure.css({left: "0px", top: "-1000px"})
			},
			"{window} click" : function(el, ev){
				if(this.ready && ev.target !== this.element[0]){
					this.element.remove();
				}
			},
			"keypress" : function(el, ev){
				if(ev.charCode){
					this.measure.text(this.element.val()+"W")
					this.element.width(this.measure.width()+6)
				}
			},
			"keyup" : function(el, ev){
				this.measure.text(this.element.val())
				this.element.width(this.measure.width()+6)
			},
			destroy : function(){
				this.measure.remove();
				can.Control.prototype.destroy.apply(this, arguments)
			}
		})

})
<|endoftext|>


<commit_before><commit_msg>melhorar vertical<commit_after><|endoftext|>


<commit_before>import _ from 'lodash';

import db from '../products.json';
import { chooseRandomKey } from '../helpers/generic';
import * as actions from '../actions';

import reducer, { initialState } from './index';

test('store is unchanged by empty action', () => {
  const state1 = reducer(initialState);
  const state2 = reducer(state1, {});
  expect(state1).toBe(state2);
});

test('add product creates new meta and product', () => {
  const state1 = reducer(initialState);
  const productId = chooseRandomKey(db);
  const stateAfterAdd = reducer(state1, actions.addProduct(productId));
  const { products, meta } = stateAfterAdd.cart;
  expect(_.size(products)).toBe(1);
  expect(_.size(meta)).toBe(1);
  expect(products).toHaveProperty(productId);
  expect(meta).toHaveProperty(productId);
});
<commit_msg>remove product test passing, begin update quantity test<commit_after>import _ from 'lodash';

import db from '../products.json';
import { chooseRandomKey } from '../helpers/generic';
import * as actions from '../actions';

import reducer, { initialState } from './index';

test('store is unchanged by empty action', () => {
  const state1 = reducer(initialState);
  const state2 = reducer(state1, {});
  expect(state1).toBe(state2);
});

function addRandomProductToState (state) {
  const productId = chooseRandomKey(db);
  const stateAfterAdd = reducer(state, actions.addProduct(productId));
  return {
    stateAfterAdd,
    productId
  };
}

test('add product creates new meta and product', () => {
  const state1 = reducer(initialState);
  const { stateAfterAdd, productId } = addRandomProductToState(state1);
  const { products, meta } = stateAfterAdd.cart;
  expect(_.size(products)).toBe(1);
  expect(_.size(meta)).toBe(1);
  expect(products).toHaveProperty(productId);
  expect(meta).toHaveProperty(productId);
});

test('removed products are not in state', () => {
  const state1 = reducer(initialState);
  const { stateAfterAdd, productId } = addRandomProductToState(state1);
  const stateAfterRemove = reducer(stateAfterAdd, actions.removeProduct(productId));
  const { products, meta } = stateAfterRemove.cart;
  expect(products).not.toHaveProperty(productId);
  expect(meta).not.toHaveProperty(productId);
});

test('can update quantity without changing product', () => {
  expect('todo').toBe('done');
});
<|endoftext|>


<commit_before>define(["jquery", "utils"], function ($, utils) {
    "use strict";

    var ApplicationListView = function(model) {
        // (Constructor) Represents the application list. In charge of
        // rendering in on the div with id #applist
        //
        // Parameters
        // model : ApplicationListModel
        //     The data model.
        this.model = model;
        var self = this;

        self.base_url = window.apidata.base_url;

        // Handlers for button clicking.
        // replace them to override default behavior (doing nothing).
        // Can return a value or a promise.
        this.stop_button_clicked = function(index) {};
        this.start_button_clicked = function(index) {};
        this.view_button_clicked = function(index) {};

        this._x_button_clicked = function () {
            // Triggered when the button X (left side) is clicked
            var button = this;
            var index = $(button).data("index");
            $(button).find(".fa-spinner").show();

            var app_info = self.model.app_data[index];

            var hide_spinner = function () {
                $(button).find(".fa-spinner").hide();
            };

            if (app_info.container !== null) {
                self.view_button_clicked(index).done(hide_spinner);
            } else {
                self.start_button_clicked(index).done(hide_spinner);
            }
        };

        this._y_button_clicked = function () {
            var button = this;
            var index = $(button).data("index");
            $(button).find(".fa-spinner").show();
            self.stop_button_clicked(index).done(function () {
                    $(button).find(".fa-spinner").hide();
            });
        };

        $("#applist").html(
            '
' +
            '' +
            '
');
    };

    ApplicationListView.prototype.render = function () {
        // Renders the full application list and adds it to the DOM.
        var num_entries = this.model.app_data.length;
        var row;
        var applist = $("#applist");
        applist.empty();
        if (num_entries === 0) {
            row = $('

No applications found

');
            applist.append(row);
        } else {
            for (var i = 0; i < num_entries; i++) {
                row = this.render_applist_entry(i);
                applist.append(row);
            }
        }
    };

    ApplicationListView.prototype.render_applist_entry = function (index) {
        // Returns a HTML snippet for a single application entry
        // index:
        //     a progressive index for the entry.

        var app_data = this.model.app_data[index];
        var configurables = this.model.configurables[index];

        var html_template = '' +
            '
' +
            '  ' +
            '
' +
            '
{image_name}
' +
            '
{policy_html}
' +
            '

' +
            '
' +
            '
' +
            '    <button id="bnx_{index}" data-index="{index}" class="{button_x_class} bnx btn">  {button_x_text}</button>' +
            '
' +
            '
' +
            '    <button id="bny_{index}" data-index="{index}" class="stop-button btn-danger bny btn" style="{button_y_style}">  Stop</button>' +
            '
' +
            '
';

        var icon = app_data.image.icon_128 ?
            "data:image/png;base64,"+app_data.image.icon_128 :
            utils.url_path_join(this.base_url,
                "static", "images", "generic_appicon_128.png");

        var image_name = app_data.image.ui_name ? app_data.image.ui_name : app_data.image.name;
        var policy_html = this._policy_html(app_data.image.policy);
        var cls, text, stop_style;
        if (app_data.container !== null) {
            cls = "view-button btn-success";
            text = " View";
            stop_style = "";
        } else {
            cls = "start-button btn-primary";
            text = " Start";
            stop_style = 'visibility: hidden;';
        }

        var row = $(html_template
            .replace(/\{icon\}/g, icon)
            .replace(/\{image_name\}/g, image_name)
            .replace(/\{policy\}/g, policy_html)
            .replace(/\{index\}/g, index)
            .replace(/\{button_x_class\}/g, cls)
            .replace(/\{button_x_text\}/g, text)
            .replace(/\{button_y_style\}/g, stop_style)
            .replace(/\{policy_html\}/g, policy_html));

        row.find(".bnx").click(this._x_button_clicked);
        row.find(".bny").click(this._y_button_clicked);

        if (app_data.container === null) {
            var ul = $("
");
            Object.getOwnPropertyNames(configurables).forEach(
                function(val, idx, array) {
                    var widget = configurables[val].view();
                    ul.append($("
").append(widget));
                }
            );
            row.find(".configurables").append(ul);
        }

        return row;
    };

    ApplicationListView.prototype.update_entry = function (index) {
        // Re-renders the entry for a given index, replacing the
        // current entry.
        var row = this.render_applist_entry(index);
        $("#applist")
            .find(".row[data-index='"+index+"']")
            .replaceWith(row);
    };

    ApplicationListView.prototype._policy_html = function(policy) {
        var mount_html = '';

        if (policy.allow_home) {
            mount_html += "
Workspace
";
        }
        if (policy.volume_source && policy.volume_target && policy.volume_mode) {
            mount_html += "
"+ policy.volume_source +
                " → " +
                policy.volume_target +
                " " +
                "(" + policy.volume_mode + ")
";
        }
        if (mount_html !== '') {
            mount_html = "
" + mount_html + "
";
        }
        return mount_html;
    };

    return {
        ApplicationListView : ApplicationListView
    };

});
<commit_msg>Replace icon with spinner.<commit_after>define(["jquery", "utils"], function ($, utils) {
    "use strict";

    var ApplicationListView = function(model) {
        // (Constructor) Represents the application list. In charge of
        // rendering in on the div with id #applist
        //
        // Parameters
        // model : ApplicationListModel
        //     The data model.
        this.model = model;
        var self = this;

        self.base_url = window.apidata.base_url;

        // Handlers for button clicking.
        // replace them to override default behavior (doing nothing).
        // Can return a value or a promise.
        this.stop_button_clicked = function(index) {};
        this.start_button_clicked = function(index) {};
        this.view_button_clicked = function(index) {};

        this._x_button_clicked = function () {
            // Triggered when the button X (left side) is clicked
            var button = this;
            var index = $(button).data("index");

            var icon_elem = $(button).find(".x-icon");
            var icons = ['fa-start', 'fa-eye'];
            var icon_type;

            for (var i = 0; i < icons.length; ++i) {
                if (icon_elem.hasClass(icons[i])) {
                    icon_type = icons[i];
                }
            }

            icon_elem.removeClass(icon_type).addClass("fa-spinner fa-spin");

            var restore_icon = function () {
                icon_elem.removeClass("fa-spinner fa-spin").addClass(icon_type);
            };

            var app_info = self.model.app_data[index];

            if (app_info.container !== null) {
                self.view_button_clicked(index).done(restore_icon);
            } else {
                self.start_button_clicked(index).done(restore_icon);
            }
        };

        this._y_button_clicked = function () {
            var button = this;
            var index = $(button).data("index");
            $(button).find(".y-icon").removeClass("fa-stop").addClass("fa-spinner fa-spin");

            self.stop_button_clicked(index).done(function () {
                $(button).find(".y-icon").removeClass("fa-spinner fa-spin").addClass("fa-stop");
            });
        };

        $("#applist").html(
            '
' +
            '' +
            '
');
    };

    ApplicationListView.prototype.render = function () {
        // Renders the full application list and adds it to the DOM.
        var num_entries = this.model.app_data.length;
        var row;
        var applist = $("#applist");
        applist.empty();
        if (num_entries === 0) {
            row = $('

No applications found

');
            applist.append(row);
        } else {
            for (var i = 0; i < num_entries; i++) {
                row = this.render_applist_entry(i);
                applist.append(row);
            }
        }
    };

    ApplicationListView.prototype.render_applist_entry = function (index) {
        // Returns a HTML snippet for a single application entry
        // index:
        //     a progressive index for the entry.

        var app_data = this.model.app_data[index];
        var configurables = this.model.configurables[index];

        var html_template = '' +
            '
' +
            '  ' +
            '
' +
            '
{image_name}
' +
            '
{policy_html}
' +
            '

' +
            '
' +
            '
' +
            '    <button id="bnx_{index}" data-index="{index}" class="{button_x_class} bnx btn">  {button_x_text}</button>' +
            '
' +
            '
' +
            '    <button id="bny_{index}" data-index="{index}" class="stop-button btn-danger bny btn" style="{button_y_style}"> Stop</button>' +
            '
' +
            '
';

        var icon = app_data.image.icon_128 ?
            "data:image/png;base64,"+app_data.image.icon_128 :
            utils.url_path_join(this.base_url,
                "static", "images", "generic_appicon_128.png");

        var image_name = app_data.image.ui_name ? app_data.image.ui_name : app_data.image.name;
        var policy_html = this._policy_html(app_data.image.policy);
        var cls, text, stop_style, x_icon;
        if (app_data.container !== null) {
            cls = "view-button btn-success";
            text = " View";
            x_icon = "fa-eye";
            stop_style = "";
        } else {
            cls = "start-button btn-primary";
            x_icon = "fa-play";
            text = " Start";
            stop_style = 'visibility: hidden;';
        }

        var row = $(html_template
            .replace(/\{icon\}/g, icon)
            .replace(/\{image_name\}/g, image_name)
            .replace(/\{policy\}/g, policy_html)
            .replace(/\{index\}/g, index)
            .replace(/\{button_x_class\}/g, cls)
            .replace(/\{button_x_icon\}/g, x_icon)
            .replace(/\{button_x_text\}/g, text)
            .replace(/\{button_y_style\}/g, stop_style)
            .replace(/\{policy_html\}/g, policy_html));

        row.find(".bnx").click(this._x_button_clicked);
        row.find(".bny").click(this._y_button_clicked);

        if (app_data.container === null) {
            var ul = $("
");
            Object.getOwnPropertyNames(configurables).forEach(
                function(val, idx, array) {
                    var widget = configurables[val].view();
                    ul.append($("
").append(widget));
                }
            );
            row.find(".configurables").append(ul);
        }

        return row;
    };

    ApplicationListView.prototype.update_entry = function (index) {
        // Re-renders the entry for a given index, replacing the
        // current entry.
        var row = this.render_applist_entry(index);
        $("#applist")
            .find(".row[data-index='"+index+"']")
            .replaceWith(row);
    };

    ApplicationListView.prototype._policy_html = function(policy) {
        var mount_html = '';

        if (policy.allow_home) {
            mount_html += "
Workspace
";
        }
        if (policy.volume_source && policy.volume_target && policy.volume_mode) {
            mount_html += "
"+ policy.volume_source +
                " → " +
                policy.volume_target +
                " " +
                "(" + policy.volume_mode + ")
";
        }
        if (mount_html !== '') {
            mount_html = "
" + mount_html + "
";
        }
        return mount_html;
    };

    return {
        ApplicationListView : ApplicationListView
    };

});
<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');
var swaggerConverter = require('swagger-converter');
var host = '172.17.42.1';
host = 'localhost';
var port = 4001;
var apiVersion = "0.3.5";

function getJson(page, callback) {
    return http.get({
        host: host,
        port: port,
        path: page,
    }, function(response) {
        // Continuously update stream with data
        var body = '';
        response.on('data', function(d) {
            body += d;
        });
        response.on('end', function() {
            // Data reception is done, do whatever with it!
            var parsed = JSON.parse(body);
            callback( parsed );
        });
    });
};

function mkdirSync (path) {
  try {
    fs.mkdirSync(path);
  } catch(e) {
    if ( e.code != 'EEXIST' ) throw e;
  }
}

// getApiEndpoints THEN createApiData THEN downloadEndPointAPIS THEN localTransformFixes THEN convertToVersion2

var fetchData = function() {
  return new Promise(function(resolve, reject) {
    getJson('/api-docs', function(jsonDoc) {
      resolve({"root": jsonDoc, "apis": jsonDoc.apis});
    });
  });
};

var parseApiEndpoints = function(data) {
  return new Promise(function(resolve, reject) {
    var resourceUrl = "";
    var newArray = [];
    var apis = data.apis;
    for (i in apis) {
      var baseName = apis[i].path.split(/^\/v\d+\//)[1];
      resourceUrl = "http://" + host + ":" + port + "/api-docs" + apis[i].path;
      newArray.push({'baseName': baseName, 'resourceUrl': resourceUrl});
    }
    data.apis = newArray;
    resolve(data);
  });
};

var readApiEndpoints = function(data) {
  var apis = data.apis;
  var promiseChain = [];
  for (var i in apis) {
    var tempPromise = new Promise(function(resolve, reject) {
      var baseName = apis[i].baseName;
      var resourceUrl = apis[i].resourceUrl;
      getJson('/api-docs/v0/' + baseName, function(jsonDoc) {
        resolve({"baseName": baseName, "api": jsonDoc});
      });
    });
    promiseChain.push(tempPromise);
  }
  return Promise.all(promiseChain)
    .then(function(chainData) {
      return new Promise(function(resolve, reject) {
        data.apis = chainData;
        resolve(data);
      });
    });
};

var flattenApis = function(data) {
  return new Promise(function(resolve, reject) {
    var flatArray = [];
    for(var i in data['apis']) {
      flatArray.push(data['apis'][i]['api']);
    }
    data['apis'] = flatArray;
    resolve(data);
  });
};

var writeVersion1 = function(data) {
  return new Promise(function(resolve, reject) {
    for (var i in data['apis']) {
      var base = data['apis'][i]['baseName'];
      var contents = data['apis'][i]['api'];
      fs.writeFileSync('./output/swaggerv1.2/' + base + '.json', JSON.stringify(contents));
    }
    resolve(data);
  });
};

var writeVersion2 = function(data) {
  return new Promise(function(resolve, reject) {
      fs.writeFileSync('./output/swaggerv2/api.json', JSON.stringify(data));
      resolve(data);
  });
};

var logData = function(data) {
  return new Promise(function(resolve, reject) {
    console.log(data);
    resolve(data);
  });
};

var transformJson = function(jsonDoc) {
  /* //for outer document
  data.info.title = "CoralAPIServer";
  data.info.version = apiVersion;
  */
  return new Promise(function(resolve, reject) {
    var dataArray = jsonDoc.apis;
    for (var h in dataArray) {
      var data = dataArray[h];
      data.basePath = "http://coralapiserver.local:4001";
      for (var i in data.apis) {
        data.apis[i].path = data.apis[i].path.substring(3) ;
        for (var j in data.apis[i].operations) {
          var requiresAuth = false;
          for (var k in data.apis[i].operations[j].parameters) {
            if (data.apis[i].operations[j].parameters[k].items ) {
              delete data.apis[i].operations[j].parameters[k].items;
              data.apis[i].operations[j].parameters[k].type = 'string';
            }
            if (data.apis[i].operations[j].parameters[k].type == 'User') {
              data.apis[i].operations[j].parameters.splice(k, 1);
              requiresAuth = true;
            }
          }
          if (requiresAuth) {
            data.apis[i].operations[j].security = { "basicAuth": [] };
          }
        }
      }
      dataArray[h] = data;
    }
    jsonDoc.apis = dataArray;
    resolve(jsonDoc);
  });
};

var convertToVersion2 = function(data) {
  return new Promise(function(resolve, reject) {
    var resourceListing = data.root;
    var apiDeclarations = data.apis
    var swagger2Document = swaggerConverter(resourceListing, apiDeclarations);
    resolve(swagger2Document);
  });
};

var updateVersion2 = function(data) {
  return new Promise(function(resolve, reject) {
    data.info.version = apiVersion;
    data.info.title = "Coral API Server";
    resolve(data);
  });
};

mkdirSync('./output');
mkdirSync('./output/swaggerv1.2');
mkdirSync('./output/swaggerv2');

fetchData().then(function(data) {
  return parseApiEndpoints(data);
}).then(function(data) {
  console.log("----STEP 1------");
  return readApiEndpoints(data);
}).then(function(data) {
  console.log("----STEP 2.5------");
  console.log(data);
  return writeVersion1(data);
}).then(function(data) {
  console.log("----STEP 2------");
  console.log(data);
  return flattenApis(data);
}).then(function(data) {
  console.log("----STEP 3------");
  console.log(data);
  return transformJson(data);
}).then(function(data) {
  console.log("----STEP 4------");
  console.log(data);
  return convertToVersion2(data);
}).then(function(data) {
  console.log("----STEP 4.2------");
  console.log(data);
  return updateVersion2(data);
}).then(function(data) {
  console.log("----STEP 4.5------");
  console.log(data);
  return writeVersion2(data);
}).then(function(data) {
  console.log("----STEP 5------");
  console.log(data);
  //return logData(data);
});
<commit_msg>cleanup<commit_after>var http = require('http');
var fs = require('fs');
var swaggerConverter = require('swagger-converter');
var host = '172.17.42.1';
host = 'localhost';
var port = 4001;
var apiVersion = "0.3.5";

function getJson(page, callback) {
    return http.get({
        host: host,
        port: port,
        path: page,
    }, function(response) {
        // Continuously update stream with data
        var body = '';
        response.on('data', function(d) {
            body += d;
        });
        response.on('end', function() {
            // Data reception is done, do whatever with it!
            var parsed = JSON.parse(body);
            callback( parsed );
        });
    });
};

function mkdirSync (path) {
  try {
    fs.mkdirSync(path);
  } catch(e) {
    if ( e.code != 'EEXIST' ) throw e;
  }
}

// getApiEndpoints THEN createApiData THEN downloadEndPointAPIS THEN localTransformFixes THEN convertToVersion2

var fetchData = function() {
  return new Promise(function(resolve, reject) {
    getJson('/api-docs', function(jsonDoc) {
      resolve({"root": jsonDoc, "apis": jsonDoc.apis});
    });
  });
};

var parseApiEndpoints = function(data) {
  return new Promise(function(resolve, reject) {
    var resourceUrl = "";
    var newArray = [];
    var apis = data.apis;
    for (i in apis) {
      var baseName = apis[i].path.split(/^\/v\d+\//)[1];
      resourceUrl = "http://" + host + ":" + port + "/api-docs" + apis[i].path;
      newArray.push({'baseName': baseName, 'resourceUrl': resourceUrl});
    }
    data.apis = newArray;
    resolve(data);
  });
};

var readApiEndpoints = function(data) {
  var apis = data.apis;
  var promiseChain = [];
  for (var i in apis) {
    var tempPromise = new Promise(function(resolve, reject) {
      var baseName = apis[i].baseName;
      var resourceUrl = apis[i].resourceUrl;
      getJson('/api-docs/v0/' + baseName, function(jsonDoc) {
        resolve({"baseName": baseName, "api": jsonDoc});
      });
    });
    promiseChain.push(tempPromise);
  }
  return Promise.all(promiseChain)
    .then(function(chainData) {
      return new Promise(function(resolve, reject) {
        data.apis = chainData;
        resolve(data);
      });
    });
};

var flattenApis = function(data) {
  return new Promise(function(resolve, reject) {
    var flatArray = [];
    for(var i in data['apis']) {
      flatArray.push(data['apis'][i]['api']);
    }
    data['apis'] = flatArray;
    resolve(data);
  });
};

var writeVersion1 = function(data) {
  return new Promise(function(resolve, reject) {
    for (var i in data['apis']) {
      var base = data['apis'][i]['baseName'];
      var contents = data['apis'][i]['api'];
      fs.writeFileSync('./output/swaggerv1.2/' + base + '.json', JSON.stringify(contents,null,'  '));
    }
    resolve(data);
  });
};

var writeVersion2 = function(data) {
  return new Promise(function(resolve, reject) {
      fs.writeFileSync('./output/swaggerv2/api.json', JSON.stringify(data,null,'  '));
      resolve(data);
  });
};

var logData = function(data) {
  return new Promise(function(resolve, reject) {
    console.log(data);
    resolve(data);
  });
};

var transformJson = function(jsonDoc) {
  /* //for outer document
  data.info.title = "CoralAPIServer";
  data.info.version = apiVersion;
  */
  return new Promise(function(resolve, reject) {
    var dataArray = jsonDoc.apis;
    for (var h in dataArray) {
      var data = dataArray[h];
      data.basePath = "http://coralapiserver.local:4001/v0";
      for (var i in data.apis) {
        data.apis[i].path = data.apis[i].path.substring(3) ;
        for (var j in data.apis[i].operations) {
          var requiresAuth = false;
          for (var k in data.apis[i].operations[j].parameters) {
            if (data.apis[i].operations[j].parameters[k].items ) {
              delete data.apis[i].operations[j].parameters[k].items;
              data.apis[i].operations[j].parameters[k].type = 'string';
            }
            if (data.apis[i].operations[j].parameters[k].type == 'User') {
              data.apis[i].operations[j].parameters.splice(k, 1);
              requiresAuth = true;
            }
          }
          if (requiresAuth) {
            data.apis[i].operations[j].security = { "basicAuth": [] };
          }
        }
      }
      dataArray[h] = data;
    }
    jsonDoc.apis = dataArray;
    resolve(jsonDoc);
  });
};

var convertToVersion2 = function(data) {
  return new Promise(function(resolve, reject) {
    var resourceListing = data.root;
    var apiDeclarations = data.apis
    var swagger2Document = swaggerConverter(resourceListing, apiDeclarations);
    resolve(swagger2Document);
  });
};

var updateVersion2 = function(data) {
  return new Promise(function(resolve, reject) {
    data.info.version = apiVersion;
    data.info.title = "Coral API Server";
    resolve(data);
  });
};

mkdirSync('./output');
mkdirSync('./output/swaggerv1.2');
mkdirSync('./output/swaggerv2');

fetchData().then(function(data) {
  return parseApiEndpoints(data);
}).then(function(data) {
  console.log("----STEP 1------");
  return readApiEndpoints(data);
}).then(function(data) {
  console.log("----STEP 2.5------");
  return writeVersion1(data);
}).then(function(data) {
  console.log("----STEP 2------");
  return flattenApis(data);
}).then(function(data) {
  console.log("----STEP 3------");
  return transformJson(data);
}).then(function(data) {
  console.log("----STEP 4------");
  return convertToVersion2(data);
}).then(function(data) {
  console.log("----STEP 4.2------");
  return updateVersion2(data);
}).then(function(data) {
  console.log("----STEP 4.5------");
  return writeVersion2(data);
}).then(function(data) {
  console.log("----STEP 5------");
  console.log("FINISHED");
  console.log('./output/swaggerv2/api.json');

});
<|endoftext|>