<commit_before>/*
    subtask:
        Logic for quickAlgo tasks, implements the Bebras task API.
*/

var initBlocklySubTask = function(subTask, language) {
   // Blockly tasks need to always have the level-specific behavior from
   // beaver-task-2.0
   subTask.assumeLevels = true;

   if (subTask.data["medium"] == undefined) {
      subTask.load = function(views, callback) {
         subTask.loadLevel("easy");
         callback();
      };
   }

   if (language == undefined) {
      language = "fr";
   }

   subTask.loadLevel = function(curLevel) {
      subTask.levelGridInfos = extractLevelSpecific(subTask.gridInfos, curLevel);

      subTask.blocklyHelper = getBlocklyHelper(subTask.levelGridInfos.maxInstructions);
      subTask.answer = null;
      subTask.state = {};
      subTask.iTestCase = 0;
      if(!window.taskResultsCache) {
         window.taskResultsCache = {};
      }
      if(!window.taskResultsCache[curLevel]) {
         window.taskResultsCache[curLevel] = {};
      }

      this.level = curLevel;

      // TODO: fix bebras platform to make this unnecessary
      try {
         $('#question-iframe', window.parent.document).css('width', '100%');
      } catch(e) {
      }
      $('body').css("width", "100%").addClass('blockly');
      window.focus();

      this.iTestCase = 0;
      this.nbTestCases = subTask.data[curLevel].length;

      this.context = quickAlgoLibraries.getContext(this.display, subTask.levelGridInfos, curLevel);
      this.context.raphaelFactory = this.raphaelFactory;
      this.context.delayFactory = this.delayFactory;
      this.context.blocklyHelper = this.blocklyHelper;

      if (this.display) {
        window.quickAlgoInterface.loadInterface(this.context);
        window.quickAlgoInterface.setOptions({
           hideSaveOrLoad: subTask.levelGridInfos.hideSaveOrLoad,
           hasExample: subTask.levelGridInfos.example && subTask.levelGridInfos.example[subTask.blocklyHelper.language],
           conceptViewer: subTask.levelGridInfos.conceptViewer,
           conceptViewerLang: this.blocklyHelper.language
           });
      }

      this.blocklyHelper.loadContext(this.context);

      //this.answer = task.getDefaultAnswerObject();
      displayHelper.hideValidateButton = true;
      displayHelper.timeoutMinutes = 30;

      var curIncludeBlocks = extractLevelSpecific(this.context.infos.includeBlocks, curLevel);

      // Load concepts into conceptViewer; must be done before loading
      // Blockly/Scratch, as scratch-mode will modify includeBlocks
      if(this.display && subTask.levelGridInfos.conceptViewer) {
         // TODO :: testConcepts is temporary-ish
         if(this.context.conceptList) {
            var allConcepts = testConcepts.concat(this.context.conceptList);
         } else {
            var allConcepts = testConcepts;
         }

         var concepts = window.getConceptsFromBlocks(curIncludeBlocks, allConcepts, this.context);
         if(subTask.levelGridInfos.conceptViewer.length) {
            concepts = concepts.concat(subTask.levelGridInfos.conceptViewer);
         }
         concepts = window.conceptsFill(concepts, allConcepts);
         window.conceptViewer.loadConcepts(concepts);
      }

      this.blocklyHelper.setIncludeBlocks(curIncludeBlocks);

      var blocklyOptions = {
         readOnly: !!subTask.taskParams.readOnly,
         defaultCode: subTask.defaultCode
      };

      this.blocklyHelper.load(stringsLanguage, this.display, this.data[curLevel].length, blocklyOptions);

      if(this.display) {
         window.quickAlgoInterface.initTestSelector(this.nbTestCases);
      }

      subTask.changeTest(0);
   };

   subTask.updateScale = function() {
      this.context.updateScale();
      this.blocklyHelper.updateSize();
   };

   var resetScores = function() {
   };

   var updateScores = function() {
   };

   function changeScore(robot, deltaScore) {
      scores[robot] += deltaScore;
      updateScores();
   };

   subTask.unloadLevel = function(callback) {
      window.quickAlgoInterface.resetTestScores();
      this.context.unload();
      this.blocklyHelper.unloadLevel();
      callback();
   };

   subTask.unload = function(callback) {
      var that = this;
      subTask.unloadLevel(function () {
         that.blocklyHelper.unload();
         callback();
      });
   };

   subTask.reset = function() {
      this.context.reset();
   };

   subTask.program_end = function(callback) {
      this.context.program_end(callback);
   };

   var initContextForLevel = function(iTestCase) {
      subTask.iTestCase = iTestCase;
      subTask.context.reset(subTask.data[subTask.level][iTestCase]);
      subTask.context.iTestCase = iTestCase;
      subTask.context.nbTestCases = subTask.nbTestCases;
      //      var prefix = "Test " + (subTask.iTestCase + 1) + "/" + subTask.nbTestCases + " : ";
      subTask.context.messagePrefixFailure = '';
      subTask.context.messagePrefixSuccess = '';
      subTask.context.linkBack = false;
   };

   subTask.run = function() {
      initBlocklyRunner(subTask.context, function(message, success) {
         $("#errors").html(''+message+'');
      });
      initContextForLevel(subTask.iTestCase);
      subTask.blocklyHelper.run(subTask.context);
   };

   subTask.submit = function() {
      this.context.display = false;
      this.getAnswerObject(); // to fill this.answer;

      $('#displayHelper_graderMessage').html('
' + languageStrings.gradingInProgress + '
');

      this.getGrade(function(result) {
         $('#displayHelper_graderMessage').html("");
         subTask.context.display = true;
         subTask.context.changeDelay(200);
         initBlocklyRunner(subTask.context, function(message, success) {
            $("#errors").html(''+message+'');
            platform.validate("done");
         });
         subTask.changeTest(result.iTestCase - subTask.iTestCase);
         initContextForLevel(result.iTestCase);
         subTask.context.linkBack = true;
         subTask.context.messagePrefixSuccess = window.languageStrings.allTests;
         subTask.blocklyHelper.run(subTask.context);
      }, true);
   };

   subTask.step = function () {
      subTask.context.changeDelay(200);
      if(!subTask.context.runner || subTask.context.runner.nbRunning() <= 0) {
        initBlocklyRunner(subTask.context, function(message, success) {
           $("#errors").html(''+message+'');
        });
        initContextForLevel(subTask.iTestCase);
      }
      subTask.blocklyHelper.step(subTask.context);
   };

   subTask.stop = function() {
      if(this.context.runner) {
         this.context.runner.stop();
      }
      $('#errors').html('');
      this.context.reset();
   };

   subTask.reloadStateObject = function(stateObj) {
      this.state = stateObj;
//      this.level = state.level;

//      initContextForLevel(this.level);

//      this.context.runner.stop();
   };

   subTask.loadExample = function() {
      subTask.blocklyHelper.loadExample(subTask.levelGridInfos.example);
   };

   subTask.getDefaultStateObject = function() {
      return { level: "easy" };
   };

   subTask.getStateObject = function() {
      this.state.level = this.level;
      return this.state;
   };

   subTask.changeSpeed =  function(speed) {
      this.context.changeDelay(speed);
      if ((this.context.runner == undefined) || !this.context.runner.isRunning()) {
         this.run();
      } else if (this.context.runner.stepMode) {
         this.context.runner.run();
      }
   };

   subTask.getAnswerObject = function() {
      this.blocklyHelper.savePrograms();

      this.answer = this.blocklyHelper.programs;
      return this.answer;
   };

   subTask.reloadAnswerObject = function(answerObj) {
      if(typeof answerObj === "undefined") {
        this.answer = this.getDefaultAnswerObject();
      } else {
        this.answer = answerObj;
      }
      this.blocklyHelper.programs = this.answer;
      if (this.answer != undefined) {
         this.blocklyHelper.loadPrograms();
      }
   };

   subTask.getDefaultAnswerObject = function() {
      var defaultBlockly = this.blocklyHelper.getDefaultContent();
      return [{javascript:"", blockly: defaultBlockly, blocklyJS: ""}];
   };

   subTask.changeTest = function(delta) {
      var newTest = subTask.iTestCase + delta;
      if ((newTest >= 0) && (newTest < this.nbTestCases)) {
         if(this.context.runner) {
            this.context.runner.stop();
         }
         initContextForLevel(newTest);
         if(subTask.context.display) {
            window.quickAlgoInterface.updateTestSelector(newTest);
         }
      }
   };

   subTask.changeTestTo = function(iTest) {
      var delta = iTest - subTask.iTestCase;
      if(delta != 0) {
         subTask.changeTest(delta);
      }
   };

   subTask.getGrade = function(callback, display) {
      subTask.context.changeDelay(0);
      var code = subTask.blocklyHelper.getCodeFromXml(subTask.answer[0].blockly, "javascript");
      code = subTask.blocklyHelper.getFullCode(code);

      var checkError = '';
      var checkDisplay = function(err) { checkError = err; }
      if(!subTask.blocklyHelper.checkCode(code, checkDisplay)) {
         var results = {
            message: checkError,
            successRate: 0,
            iTestCase: 0
         };
         callback(results);
         return;
      }

      var codes = [code]; // We only ever send one code to grade
      subTask.iTestCase = 0;

/*      var levelResultsCache = window.taskResultsCache[this.level];

      if(levelResultsCache[code]) {
         // We already have a cached result for that
         window.quickAlgoInterface.updateTestScores(levelResultsCache[code].fullResults);
         callback(levelResultsCache[code].results);
         return;
      }*/

      initBlocklyRunner(subTask.context, function(message, success) {
         var computeGrade = function(context, message) {
            var rate = 0;
            if (context.success) {
               rate = 1;
            }
            return {
               successRate: rate,
               message: message
            };
         }
         if (subTask.levelGridInfos.computeGrade != undefined) {
            computeGrade = subTask.levelGridInfos.computeGrade;
         }
         subTask.testCaseResults[subTask.iTestCase] = computeGrade(subTask.context, message)
         subTask.iTestCase++;
         if (subTask.iTestCase < subTask.nbTestCases) {
            initContextForLevel(subTask.iTestCase);
            subTask.context.runner.runCodes(codes);
         } else {
            var iWorstTestCase = 0;
            var worstRate = 1;
            var nbSuccess = 0;
            for (var iCase = 0; iCase < subTask.nbTestCases; iCase++) {
               if (subTask.testCaseResults[iCase].successRate >= 1) {
                  nbSuccess++;
               }
               if (subTask.testCaseResults[iCase].successRate < worstRate) {
                  worstRate = subTask.testCaseResults[iCase].successRate;
                  iWorstTestCase = iCase;
               }
            }
            subTask.testCaseResults[iWorstTestCase].iTestCase = iWorstTestCase;
            if(display) {
               window.quickAlgoInterface.updateTestScores(subTask.testCaseResults);
            }
            if(subTask.testCaseResults[iWorstTestCase].successRate < 1) {
               if(subTask.nbTestCases == 1) {
                  var msg = subTask.testCaseResults[iWorstTestCase].message;
               } else if(nbSuccess > 0) {
                  var msg = languageStrings.resultsPartialSuccess.format({
                     nbSuccess: nbSuccess,
                     nbTests: subTask.nbTestCases
                     });
               } else {
                  var msg = languageStrings.resultsNoSuccess;
               }
               var results = {
                  message: msg,
                  successRate: subTask.testCaseResults[iWorstTestCase].successRate,
                  iTestCase: iWorstTestCase
               };
            } else {
               var results = subTask.testCaseResults[iWorstTestCase];
            }
            /*levelResultsCache[code] = {
               results: results,
               fullResults: subTask.testCaseResults
               };*/
            callback(results);
         }
      });
      subTask.iTestCase = 0;
      subTask.testCaseResults = [];
      initContextForLevel(subTask.iTestCase);
      subTask.context.linkBack = true;
      subTask.context.messagePrefixSuccess = window.languageStrings.allTests;
      subTask.context.runner.runCodes(codes);
   };
}
<commit_msg>quickAlgo: No grading when hideValidate is true<commit_after>/*
    subtask:
        Logic for quickAlgo tasks, implements the Bebras task API.
*/

var initBlocklySubTask = function(subTask, language) {
   // Blockly tasks need to always have the level-specific behavior from
   // beaver-task-2.0
   subTask.assumeLevels = true;

   if (subTask.data["medium"] == undefined) {
      subTask.load = function(views, callback) {
         subTask.loadLevel("easy");
         callback();
      };
   }

   if (language == undefined) {
      language = "fr";
   }

   subTask.loadLevel = function(curLevel) {
      subTask.levelGridInfos = extractLevelSpecific(subTask.gridInfos, curLevel);

      subTask.blocklyHelper = getBlocklyHelper(subTask.levelGridInfos.maxInstructions);
      subTask.answer = null;
      subTask.state = {};
      subTask.iTestCase = 0;
      if(!window.taskResultsCache) {
         window.taskResultsCache = {};
      }
      if(!window.taskResultsCache[curLevel]) {
         window.taskResultsCache[curLevel] = {};
      }

      this.level = curLevel;

      // TODO: fix bebras platform to make this unnecessary
      try {
         $('#question-iframe', window.parent.document).css('width', '100%');
      } catch(e) {
      }
      $('body').css("width", "100%").addClass('blockly');
      window.focus();

      this.iTestCase = 0;
      this.nbTestCases = subTask.data[curLevel].length;

      this.context = quickAlgoLibraries.getContext(this.display, subTask.levelGridInfos, curLevel);
      this.context.raphaelFactory = this.raphaelFactory;
      this.context.delayFactory = this.delayFactory;
      this.context.blocklyHelper = this.blocklyHelper;

      if (this.display) {
        window.quickAlgoInterface.loadInterface(this.context);
        window.quickAlgoInterface.setOptions({
           hideSaveOrLoad: subTask.levelGridInfos.hideSaveOrLoad,
           hasExample: subTask.levelGridInfos.example && subTask.levelGridInfos.example[subTask.blocklyHelper.language],
           conceptViewer: subTask.levelGridInfos.conceptViewer,
           conceptViewerLang: this.blocklyHelper.language
           });
      }

      this.blocklyHelper.loadContext(this.context);

      //this.answer = task.getDefaultAnswerObject();
      displayHelper.hideValidateButton = true;
      displayHelper.timeoutMinutes = 30;

      var curIncludeBlocks = extractLevelSpecific(this.context.infos.includeBlocks, curLevel);

      // Load concepts into conceptViewer; must be done before loading
      // Blockly/Scratch, as scratch-mode will modify includeBlocks
      if(this.display && subTask.levelGridInfos.conceptViewer) {
         // TODO :: testConcepts is temporary-ish
         if(this.context.conceptList) {
            var allConcepts = testConcepts.concat(this.context.conceptList);
         } else {
            var allConcepts = testConcepts;
         }

         var concepts = window.getConceptsFromBlocks(curIncludeBlocks, allConcepts, this.context);
         if(subTask.levelGridInfos.conceptViewer.length) {
            concepts = concepts.concat(subTask.levelGridInfos.conceptViewer);
         }
         concepts = window.conceptsFill(concepts, allConcepts);
         window.conceptViewer.loadConcepts(concepts);
      }

      this.blocklyHelper.setIncludeBlocks(curIncludeBlocks);

      var blocklyOptions = {
         readOnly: !!subTask.taskParams.readOnly,
         defaultCode: subTask.defaultCode
      };

      this.blocklyHelper.load(stringsLanguage, this.display, this.data[curLevel].length, blocklyOptions);

      if(this.display) {
         window.quickAlgoInterface.initTestSelector(this.nbTestCases);
      }

      subTask.changeTest(0);
   };

   subTask.updateScale = function() {
      this.context.updateScale();
      this.blocklyHelper.updateSize();
   };

   var resetScores = function() {
   };

   var updateScores = function() {
   };

   function changeScore(robot, deltaScore) {
      scores[robot] += deltaScore;
      updateScores();
   };

   subTask.unloadLevel = function(callback) {
      window.quickAlgoInterface.resetTestScores();
      this.context.unload();
      this.blocklyHelper.unloadLevel();
      callback();
   };

   subTask.unload = function(callback) {
      var that = this;
      subTask.unloadLevel(function () {
         that.blocklyHelper.unload();
         callback();
      });
   };

   subTask.reset = function() {
      this.context.reset();
   };

   subTask.program_end = function(callback) {
      this.context.program_end(callback);
   };

   var initContextForLevel = function(iTestCase) {
      subTask.iTestCase = iTestCase;
      subTask.context.reset(subTask.data[subTask.level][iTestCase]);
      subTask.context.iTestCase = iTestCase;
      subTask.context.nbTestCases = subTask.nbTestCases;
      //      var prefix = "Test " + (subTask.iTestCase + 1) + "/" + subTask.nbTestCases + " : ";
      subTask.context.messagePrefixFailure = '';
      subTask.context.messagePrefixSuccess = '';
      subTask.context.linkBack = false;
   };

   subTask.run = function() {
      initBlocklyRunner(subTask.context, function(message, success) {
         $("#errors").html(''+message+'');
      });
      initContextForLevel(subTask.iTestCase);
      subTask.blocklyHelper.run(subTask.context);
   };

   subTask.submit = function() {
      this.context.display = false;
      this.getAnswerObject(); // to fill this.answer;

      $('#displayHelper_graderMessage').html('
' + languageStrings.gradingInProgress + '
');

      this.getGrade(function(result) {
         $('#displayHelper_graderMessage').html("");
         subTask.context.display = true;
         subTask.context.changeDelay(200);
         initBlocklyRunner(subTask.context, function(message, success) {
            $("#errors").html(''+message+'');
            platform.validate("done");
         });
         subTask.changeTest(result.iTestCase - subTask.iTestCase);
         initContextForLevel(result.iTestCase);
         subTask.context.linkBack = true;
         subTask.context.messagePrefixSuccess = window.languageStrings.allTests;
         subTask.blocklyHelper.run(subTask.context);
      }, true);
   };

   subTask.step = function () {
      subTask.context.changeDelay(200);
      if(!subTask.context.runner || subTask.context.runner.nbRunning() <= 0) {
        initBlocklyRunner(subTask.context, function(message, success) {
           $("#errors").html(''+message+'');
        });
        initContextForLevel(subTask.iTestCase);
      }
      subTask.blocklyHelper.step(subTask.context);
   };

   subTask.stop = function() {
      if(this.context.runner) {
         this.context.runner.stop();
      }
      $('#errors').html('');
      this.context.reset();
   };

   subTask.reloadStateObject = function(stateObj) {
      this.state = stateObj;
//      this.level = state.level;

//      initContextForLevel(this.level);

//      this.context.runner.stop();
   };

   subTask.loadExample = function() {
      subTask.blocklyHelper.loadExample(subTask.levelGridInfos.example);
   };

   subTask.getDefaultStateObject = function() {
      return { level: "easy" };
   };

   subTask.getStateObject = function() {
      this.state.level = this.level;
      return this.state;
   };

   subTask.changeSpeed =  function(speed) {
      this.context.changeDelay(speed);
      if ((this.context.runner == undefined) || !this.context.runner.isRunning()) {
         this.run();
      } else if (this.context.runner.stepMode) {
         this.context.runner.run();
      }
   };

   subTask.getAnswerObject = function() {
      this.blocklyHelper.savePrograms();

      this.answer = this.blocklyHelper.programs;
      return this.answer;
   };

   subTask.reloadAnswerObject = function(answerObj) {
      if(typeof answerObj === "undefined") {
        this.answer = this.getDefaultAnswerObject();
      } else {
        this.answer = answerObj;
      }
      this.blocklyHelper.programs = this.answer;
      if (this.answer != undefined) {
         this.blocklyHelper.loadPrograms();
      }
   };

   subTask.getDefaultAnswerObject = function() {
      var defaultBlockly = this.blocklyHelper.getDefaultContent();
      return [{javascript:"", blockly: defaultBlockly, blocklyJS: ""}];
   };

   subTask.changeTest = function(delta) {
      var newTest = subTask.iTestCase + delta;
      if ((newTest >= 0) && (newTest < this.nbTestCases)) {
         if(this.context.runner) {
            this.context.runner.stop();
         }
         initContextForLevel(newTest);
         if(subTask.context.display) {
            window.quickAlgoInterface.updateTestSelector(newTest);
         }
      }
   };

   subTask.changeTestTo = function(iTest) {
      var delta = iTest - subTask.iTestCase;
      if(delta != 0) {
         subTask.changeTest(delta);
      }
   };

   subTask.getGrade = function(callback, display) {
      if(subTask.context.infos && subTask.context.infos.hideValidate) {
         // There's no validation
         callback({
            message: '',
            successRate: 1,
            iTestCase: 0
            });
         return;
      }

      subTask.context.changeDelay(0);
      var code = subTask.blocklyHelper.getCodeFromXml(subTask.answer[0].blockly, "javascript");
      code = subTask.blocklyHelper.getFullCode(code);

      var checkError = '';
      var checkDisplay = function(err) { checkError = err; }
      if(!subTask.blocklyHelper.checkCode(code, checkDisplay)) {
         var results = {
            message: checkError,
            successRate: 0,
            iTestCase: 0
         };
         callback(results);
         return;
      }

      var codes = [code]; // We only ever send one code to grade
      subTask.iTestCase = 0;

/*      var levelResultsCache = window.taskResultsCache[this.level];

      if(levelResultsCache[code]) {
         // We already have a cached result for that
         window.quickAlgoInterface.updateTestScores(levelResultsCache[code].fullResults);
         callback(levelResultsCache[code].results);
         return;
      }*/

      initBlocklyRunner(subTask.context, function(message, success) {
         var computeGrade = function(context, message) {
            var rate = 0;
            if (context.success) {
               rate = 1;
            }
            return {
               successRate: rate,
               message: message
            };
         }
         if (subTask.levelGridInfos.computeGrade != undefined) {
            computeGrade = subTask.levelGridInfos.computeGrade;
         }
         subTask.testCaseResults[subTask.iTestCase] = computeGrade(subTask.context, message)
         subTask.iTestCase++;
         if (subTask.iTestCase < subTask.nbTestCases) {
            initContextForLevel(subTask.iTestCase);
            subTask.context.runner.runCodes(codes);
         } else {
            var iWorstTestCase = 0;
            var worstRate = 1;
            var nbSuccess = 0;
            for (var iCase = 0; iCase < subTask.nbTestCases; iCase++) {
               if (subTask.testCaseResults[iCase].successRate >= 1) {
                  nbSuccess++;
               }
               if (subTask.testCaseResults[iCase].successRate < worstRate) {
                  worstRate = subTask.testCaseResults[iCase].successRate;
                  iWorstTestCase = iCase;
               }
            }
            subTask.testCaseResults[iWorstTestCase].iTestCase = iWorstTestCase;
            if(display) {
               window.quickAlgoInterface.updateTestScores(subTask.testCaseResults);
            }
            if(subTask.testCaseResults[iWorstTestCase].successRate < 1) {
               if(subTask.nbTestCases == 1) {
                  var msg = subTask.testCaseResults[iWorstTestCase].message;
               } else if(nbSuccess > 0) {
                  var msg = languageStrings.resultsPartialSuccess.format({
                     nbSuccess: nbSuccess,
                     nbTests: subTask.nbTestCases
                     });
               } else {
                  var msg = languageStrings.resultsNoSuccess;
               }
               var results = {
                  message: msg,
                  successRate: subTask.testCaseResults[iWorstTestCase].successRate,
                  iTestCase: iWorstTestCase
               };
            } else {
               var results = subTask.testCaseResults[iWorstTestCase];
            }
            /*levelResultsCache[code] = {
               results: results,
               fullResults: subTask.testCaseResults
               };*/
            callback(results);
         }
      });
      subTask.iTestCase = 0;
      subTask.testCaseResults = [];
      initContextForLevel(subTask.iTestCase);
      subTask.context.linkBack = true;
      subTask.context.messagePrefixSuccess = window.languageStrings.allTests;
      subTask.context.runner.runCodes(codes);
   };
}
<|endoftext|>


<commit_before>/**
 * @description	This module is used for the context menu.
 * @copyright	2015 by Tobias Reich
 */

contextMenu = {}

contextMenu.add = function(e) {

	var items = [
		{ type: 'item', title: build.iconic('image') + 'Upload Photo', fn: function() { $('#upload_files').click() } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('link-intact') + 'Import from Link', fn: upload.start.url },
		{ type: 'item', title: build.iconic('dropbox', 'ionicons', 'ionicons') + 'Import from Dropbox', fn: upload.start.dropbox },
		{ type: 'item', title: build.iconic('terminal') + 'Import from Server', fn: upload.start.server },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('folder') + 'New Album', fn: album.add }
	];

	basicContext.show(items, e);

	upload.notify();

}

contextMenu.settings = function(e) {

	var items = [
		{ type: 'item', title: build.iconic('person') + 'Change Login', fn: settings.setLogin },
		{ type: 'item', title: build.iconic('sort-ascending') + 'Change Sorting', fn: settings.setSorting },
		{ type: 'item', title: build.iconic('dropbox', 'ionicons', 'ionicons') + 'Set Dropbox', fn: settings.setDropboxKey },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('info') + 'About Lychee', fn: function() { window.open(lychee.website) } },
		{ type: 'item', title: build.iconic('wrench') + 'Diagnostics', fn: function() { window.open('plugins/check/') } },
		{ type: 'item', title: build.iconic('align-left') + 'Show Log', fn: function() { window.open('plugins/displaylog/') } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('account-logout') + 'Sign Out', fn: lychee.logout }
	];

	basicContext.show(items, e);

}

contextMenu.album = function(albumID, e) {

	if (albumID==='0'||albumID==='f'||albumID==='s'||albumID==='r') return false;

	var items = [
		{ type: 'item', title: build.iconic('pencil') + 'Rename', fn: function() { album.setTitle([albumID]) } },
		{ type: 'item', title: build.iconic('trash') + 'Delete', fn: function() { album.delete([albumID]) } }
	];

	$('.album[data-id="' + albumID + '"]').addClass('active');

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.albumMulti = function(albumIDs, e) {

	multiselect.stopResize();

	var items = [
		{ type: 'item', title: build.iconic('pencil') + 'Rename All', fn: function() { album.setTitle(albumIDs) } },
		{ type: 'item', title: build.iconic('trash') + 'Delete All', fn: function() { album.delete(albumIDs) } }
	];

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.albumTitle = function(albumID, e) {

	var items = [
		{ type: 'item', title: build.iconic('pencil') + 'Rename', fn: function() { album.setTitle([albumID]) } }
	];

	api.post('Album::getAll', {}, function(data) {

		if (data.num>1) {

			items.push({ type: 'separator' });

			// Generate list of albums
			$.each(data.content, function(index) {

				var that	= this,
					title	= '';

				if (!that.thumb0) that.thumb0 = 'src/images/no_cover.svg';

				title = "
" + that.title + "
";

				if (that.id!=albumID) items.push({ type: 'item', title, fn: function() { lychee.goto(that.id) } });

			});

		}

		basicContext.show(items, e, contextMenu.close);

	});

}

contextMenu.photo = function(photoID, e) {

	// Notice for 'Move':
	// fn must call basicContext.close() first,
	// in order to keep the selection

	var items = [
		{ type: 'item', title: build.iconic('star') + 'Star', fn: function() { photo.setStar([photoID]) } },
		{ type: 'item', title: build.iconic('tag') + 'Tags', fn: function() { photo.editTags([photoID]) } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('pencil') + 'Rename', fn: function() { photo.setTitle([photoID]) } },
		{ type: 'item', title: build.iconic('layers') + 'Duplicate', fn: function() { photo.duplicate([photoID]) } },
		{ type: 'item', title: build.iconic('folder') + 'Move', fn: function() { basicContext.close(); contextMenu.move([photoID], e); } },
		{ type: 'item', title: build.iconic('trash') + 'Delete', fn: function() { photo.delete([photoID]) } }
	];

	$('.photo[data-id="' + photoID + '"]').addClass('active');

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.photoMulti = function(photoIDs, e) {

	// Notice for 'Move All':
	// fn must call basicContext.close() first,
	// in order to keep the selection and multiselect

	multiselect.stopResize();

	var items = [
		{ type: 'item', title: build.iconic('star') + 'Star All', fn: function() { photo.setStar(photoIDs) } },
		{ type: 'item', title: build.iconic('tag') + 'Tag All', fn: function() { photo.editTags(photoIDs) } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('pencil') + 'Rename All', fn: function() { photo.setTitle(photoIDs) } },
		{ type: 'item', title: build.iconic('layers') + 'Duplicate All', fn: function() { photo.duplicate(photoIDs) } },
		{ type: 'item', title: build.iconic('folder') + 'Move All', fn: function() { basicContext.close(); contextMenu.move(photoIDs, e); } },
		{ type: 'item', title: build.iconic('trash') + 'Delete All', fn: function() { photo.delete(photoIDs) } }
	];

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.photoTitle = function(albumID, photoID, e) {

	var items = [
		{ type: 'item', title: build.iconic('pencil') + 'Rename', fn: function() { photo.setTitle([photoID]) } }
	];

	var data = album.json;

	if (data.num>1) {

		items.push({ type: 'separator' });

		// Generate list of albums
		$.each(data.content, function(index) {

			var that	= this,
				title	= '';

			title = "
" + that.title + "
";

			if (that.id!=photoID) items.push({ type: 'item', title, fn: function() { lychee.goto(albumID + '/' + that.id) } });

		});

	}

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.photoMore = function(photoID, e) {

	var items = [
		{ type: 'item', title: build.iconic('fullscreen-enter') + 'Full Photo', fn: function() { window.open(photo.getDirectLink()) } },
		{ type: 'item', title: build.iconic('cloud-download') + 'Download', fn: function() { photo.getArchive(photoID) } }
	];

	// Remove download-item when
	// 1) In public mode
	// 2) Downloadable not 1 or not found
	if (!(album.json&&album.json.downloadable&&album.json.downloadable==='1')&&
		lychee.publicMode===true) items.splice(1, 1);

	basicContext.show(items, e);

}

contextMenu.move = function(photoIDs, e) {

	var items = [];

	// Show Unsorted when unsorted is not the current album
	if (album.getID()!=='0') {

		items = [
			{ type: 'item', title: 'Unsorted', fn: function() { photo.setAlbum(photoIDs, 0) } },
			{ type: 'separator' }
		];

	}

	api.post('Album::getAll', {}, function(data) {

		if (data.num===0) {

			// Show only 'Add album' when no album available
			items = [
				{ type: 'item', title: 'New Album', fn: album.add }
			];

		} else {

			// Generate list of albums
			$.each(data.content, function(index) {

				var that = this;

				if (!that.thumb0) that.thumb0 = 'src/images/no_cover.svg';
				that.title = "
" + that.title + "
";

				if (that.id!=album.getID()) items.push({ type: 'item', title: that.title, fn: function() { photo.setAlbum(photoIDs, that.id) } });

			});

		}

		basicContext.show(items, e, contextMenu.close);

	});

}

contextMenu.sharePhoto = function(photoID, e) {

	var link	= photo.getViewLink(photoID),
		file	= 'ionicons';

	if (photo.json.public==='2') link = location.href;

	var items = [
		{ type: 'item', title: '<input readonly id="link" value="' + link + '">', fn: function() {}, class: 'noHover' },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('twitter', file, file) + 'Twitter', fn: function() { photo.share(photoID, 0) } },
		{ type: 'item', title: build.iconic('facebook', file, file) + 'Facebook', fn: function() { photo.share(photoID, 1) } },
		{ type: 'item', title: build.iconic('envelope-closed') + 'Mail', fn: function() { photo.share(photoID, 2) } },
		{ type: 'item', title: build.iconic('dropbox', file, file) + 'Dropbox', fn: function() { photo.share(photoID, 3) } },
		{ type: 'item', title: build.iconic('link-intact') + 'Direct Link', fn: function() { window.open(photo.getDirectLink()) } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('ban') + 'Make Private', fn: function() { photo.setPublic(photoID) } }
	];

	basicContext.show(items, e);
	$('.basicContext input#link').focus().select();

}

contextMenu.shareAlbum = function(albumID, e) {

	var file = 'ionicons';

	var items = [
		{ type: 'item', title: '<input readonly id="link" value="' + location.href + '">', fn: function() {}, class: 'noHover' },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('twitter', file, file) + 'Twitter', fn: function() { album.share(0) } },
		{ type: 'item', title: build.iconic('facebook', file, file) + 'Facebook', fn: function() { album.share(1) } },
		{ type: 'item', title: build.iconic('envelope-closed') + 'Mail', fn: function() { album.share(2) } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('ban') + 'Make Private', fn: function() { album.setPublic(albumID) } }
	];

	basicContext.show(items, e);
	$('.basicContext input#link').focus().select();

}

contextMenu.close = function() {

	if (!visible.contextMenu()) return false;

	basicContext.close();

	$('.photo.active, .album.active').removeClass('active');
	if (visible.multiselect()) multiselect.close();

}<commit_msg>Fixed move photo<commit_after>/**
 * @description	This module is used for the context menu.
 * @copyright	2015 by Tobias Reich
 */

contextMenu = {}

contextMenu.add = function(e) {

	var items = [
		{ type: 'item', title: build.iconic('image') + 'Upload Photo', fn: function() { $('#upload_files').click() } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('link-intact') + 'Import from Link', fn: upload.start.url },
		{ type: 'item', title: build.iconic('dropbox', 'ionicons', 'ionicons') + 'Import from Dropbox', fn: upload.start.dropbox },
		{ type: 'item', title: build.iconic('terminal') + 'Import from Server', fn: upload.start.server },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('folder') + 'New Album', fn: album.add }
	];

	basicContext.show(items, e);

	upload.notify();

}

contextMenu.settings = function(e) {

	var items = [
		{ type: 'item', title: build.iconic('person') + 'Change Login', fn: settings.setLogin },
		{ type: 'item', title: build.iconic('sort-ascending') + 'Change Sorting', fn: settings.setSorting },
		{ type: 'item', title: build.iconic('dropbox', 'ionicons', 'ionicons') + 'Set Dropbox', fn: settings.setDropboxKey },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('info') + 'About Lychee', fn: function() { window.open(lychee.website) } },
		{ type: 'item', title: build.iconic('wrench') + 'Diagnostics', fn: function() { window.open('plugins/check/') } },
		{ type: 'item', title: build.iconic('align-left') + 'Show Log', fn: function() { window.open('plugins/displaylog/') } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('account-logout') + 'Sign Out', fn: lychee.logout }
	];

	basicContext.show(items, e);

}

contextMenu.album = function(albumID, e) {

	if (albumID==='0'||albumID==='f'||albumID==='s'||albumID==='r') return false;

	var items = [
		{ type: 'item', title: build.iconic('pencil') + 'Rename', fn: function() { album.setTitle([albumID]) } },
		{ type: 'item', title: build.iconic('trash') + 'Delete', fn: function() { album.delete([albumID]) } }
	];

	$('.album[data-id="' + albumID + '"]').addClass('active');

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.albumMulti = function(albumIDs, e) {

	multiselect.stopResize();

	var items = [
		{ type: 'item', title: build.iconic('pencil') + 'Rename All', fn: function() { album.setTitle(albumIDs) } },
		{ type: 'item', title: build.iconic('trash') + 'Delete All', fn: function() { album.delete(albumIDs) } }
	];

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.albumTitle = function(albumID, e) {

	var items = [
		{ type: 'item', title: build.iconic('pencil') + 'Rename', fn: function() { album.setTitle([albumID]) } }
	];

	api.post('Album::getAll', {}, function(data) {

		if (data.num>1) {

			items.push({ type: 'separator' });

			// Generate list of albums
			$.each(data.content, function(index) {

				var that	= this,
					title	= '';

				if (!that.thumb0) that.thumb0 = 'src/images/no_cover.svg';

				title = "
" + that.title + "
";

				if (that.id!=albumID) items.push({ type: 'item', title, fn: function() { lychee.goto(that.id) } });

			});

		}

		basicContext.show(items, e, contextMenu.close);

	});

}

contextMenu.photo = function(photoID, e) {

	// Notice for 'Move':
	// fn must call basicContext.close() first,
	// in order to keep the selection

	var items = [
		{ type: 'item', title: build.iconic('star') + 'Star', fn: function() { photo.setStar([photoID]) } },
		{ type: 'item', title: build.iconic('tag') + 'Tags', fn: function() { photo.editTags([photoID]) } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('pencil') + 'Rename', fn: function() { photo.setTitle([photoID]) } },
		{ type: 'item', title: build.iconic('layers') + 'Duplicate', fn: function() { photo.duplicate([photoID]) } },
		{ type: 'item', title: build.iconic('folder') + 'Move', fn: function() { basicContext.close(); contextMenu.move([photoID], e); } },
		{ type: 'item', title: build.iconic('trash') + 'Delete', fn: function() { photo.delete([photoID]) } }
	];

	$('.photo[data-id="' + photoID + '"]').addClass('active');

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.photoMulti = function(photoIDs, e) {

	// Notice for 'Move All':
	// fn must call basicContext.close() first,
	// in order to keep the selection and multiselect

	multiselect.stopResize();

	var items = [
		{ type: 'item', title: build.iconic('star') + 'Star All', fn: function() { photo.setStar(photoIDs) } },
		{ type: 'item', title: build.iconic('tag') + 'Tag All', fn: function() { photo.editTags(photoIDs) } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('pencil') + 'Rename All', fn: function() { photo.setTitle(photoIDs) } },
		{ type: 'item', title: build.iconic('layers') + 'Duplicate All', fn: function() { photo.duplicate(photoIDs) } },
		{ type: 'item', title: build.iconic('folder') + 'Move All', fn: function() { basicContext.close(); contextMenu.move(photoIDs, e); } },
		{ type: 'item', title: build.iconic('trash') + 'Delete All', fn: function() { photo.delete(photoIDs) } }
	];

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.photoTitle = function(albumID, photoID, e) {

	var items = [
		{ type: 'item', title: build.iconic('pencil') + 'Rename', fn: function() { photo.setTitle([photoID]) } }
	];

	var data = album.json;

	if (data.num>1) {

		items.push({ type: 'separator' });

		// Generate list of albums
		$.each(data.content, function(index) {

			var that	= this,
				title	= '';

			title = "
" + that.title + "
";

			if (that.id!=photoID) items.push({ type: 'item', title, fn: function() { lychee.goto(albumID + '/' + that.id) } });

		});

	}

	basicContext.show(items, e, contextMenu.close);

}

contextMenu.photoMore = function(photoID, e) {

	var items = [
		{ type: 'item', title: build.iconic('fullscreen-enter') + 'Full Photo', fn: function() { window.open(photo.getDirectLink()) } },
		{ type: 'item', title: build.iconic('cloud-download') + 'Download', fn: function() { photo.getArchive(photoID) } }
	];

	// Remove download-item when
	// 1) In public mode
	// 2) Downloadable not 1 or not found
	if (!(album.json&&album.json.downloadable&&album.json.downloadable==='1')&&
		lychee.publicMode===true) items.splice(1, 1);

	basicContext.show(items, e);

}

contextMenu.move = function(photoIDs, e) {

	var items = [];

	// Show Unsorted when unsorted is not the current album
	if (album.getID()!=='0') {

		items = [
			{ type: 'item', title: 'Unsorted', fn: function() { photo.setAlbum(photoIDs, 0) } },
			{ type: 'separator' }
		];

	}

	api.post('Album::getAll', {}, function(data) {

		if (data.num===0) {

			// Show only 'Add album' when no album available
			items = [
				{ type: 'item', title: 'New Album', fn: album.add }
			];

		} else {

			// Generate list of albums
			$.each(data.content, function(index) {

				var that = this;

				if (!that.thumb0) that.thumb0 = 'src/images/no_cover.svg';
				that.title = "
" + that.title + "
";

				if (that.id!=album.getID()) items.push({ type: 'item', title: that.title, fn: function() { photo.setAlbum(photoIDs, that.id) } });

			});

		}

		basicContext.show(items, e, contextMenu.close);

	});

}

contextMenu.sharePhoto = function(photoID, e) {

	var link	= photo.getViewLink(photoID),
		file	= 'ionicons';

	if (photo.json.public==='2') link = location.href;

	var items = [
		{ type: 'item', title: '<input readonly id="link" value="' + link + '">', fn: function() {}, class: 'noHover' },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('twitter', file, file) + 'Twitter', fn: function() { photo.share(photoID, 0) } },
		{ type: 'item', title: build.iconic('facebook', file, file) + 'Facebook', fn: function() { photo.share(photoID, 1) } },
		{ type: 'item', title: build.iconic('envelope-closed') + 'Mail', fn: function() { photo.share(photoID, 2) } },
		{ type: 'item', title: build.iconic('dropbox', file, file) + 'Dropbox', fn: function() { photo.share(photoID, 3) } },
		{ type: 'item', title: build.iconic('link-intact') + 'Direct Link', fn: function() { window.open(photo.getDirectLink()) } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('ban') + 'Make Private', fn: function() { photo.setPublic(photoID) } }
	];

	basicContext.show(items, e);
	$('.basicContext input#link').focus().select();

}

contextMenu.shareAlbum = function(albumID, e) {

	var file = 'ionicons';

	var items = [
		{ type: 'item', title: '<input readonly id="link" value="' + location.href + '">', fn: function() {}, class: 'noHover' },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('twitter', file, file) + 'Twitter', fn: function() { album.share(0) } },
		{ type: 'item', title: build.iconic('facebook', file, file) + 'Facebook', fn: function() { album.share(1) } },
		{ type: 'item', title: build.iconic('envelope-closed') + 'Mail', fn: function() { album.share(2) } },
		{ type: 'separator' },
		{ type: 'item', title: build.iconic('ban') + 'Make Private', fn: function() { album.setPublic(albumID) } }
	];

	basicContext.show(items, e);
	$('.basicContext input#link').focus().select();

}

contextMenu.close = function() {

	if (!visible.contextMenu()) return false;

	basicContext.close();

	$('.photo.active, .album.active').removeClass('active');
	if (visible.multiselect()) multiselect.close();

}<|endoftext|>


<commit_before>import React from 'react';
import _ from 'lodash';
import ReplEntry from './ReplEntry';

export default class ReplEntries extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (

        {
          _.map(this.props.entries, (entry, pos) => {
            return <ReplEntry log={entry} index={pos} key={entry.tag}/>;
          })
        }

    );
  }
}
<commit_msg>:bug: Ignore displaying empty command<commit_after>import React from 'react';
import _ from 'lodash';
import ReplEntry from './ReplEntry';

export default class ReplEntries extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (

        {
          _.chain(this.props.entries)
            .filter(entry => entry.plainCode && entry.plainCode.trim().length)
            .map((entry, pos) => {
              return <ReplEntry log={entry} index={pos} key={entry.tag}/>;
            })
            .value()
        }

    );
  }
}
<|endoftext|>


<commit_before>/**
 * The LayerSpecModel model.
 *
 * @return LayerSpecModel (extends Backbone.Model).
 */

/* eslint-disable */

define(['underscore', 'backbone'], function(_, Backbone) {
  var LayerSpecModel = Backbone.Model.extend({
    // You should put more importants layers at the bottom of the layerOrder
    // As you see forestchange layers are the more importants so they will be added to top
    // the order will be Grump, forest cover,Conservation, Forest Use, and People layers and finally  Forest Change layers
    layerOrder: [
      // high resolution maps
      'highres',
      'sentinel_tiles',
      //-
      'grump2000',
      'mex_forest_zoning_cat',
      'mex_forest_zoning_subcat',
      // FOREST/LAND COVER CONTEXTUAL LAYER
      'forma_coverage',
      'forest2000',
      'forest2010',
      'per_minam_tree_cover',
      'cod_primary_forest_wgs',
      'can_ifl',
      'WMSLayer',
      'global_land_cover',
      'us_land_cover',
      'mex_land_cover',
      'gtm_forest_cover',
      'bra_rtrs',
      'pry_rtrs',
      'gtm_forest_density',
      'gtm_forest_change2',
      'gtm_forest_change1',
      'us_land_cover_change',
      'colombia_forest_change',
      'intact_forest',
      'pantropical',
      'idn_primary',
      'ifl_2013_deg',
      'ifl_2000',
      'mangrove_watch',
      'plantations_by_type',
      'plantations_by_species',
      'bra_plantations_by_type',
      'bra_plantations_by_species',
      'per_plantations_by_type',
      'per_plantations_by_species',
      'lbr_plantations_by_type',
      'lbr_plantations_by_species',
      'col_plantations_by_type',
      'col_plantations_by_species',
      'khm_plantations_by_type',
      'khm_plantations_by_species',
      'idn_forest_cover',
      'idn_forest_area',
      'idn_plantations_by_type',
      'idn_plantations_by_species',
      'mys_plantations_by_type',
      'mys_plantations_by_species',
      'khm_eco_land_conc',
      'usa_forest_ownership',
      'idn_peat_lands',
      'pak_user_mangroves',
      'sen_user_protected_areas',
      'hti_user_watersheds',
      'ecu_user_protected_areas',
      'bol_user_fire_frequency',
      // PEOPLE
      'resource_rights',
      'cmr_resource_rights',
      'lbr_resource_rights',
      'gnq_resource_rights',
      'nam_resource_rights',
      'land_rights',
      'aus_land_rights',
      'pan_land_rights',
      'bra_land_rights',
      'can_land_rights',
      'cri_land_rights',
      'nzl_land_rights',
      'raisg',
      'mex_land_rights',
      // CONSERVATION
      'biodiversity_hotspots',
      'biodiversity_intactness',
      'biodiversity_completeness',
      'verified_carbon',
      'azepoly',
      'wwf',
      'usa_conservation_easements',
      'birdlife',
      'tigers',
      'bra_biomes',
      'map_biomas',
      'biodiversity_hotspots',
      'protected_areasCDB',
      'khm_pa',
      'idn_leuser',
      'per_buffer',
      'per_nat_pa',
      'per_priv_pa',
      'per_reg_pa',
      'mys_proteced_areas_sabah',
      'per_protected_areas',
      // Land USE
      'per_prod_for',
      'concesiones_wrapper',
      'concesiones_forestalesNS',
      'concesiones_forestales',
      'mys_wood_fiber',
      'idn_wood_fiber',
      'cog_wood_fiber',
      'gab_wood_fiber',
      'wood_fiber_plantations',
      'cog_oil_palm',
      'lbr_oil_palm',
      'cmr_oil_palm',
      'idn_oil_palm',
      'idn_suitability',
      'mys_oil_palm',
      'bra_mining',
      'bra_soy',
      'mex_mining',
      'per_mining',
      'can_oil',
      'can_mining',
      'col_mining',
      'khm_mining',
      'gab_mining',
      'cog_mining',
      'cod_mining',
      'cmr_mining',
      'mining',
      'gab_logging',
      'caf_logging',
      'idn_for_mor',
      'idn_logging',
      'gnq_logging',
      'cmr_logging',
      'cod_logging',
      'cog_logging',
      'mys_logging',
      'mys_logging_sabah',
      'logging',
      'logging_roads',
      'raisg_mining',
      'mexican_psa',
      'bra_logging',
      'mys_wood_fiber_sabah',
      // STORIES
      'infoamazonia',
      'mongabay',
      'user_stories',
      // FOREST CHANGE
      'gfw_landsat_alerts_coverage',
      'glad_coverage',
      'terraicanvas_cover',
      'imazon_cover',
      'gran_chaco_extent',
      // FOREST CHANGE
      'per_minam_loss',
      'mangrove_2',
      'guyra',
      'terrailoss',
      'viirs_fires_alerts',
      'imazon',
      'peru_forma_250',
      'brazil_forma_250',
      'laos_forma_250',
      'indonesia_forma_250',
      'drc_forma_250',
      'prodes',
      'loss',
      'forestgain',
      'gfw_landsat_alerts',
      'umd_as_it_happens',
      'umd_as_it_happens_per',
      'umd_as_it_happens_idn',
      'umd_as_it_happens_cog',
      'uncurated_places_to_watch',
      'places_to_watch',
      'forma_month_3',
      'forma_activity',
      'oil_palm',
      'oil_palm_mills',
      'dam_hotspots'
    ],

    categoryOrder: [
      'forest_clearing',
      'forest_cover',
      'forest_use',
      'people',
      'conservation',
      'stories',
      'hrmap'
    ],

    /**
     * Add a position attribute to the provided layers.
     *
     * @param  {object} layers
     * @return {object} layers
     */
    positionizer: function(layers) {
      var layerOrder = _.intersection(this.layerOrder, _.pluck(layers, 'slug'));
      _.each(
        layerOrder,
        _.bind(function(slug, i) {
          layers[slug].position = this.layerOrder.indexOf(slug);
        }, this)
      );

      return layers;
    },

    getLayer: function(where) {
      if (!where) {
        return;
      }
      var layer = _.findWhere(this.getLayers(), where, this);
      return layer;
    },

    /**
     * Get all the layers uncategorized.
     * {forest2000: {}, gain:{}, ...}
     *
     * @return {object} layers
     */
    getLayers: function() {
      var layers = {};

      _.each(this.toJSON(), function(category) {
        _.extend(layers, category);
      });

      return this.positionizer(layers);
    },

    /**
     * Return baselayers object.
     *
     * @return {object} baselayers
     */
    getBaselayers: function() {
      return this.positionizer(this.get('forest_clearing') || {});
    },

    getBaselayer: function() {
      var baselayers = _.keys(
        this.positionizer(this.get('forest_clearing') || {})
      );
      if (baselayers.length) {
        return this.getLayer({ slug: baselayers[0] });
      }
      return {};
    },

    /**
     * Return sublayers object.
     *
     * @return {object} sublayers
     */
    getSublayers: function() {
      var layers = {};

      _.each(_.omit(this.toJSON(), 'forest_clearing'), function(results) {
        layers = _.extend(layers, results);
      });

      return this.positionizer(layers);
    },

    /**
     * Return an ordered array of categories and layers.
     *
     * @return {array} categories
     */
    getLayersByCategory: function() {
      var categories = [];

      _.each(
        this.categoryOrder,
        _.bind(function(categoryName) {
          var category = this.get(categoryName);
          if (category) {
            categories.push(
              _.sortBy(this.positionizer(category), function(layer) {
                return layer.position;
              }).reverse()
            );
          }
        }, this)
      );

      return categories;
    }
  });

  return LayerSpecModel;
});
<commit_msg>adding VIIRS<commit_after>/**
 * The LayerSpecModel model.
 *
 * @return LayerSpecModel (extends Backbone.Model).
 */

/* eslint-disable */

define(['underscore', 'backbone'], function(_, Backbone) {
  var LayerSpecModel = Backbone.Model.extend({
    // You should put more importants layers at the bottom of the layerOrder
    // As you see forestchange layers are the more importants so they will be added to top
    // the order will be Grump, forest cover,Conservation, Forest Use, and People layers and finally  Forest Change layers
    layerOrder: [
      // high resolution maps
      'highres',
      'sentinel_tiles',
      //-
      'grump2000',
      'mex_forest_zoning_cat',
      'mex_forest_zoning_subcat',
      // FOREST/LAND COVER CONTEXTUAL LAYER
      'forma_coverage',
      'forest2000',
      'forest2010',
      'per_minam_tree_cover',
      'cod_primary_forest_wgs',
      'can_ifl',
      'WMSLayer',
      'global_land_cover',
      'us_land_cover',
      'mex_land_cover',
      'gtm_forest_cover',
      'bra_rtrs',
      'pry_rtrs',
      'gtm_forest_density',
      'gtm_forest_change2',
      'gtm_forest_change1',
      'us_land_cover_change',
      'colombia_forest_change',
      'intact_forest',
      'pantropical',
      'idn_primary',
      'ifl_2013_deg',
      'ifl_2000',
      'mangrove_watch',
      'plantations_by_type',
      'plantations_by_species',
      'bra_plantations_by_type',
      'bra_plantations_by_species',
      'per_plantations_by_type',
      'per_plantations_by_species',
      'lbr_plantations_by_type',
      'lbr_plantations_by_species',
      'col_plantations_by_type',
      'col_plantations_by_species',
      'khm_plantations_by_type',
      'khm_plantations_by_species',
      'idn_forest_cover',
      'idn_forest_area',
      'idn_plantations_by_type',
      'idn_plantations_by_species',
      'mys_plantations_by_type',
      'mys_plantations_by_species',
      'khm_eco_land_conc',
      'usa_forest_ownership',
      'idn_peat_lands',
      'pak_user_mangroves',
      'sen_user_protected_areas',
      'hti_user_watersheds',
      'ecu_user_protected_areas',
      'bol_user_fire_frequency',
      // PEOPLE
      'resource_rights',
      'cmr_resource_rights',
      'lbr_resource_rights',
      'gnq_resource_rights',
      'nam_resource_rights',
      'land_rights',
      'aus_land_rights',
      'pan_land_rights',
      'bra_land_rights',
      'can_land_rights',
      'cri_land_rights',
      'nzl_land_rights',
      'raisg',
      'mex_land_rights',
      // CONSERVATION
      'biodiversity_hotspots',
      'biodiversity_intactness',
      'biodiversity_completeness',
      'verified_carbon',
      'azepoly',
      'wwf',
      'usa_conservation_easements',
      'birdlife',
      'tigers',
      'bra_biomes',
      'map_biomas',
      'biodiversity_hotspots',
      'protected_areasCDB',
      'khm_pa',
      'idn_leuser',
      'per_buffer',
      'per_nat_pa',
      'per_priv_pa',
      'per_reg_pa',
      'mys_proteced_areas_sabah',
      'per_protected_areas',
      // Land USE
      'per_prod_for',
      'concesiones_wrapper',
      'concesiones_forestalesNS',
      'concesiones_forestales',
      'mys_wood_fiber',
      'idn_wood_fiber',
      'cog_wood_fiber',
      'gab_wood_fiber',
      'wood_fiber_plantations',
      'cog_oil_palm',
      'lbr_oil_palm',
      'cmr_oil_palm',
      'idn_oil_palm',
      'idn_suitability',
      'mys_oil_palm',
      'bra_mining',
      'bra_soy',
      'mex_mining',
      'per_mining',
      'can_oil',
      'can_mining',
      'col_mining',
      'khm_mining',
      'gab_mining',
      'cog_mining',
      'cod_mining',
      'cmr_mining',
      'mining',
      'gab_logging',
      'caf_logging',
      'idn_for_mor',
      'idn_logging',
      'gnq_logging',
      'cmr_logging',
      'cod_logging',
      'cog_logging',
      'mys_logging',
      'mys_logging_sabah',
      'logging',
      'logging_roads',
      'raisg_mining',
      'mexican_psa',
      'bra_logging',
      'mys_wood_fiber_sabah',
      // STORIES
      'infoamazonia',
      'mongabay',
      'user_stories',
      // FOREST CHANGE
      'gfw_landsat_alerts_coverage',
      'glad_coverage',
      'terraicanvas_cover',
      'imazon_cover',
      'gran_chaco_extent',
      // FOREST CHANGE
      'per_minam_loss',
      'mangrove_2',
      'guyra',
      'terrailoss',
      'imazon',
      'peru_forma_250',
      'brazil_forma_250',
      'laos_forma_250',
      'indonesia_forma_250',
      'drc_forma_250',
      'prodes',
      'loss',
      'forestgain',
      'gfw_landsat_alerts',
      'umd_as_it_happens',
      'umd_as_it_happens_per',
      'umd_as_it_happens_idn',
      'umd_as_it_happens_cog',
      'uncurated_places_to_watch',
      'places_to_watch',
      'forma_month_3',
      'forma_activity',
      'oil_palm',
      'oil_palm_mills',
      'dam_hotspots',
      'viirs_fires_alerts'
    ],

    categoryOrder: [
      'forest_clearing',
      'forest_cover',
      'forest_use',
      'people',
      'conservation',
      'stories',
      'hrmap'
    ],

    /**
     * Add a position attribute to the provided layers.
     *
     * @param  {object} layers
     * @return {object} layers
     */
    positionizer: function(layers) {
      var layerOrder = _.intersection(this.layerOrder, _.pluck(layers, 'slug'));
      _.each(
        layerOrder,
        _.bind(function(slug, i) {
          layers[slug].position = this.layerOrder.indexOf(slug);
        }, this)
      );

      return layers;
    },

    getLayer: function(where) {
      if (!where) {
        return;
      }
      var layer = _.findWhere(this.getLayers(), where, this);
      return layer;
    },

    /**
     * Get all the layers uncategorized.
     * {forest2000: {}, gain:{}, ...}
     *
     * @return {object} layers
     */
    getLayers: function() {
      var layers = {};

      _.each(this.toJSON(), function(category) {
        _.extend(layers, category);
      });

      return this.positionizer(layers);
    },

    /**
     * Return baselayers object.
     *
     * @return {object} baselayers
     */
    getBaselayers: function() {
      return this.positionizer(this.get('forest_clearing') || {});
    },

    getBaselayer: function() {
      var baselayers = _.keys(
        this.positionizer(this.get('forest_clearing') || {})
      );
      if (baselayers.length) {
        return this.getLayer({ slug: baselayers[0] });
      }
      return {};
    },

    /**
     * Return sublayers object.
     *
     * @return {object} sublayers
     */
    getSublayers: function() {
      var layers = {};

      _.each(_.omit(this.toJSON(), 'forest_clearing'), function(results) {
        layers = _.extend(layers, results);
      });

      return this.positionizer(layers);
    },

    /**
     * Return an ordered array of categories and layers.
     *
     * @return {array} categories
     */
    getLayersByCategory: function() {
      var categories = [];

      _.each(
        this.categoryOrder,
        _.bind(function(categoryName) {
          var category = this.get(categoryName);
          if (category) {
            categories.push(
              _.sortBy(this.positionizer(category), function(layer) {
                return layer.position;
              }).reverse()
            );
          }
        }, this)
      );

      return categories;
    }
  });

  return LayerSpecModel;
});
<|endoftext|>


<commit_before>// Slovak

jQuery.extend( jQuery.fn.pickadate.defaults, {
    monthsFull: [ 'január', 'február', 'marec', 'apríl', 'máj', 'jún', 'júl', 'august', 'september', 'október', 'november', 'december' ],
    monthsShort: [ 'jan', 'feb', 'mar', 'apr', 'máj', 'jún', 'júl', 'aug', 'sep', 'okt', 'nov', 'dec' ],
    weekdaysFull: [ 'nedeľa', 'pondelok', 'utorok', 'streda', 'štvrtok', 'piatok', 'sobota' ],
    weekdaysShort: [ 'Ne', 'Po', 'Ut', 'St', 'Št', 'Pi', 'So' ],
    today: 'dnes',
    clear: 'vymazať',
    firstDay: 1,
    format: 'd. mmmm yyyy',
    formatSubmit: 'yyyy/mm/dd'
});<commit_msg>Add translation for 'close'<commit_after>// Slovak

jQuery.extend( jQuery.fn.pickadate.defaults, {
    monthsFull: [ 'január', 'február', 'marec', 'apríl', 'máj', 'jún', 'júl', 'august', 'september', 'október', 'november', 'december' ],
    monthsShort: [ 'jan', 'feb', 'mar', 'apr', 'máj', 'jún', 'júl', 'aug', 'sep', 'okt', 'nov', 'dec' ],
    weekdaysFull: [ 'nedeľa', 'pondelok', 'utorok', 'streda', 'štvrtok', 'piatok', 'sobota' ],
    weekdaysShort: [ 'Ne', 'Po', 'Ut', 'St', 'Št', 'Pi', 'So' ],
    today: 'dnes',
    clear: 'vymazať',
    close: 'zavrieť',
    firstDay: 1,
    format: 'd. mmmm yyyy',
    formatSubmit: 'yyyy/mm/dd'
});<|endoftext|>


<commit_before>'use strict';

var m = require('mithril');

var Fangorn = require('js/fangorn').Fangorn;

// Define Fangorn Button Actions
var _figshareItemButtons = {
    view: function (ctrl, args, children) {
        var buttons = [];
        var tb = args.treebeard;
        var item = args.item;
        if (tb.options.placement !== 'fileview') {
            // If File and FileRead are not defined dropzone is not supported and neither is uploads
            if (window.File && window.FileReader && item.data.permissions && item.data.permissions.edit && item.kind === 'folder') {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            Fangorn.ButtonEvents._uploadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-upload',
                        className: 'text-success'
                    }, 'Upload')
                );
            }

            // Download file or Download-as-zip
            if (item.kind === 'file') {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            Fangorn.ButtonEvents._downloadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-download',
                        className: 'text-primary'
                    }, 'Download')
                );
            }
            else {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) { Fangorn.ButtonEvents._downloadZipEvent.call(tb, event, item); },
                        icon: 'fa fa-download',
                        className: 'text-primary'
                    }, 'Download as zip')
                );
            }

            // All files are viewable on the OSF.
            if (item.kind === 'file' && item.data.permissions && item.data.permissions.view) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            Fangorn.ButtonEvents._gotoFileEvent.call(tb, item);
                        },
                        icon: 'fa fa-file-o',
                        className: 'text-info'
                    }, 'View'));
            }

            // Files can be deleted if private or if it is in a dataset that contains more than one file
            var privateOrSiblings = (item.data.extra && item.data.extra.status !== 'public') ||
                (!item.parent().data.isAddonRoot && item.parent().children.length > 1);
            if (item.kind === 'file' && privateOrSiblings && item.data.permissions && item.data.permissions.edit) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            Fangorn.ButtonEvents._removeEvent.call(tb, event, tb.multiselected());
                        },
                        icon: 'fa fa-trash',
                        className: 'text-danger'
                    }, 'Delete')
                );
            }

            // Files are only viewable on figshare if they are public
            if (item.kind === 'file' && item.data.permissions && item.data.permissions.view && item.data.extra.status === 'public') {
                buttons.push(
                    m('a.text-info.fangorn-toolbar-icon', {href: item.data.extra.webView}, [
                        m('i.fa.fa-external-link'),
                        m('span', 'View on figshare')
                    ])
                );
            }
        }
        return m('span', buttons); // Tell fangorn this function is used.
    }
};

Fangorn.config.figshare = {
    // Fangorn options are called if functions, so return a thunk that returns the column builder
    itemButtons: _figshareItemButtons
};
<commit_msg>update fangorn delete logic<commit_after>'use strict';

var m = require('mithril');

var Fangorn = require('js/fangorn').Fangorn;

// Define Fangorn Button Actions
var _figshareItemButtons = {
    view: function (ctrl, args, children) {
        var buttons = [];
        var tb = args.treebeard;
        var item = args.item;
        if (tb.options.placement !== 'fileview') {
            // If File and FileRead are not defined dropzone is not supported and neither is uploads
            if (window.File && window.FileReader && item.data.permissions && item.data.permissions.edit && item.kind === 'folder') {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            Fangorn.ButtonEvents._uploadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-upload',
                        className: 'text-success'
                    }, 'Upload')
                );
            }

            // Download file or Download-as-zip
            if (item.kind === 'file') {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            Fangorn.ButtonEvents._downloadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-download',
                        className: 'text-primary'
                    }, 'Download')
                );
            }
            else {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) { Fangorn.ButtonEvents._downloadZipEvent.call(tb, event, item); },
                        icon: 'fa fa-download',
                        className: 'text-primary'
                    }, 'Download as zip')
                );
            }

            // All files are viewable on the OSF.
            if (item.kind === 'file' && item.data.permissions && item.data.permissions.view) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            Fangorn.ButtonEvents._gotoFileEvent.call(tb, item);
                        },
                        icon: 'fa fa-file-o',
                        className: 'text-info'
                    }, 'View'));
            }

            // Files and folders can be deleted if private.
            var isPrivate = (item.data.extra && item.data.extra.status !== 'public');
            if (isPrivate && item.data.permissions && item.data.permissions.edit) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            Fangorn.ButtonEvents._removeEvent.call(tb, event, tb.multiselected());
                        },
                        icon: 'fa fa-trash',
                        className: 'text-danger'
                    }, 'Delete')
                );
            }

            // Files are only viewable on figshare if they are public
            if (item.kind === 'file' && item.data.permissions && item.data.permissions.view && item.data.extra.status === 'public') {
                buttons.push(
                    m('a.text-info.fangorn-toolbar-icon', {href: item.data.extra.webView}, [
                        m('i.fa.fa-external-link'),
                        m('span', 'View on figshare')
                    ])
                );
            }
        }
        return m('span', buttons); // Tell fangorn this function is used.
    }
};

Fangorn.config.figshare = {
    // Fangorn options are called if functions, so return a thunk that returns the column builder
    itemButtons: _figshareItemButtons
};
<|endoftext|>


<commit_before>///*
//Copyright Jesus Perez <jesusprubio gmail com>
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.
//*/
//
//'use strict';
//
//var async   = require('async'),
//    namiLib = require('nami'),
//    Nami    = namiLib.Nami,
//
//    printer = require('../utils/printer');
//
//
//module.exports = (function () {
//
//    return {
//
//        info : {
//            name        : 'amiCoreSetting',
//            description : 'Use the Asterisk Manager service (AMI) to get the core settings of the server',
//            options     : {
//                target : {
//                    description  : 'IP address to brute-force',
//                    defaultValue : '127.0.0.1',
//                    type         : 'targetIp'
//                },
//                port : {
//                    description  : 'Port of the server',
//                    defaultValue : 5038,
//                    type         : 'port'
//                },
//                user : {
//                    description  : 'User to use in the request',
//                    defaultValue : 'admin',
//                    type         : 'anyValue'
//                },
//                password : {
//                    description  : 'Password to use in the request',
//                    defaultValue : 'amp111',
//                    type         : 'anyValue'
//                },
//                timeout : {
//                    description  : 'Time to wait for a response (ms.)',
//                    defaultValue : 5000,
//                    type         : 'positiveInt'
//                }
//            }
//        },
//
//        run : function (options, callback) {
//            var connected = false,
//                ami       = new Nami({
//                    host     : options.target,
//                    port     : options.port,
//                    username : options.user,
//                    secret   : options.password
//                });
//
//            ami.logger.setLevel('OFF');
//
//            ami.on('namiConnected', function () {
//                var action = new namiLib.Actions.CoreSettings();
//
//                connected = true;
//                ami.send(action, function (res) {
//                    ami.close();
//                    callback(null, res);
//                });
//            });
//
//            ami.on('namiLoginIncorrect', function () {
//                callback({
//                    type : 'login'
//                });
//            });
//
//            // The module do not supports connection timeout, so
//            // we add it manually ("connected" var), really dirty trick
//            setTimeout(function () {
//                if (!connected) {
//                    callback({
//                        type : 'timeout'
//                    });
//                }
//            }, options.timeout);
//            ami.open();
//        }
//    };
//
//}());
<commit_msg>amiCoreSettings module modified<commit_after>/*
Copyright Jesus Perez <jesusprubio gmail com>
		  Sergio García <s3rgio.gr gmail com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

// Private stuff

var async   = require('async'),
   	namiLib = require('nami'),
   	Nami    = namiLib.Nami,

   	printer = require('../utils/printer'),

	HELP = {
        description : 'Use the Asterisk Manager service (AMI) to get the core settings of the server',
        options     : {
            target : {
            	type : 'ip',
                description  : 'IP address to brute-force',
                defaultValue : '127.0.0.1'
            },
            port : {
            	type         : 'port',
                description  : 'Port of the server',
                defaultValue : 5038
            },
            user : {
            	type         : 'allValid',
                description  : 'User to use in the request',
                defaultValue : 'admin'
            },
            password : {
            	type         : 'allValid',
                description  : 'Password to use in the request',
                defaultValue : 'amp111'
            },
            timeout : {
            	type         : 'positiveInt',
                description  : 'Time to wait for a response (ms.)',
                defaultValue : 5000
            }
        }
    };

// Public stuff

module.exports.help = HELP;

module.exports.run = function (options, callback) {
   var connected = false,
       ami       = new Nami({
           host     : options.target,
           port     : options.port,
           username : options.user,
           secret   : options.password
       });

   ami.logger.setLevel('OFF');

   ami.on('namiConnected', function () {
       var action = new namiLib.Actions.CoreSettings();

       connected = true;
       ami.send(action, function (res) {
           ami.close();
           callback(null, res);
       });
   });

   ami.on('namiLoginIncorrect', function () {
       callback({
           type : 'login'
       });
   });

   // The module do not supports connection timeout, so
   // we add it manually ("connected" var), really dirty trick
   setTimeout(function () {
       if (!connected) {
           callback({
               type : 'timeout'
           });
       }
   }, options.timeout);
   ami.open();
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Grid, Row, Col, Image, FormGroup, FormControl, ControlLabel, HelpBlock } from 'react-bootstrap';
import DatePicker from 'react-bootstrap-date-picker';
import _ from 'lodash';
import moment from 'moment';
import AddControls from './AddControls';
import TopicChooser from './TopicChooser';

import { topics } from './stories/fixtures';

class RequestForm extends Component {

    constructor(props) {
        super(props);

        var {name: issuerName, picture: issuerAvatar} = props.route.auth.getProfile();

        this.state = {
            request: {
                fromDate: moment().toISOString(),
                toDate: moment().add(1, 'months').toISOString(),
                reason: '',
                topics: null,
                issuerName,
                issuerAvatar
            }
        }

        this.save = this.save.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    save() {
        console.log('save', this.state.request);
    }

    handleChange(key, value) {
        var request = this.state.request;
        request[key] = value;
        this.setState({
            request
        });
    }

    handleInputChange(key, evt) {
        this.handleChange(key, evt.target.value);
    }

    render(){
        return (
            <Grid>
                <Row>
                    <Col xsOffset={3} xs={6}>

Request Access to Entries

                    </Col>
                </Row>
                <Row>
                    <Col xsOffset={3} xs={6}>
                        <Image
                            src={this.state.request.issuerAvatar}
                            className='profile-img'
                            circle
                        />
                        {this.state.request.issuerName}
                    </Col>
                </Row>
                <Row>
                    <Col xsOffset={3} xs={6}>
                        <TopicChooser
                            label="Would like to see entries about"
                            topics={this.props.topics}
                            maxSelections={1}
                            onChange={_.partial(this.handleChange, 'topics')} />
                        <FormGroup>
                            <ControlLabel>From</ControlLabel>
                            <DatePicker value={this.state.request.fromDate}
                              onChange={_.partial(this.handleChange, 'fromDate')} />
                        </FormGroup>

                        <FormGroup>
                            <ControlLabel>To</ControlLabel>
                            <DatePicker value={this.state.request.toDate}
                              onChange={_.partial(this.handleChange, 'toDate')} />
                        </FormGroup>

                        <FormGroup>
                            <ControlLabel>Because</ControlLabel>
                            <FormControl componentClass="textarea"
                              maxLength={this.props.maxLength}
                              onChange={_.partial(this.handleInputChange, 'reason')} />
                            <HelpBlock>{this.state.request.reason.length} of {this.props.maxLength} letters used</HelpBlock>
                        </FormGroup>
                    </Col>
                </Row>
                <Row>
                    <Col xsOffset={3} xs={6}>
                        <AddControls onNext={this.save} />
                    </Col>
                </Row>
            </Grid>
        );
    }
}

RequestForm.propTypes = {
    maxLength: React.PropTypes.number,
    topics: React.PropTypes.array
}

RequestForm.defaultProps = {
    maxLength: 240,
    topics: topics
}

export default RequestForm;
<commit_msg>Add a preview to RequestForm<commit_after>import React, { Component } from 'react';
import { Grid, Row, Col, Image, FormGroup, FormControl, ControlLabel, HelpBlock } from 'react-bootstrap';
import DatePicker from 'react-bootstrap-date-picker';
import _ from 'lodash';
import moment from 'moment';
import AddControls from './AddControls';
import TopicChooser from './TopicChooser';
import Request from './Request';

import { topics } from './stories/fixtures';

class RequestForm extends Component {

    constructor(props) {
        super(props);

        var {name: issuerName, picture: issuerAvatar} = props.route.auth.getProfile();

        this.state = {
            request: {
                fromDate: moment().toISOString(),
                toDate: moment().add(1, 'months').toISOString(),
                reason: '',
                topics: [],
                issuerName,
                issuerAvatar
            }
        }

        this.save = this.save.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    save() {
        console.log('save', this.state.request);
    }

    handleChange(key, value) {
        var request = this.state.request;
        request[key] = value;
        this.setState({
            request
        });
    }

    handleInputChange(key, evt) {
        this.handleChange(key, evt.target.value);
    }

    render(){
        return (
            <Grid>
                <Row>
                    <Col xsOffset={3} xs={6}>

Request Access to Entries

                    </Col>
                </Row>
                <Row>
                    <Col xsOffset={3} xs={6}>

Preview:

                        <Request
                            {...this.state.request}
                             />
                    </Col>
                </Row>
                <Row>
                    <Col xsOffset={3} xs={6}>
                        <TopicChooser
                            label="Would like to see entries about"
                            topics={this.props.topics}
                            maxSelections={1}
                            onChange={_.partial(this.handleChange, 'topics')} />
                        <FormGroup>
                            <ControlLabel>From</ControlLabel>
                            <DatePicker value={this.state.request.fromDate}
                              onChange={_.partial(this.handleChange, 'fromDate')} />
                        </FormGroup>

                        <FormGroup>
                            <ControlLabel>To</ControlLabel>
                            <DatePicker value={this.state.request.toDate}
                              onChange={_.partial(this.handleChange, 'toDate')} />
                        </FormGroup>

                        <FormGroup>
                            <ControlLabel>Because</ControlLabel>
                            <FormControl componentClass="textarea"
                              maxLength={this.props.maxLength}
                              onChange={_.partial(this.handleInputChange, 'reason')} />
                            <HelpBlock>{this.state.request.reason.length} of {this.props.maxLength} letters used</HelpBlock>
                        </FormGroup>
                    </Col>
                </Row>
                <Row>
                    <Col xsOffset={3} xs={6}>
                        <AddControls onNext={this.save} />
                    </Col>
                </Row>
            </Grid>
        );
    }
}

RequestForm.propTypes = {
    maxLength: React.PropTypes.number,
    topics: React.PropTypes.array
}

RequestForm.defaultProps = {
    maxLength: 240,
    topics: topics
}

export default RequestForm;
<|endoftext|>


<commit_before>/**
 * @class Photon
 */
export class Photon {
  /**
   * @constructor
   */
  constructor() {

    this.settings = {
      url: 'http://photon.komoot.de/api/',
      params: {
        q: '',
        limit: 10,
        lang: 'en'
      },
      langs: ['de', 'it', 'fr', 'en']
    };
  }

  getParameters(options) {
    options.lang = options.lang.toLowerCase();

    return {
      url: this.settings.url,
      params: {
        q: options.query,
        limit: options.limit || this.settings.params.limit,
        lang: this.settings.langs.indexOf(options.lang) > -1 ?
          options.lang : this.settings.params.lang
      }
    };
  }

  handleResponse(results) {
    return results.map(result => ({
      lon: result.geometry.coordinates[0],
      lat: result.geometry.coordinates[1],
      address: {
        name: result.properties.name,
        postcode: result.properties.postcode,
        city: result.properties.city,
        state: result.properties.state,
        country: result.properties.country
      },
      original: {
        formatted: result.properties.name,
        details: result.properties
      }
    }));
  }
}
<commit_msg>Update photon URL to HTTPS<commit_after>/**
 * @class Photon
 */
export class Photon {
  /**
   * @constructor
   */
  constructor() {

    this.settings = {
      url: 'https://photon.komoot.de/api/',
      params: {
        q: '',
        limit: 10,
        lang: 'en'
      },
      langs: ['de', 'it', 'fr', 'en']
    };
  }

  getParameters(options) {
    options.lang = options.lang.toLowerCase();

    return {
      url: this.settings.url,
      params: {
        q: options.query,
        limit: options.limit || this.settings.params.limit,
        lang: this.settings.langs.indexOf(options.lang) > -1 ?
          options.lang : this.settings.params.lang
      }
    };
  }

  handleResponse(results) {
    return results.map(result => ({
      lon: result.geometry.coordinates[0],
      lat: result.geometry.coordinates[1],
      address: {
        name: result.properties.name,
        postcode: result.properties.postcode,
        city: result.properties.city,
        state: result.properties.state,
        country: result.properties.country
      },
      original: {
        formatted: result.properties.name,
        details: result.properties
      }
    }));
  }
}
<|endoftext|>


<commit_before>class Game extends Phaser.State {

  init (stageName, transitionName = 'fade-from-black') {
    this.game.transitions.registerTransition(transitionName);

    this.controls = this.game.controls;

    this.stageName = stageName;

    this._gameStageManager = this._makeManager(GameStageManager);
    this._objectsManager   = this._makeManager(ObjectsManager);

    this._playerActor = null;
    this._idleActor   = null;
  }

  create () {
    this.game.transitions.doTransition();

    this._stageDefinitions = this._getStageDefinitions(this.stageName);

    this._agents = this.add.existing(new Agents(this.game));

    this._heartGroup = this._objectsManager.createLayerFor('heart', true);
    this._starGroup  = this._objectsManager.createLayerFor('star', true);
    this._moonGroup  = this._objectsManager.createLayerFor('both');

    this._objectsManager.createObjects(this._stageDefinitions.objects);

    this._goal = this.add.existing(new Goal(this.game));
    this._goal.reset(this.goalCoordinates.x, this.goalCoordinates.y);
    this._goal.actorsLanded.addOnce(this._celebrate, this);

    this._heart = this.add.existing(this._makeActor(Actor.HEART));
    this._star  = this.add.existing(this._makeActor(Actor.STAR));

    this._heart.wasHurt.add(this._star.startle, this._star);
    this._star.wasHurt.add(this._heart.startle, this._heart);
    this._heart.wasHurt.add(this._actorHurt, this);
    this._star.wasHurt.add(this._actorHurt, this);

    this._restartActors();
    this._changeActors(this._heart, this._star);

    this.controls.spacebar.onUp.add(this._togglePlayerActor, this);
    this.controls.backspace.onUp.add(this._preRestartActors, this);

    this.game.storage.fetch('stages', this._unlockCurrentGameStage, this);
  }

  update () {
    this._playerActor.collideActor(this._idleActor);
    this._goal.collideActors(this._playerActor, this._idleActor);

    this._heartGroup.collide(this._heart);
    this._starGroup.collide(this._star);
    this._moonGroup.collide([ this._heart, this._star ]);

    this._agents.collide(this._playerActor);
    this._agents.collide(this._idleActor);

    if (this.inGame) {
      if (this.controls.left.isDown) {
        this._playerActor.walkLeft();
      }
      else if (this.controls.right.isDown) {
        this._playerActor.walkRight();
      }
      else {
        this._playerActor.stop();
        this._idleActor.stop();
      }

      if (this.controls.up.isDown) {
        this._playerActor.jump();
      }
      else {
        this._playerActor.cancelPowerJump();
      }
    }
    else {
      this._playerActor.stop();
      this._idleActor.stop();
    }
  }

  // --------------------------------------------------------------------------

  _makeManager (factory, ... args) {
    return new factory(this.game, ... args);
  }

  _getStageDefinitions (stageName) {
    return this._gameStageManager.getStage(stageName);
  }

  _makeActor (roleName) {
    return new Actor(this.game, roleName);
  }

  _changeActors (playerActor, idleActor) {
    this._playerActor      = playerActor;
    this._playerActor.idle = false;
    this._playerActor.stop();

    this._idleActor      = idleActor;
    this._idleActor.idle = true;
    this._idleActor.stop();

    this._toggleLayers();
  }

  _toggleLayers () {
    this._heartGroup.toggle(!this._heart.idle);
    this._starGroup.toggle(!this._star.idle);
  }

  _blink () {
    if (this._heart.idle)
      this.game.transitions.registerTransition('blink-blue');

    else if (this._star.idle)
      this.game.transitions.registerTransition('blink-pink');

    this.game.transitions.doTransition();
  }

  _closeBlinds () {
    this.game.transitions.registerTransition('blinds-close');
    this.game.transitions.registerTransitionCallback(this._goToNextStage, this);
    this.game.transitions.doTransition();
  }

  _togglePlayerActor () {
    if (!this.inGame) return;
    if (this.game.transitions.transitionRunning) return;
    if (!this._playerActor.standing) return;

    this._changeActors(this._idleActor, this._playerActor);

    this._blink();
  }

  _preRestartActors () {
    this.game.transitions.registerTransition('blinds-close');
    this.game.transitions.registerTransitionCallback(this._restartActors, this);
    this.game.transitions.doTransition();
  }

  _restartActors () {
    this._restartActor(this._heart, this.heartCoordinates);
    this._restartActor(this._star, this.starCoordinates);

    this.game.transitions.registerTransition('blinds-open');
    this.game.transitions.doTransition();

    this._changeActors(this._heart, this._star);
    this._objectsManager.reset();
  }

  _restartActor(actor, { x, y }) {
    actor.reset(x, y);
    actor.sink();
  }

  _actorHurt () {
    this.time.events.add(1500, this._preRestartActors, this);
  }

  _celebrate () {
    this._heart.emotion = 'cheering';
    this._star.emotion  = 'cheering';

    this.time.events.add(1000, this._closeBlinds, this);
  }

  _goToNextStage () {
    var nextStage = this._stageDefinitions.next;

    if (nextStage === null)
      this.state.start('Credits');
    else
      this.state.start('Game', true, false, nextStage, 'blinds-open');
  }

  _unlockCurrentGameStage (err, unlockedStages) {
    for (var unlockedStage of unlockedStages) {
      if (unlockedStage.stage === this.stageName) {
        unlockedStage.locked = false;
        break;
      }
    }

    this.game.storage.store('stages', unlockedStages);
  }

  // --------------------------------------------------------------------------

  get heartCoordinates () {
    return this._stageDefinitions.actors.heart;
  }

  get starCoordinates () {
    return this._stageDefinitions.actors.star;
  }

  get goalCoordinates () {
    return this._stageDefinitions.actors.goal;
  }

  get inGame () {
    return !this.game.transitions.transitionRunning &&
      this._playerActor && this._playerActor.emotion === null;
  }

}

import ObjectsManager   from 'managers/ObjectsManager';
import GameStageManager from 'managers/GameStageManager';

import Goal   from 'objects/Goal';
import Actor  from 'objects/Actor';
import Agents from 'objects/Agents';

export default Game;
<commit_msg>Small fix in Game state.<commit_after>class Game extends Phaser.State {

  init (stageName, transitionName = 'fade-from-black') {
    this.game.transitions.registerTransition(transitionName);

    this.controls = this.game.controls;

    this.stageName = stageName;

    this._gameStageManager = this._makeManager(GameStageManager);
    this._objectsManager   = this._makeManager(ObjectsManager);

    this._playerActor = null;
    this._idleActor   = null;
  }

  create () {
    this.game.transitions.doTransition();

    this._stageDefinitions = this._getStageDefinitions(this.stageName);

    this._agents = this.add.existing(new Agents(this.game));

    this._heartGroup = this._objectsManager.createLayerFor('heart', true);
    this._starGroup  = this._objectsManager.createLayerFor('star', true);
    this._moonGroup  = this._objectsManager.createLayerFor('both');

    this._objectsManager.createObjects(this._stageDefinitions.objects);

    this._goal = this.add.existing(new Goal(this.game));
    this._goal.reset(this.goalCoordinates.x, this.goalCoordinates.y);
    this._goal.actorsLanded.addOnce(this._celebrate, this);

    this._heart = this.add.existing(this._makeActor(Actor.HEART));
    this._star  = this.add.existing(this._makeActor(Actor.STAR));

    this._heart.wasHurt.add(this._star.startle, this._star);
    this._star.wasHurt.add(this._heart.startle, this._heart);
    this._heart.wasHurt.add(this._actorHurt, this);
    this._star.wasHurt.add(this._actorHurt, this);

    this._restartActors();
    this._changeActors(this._heart, this._star);

    this.controls.spacebar.onUp.add(this._togglePlayerActor, this);
    this.controls.backspace.onUp.add(this._preRestartActors, this);

    this.game.storage.fetch('stages', this._unlockCurrentGameStage, this);
  }

  update () {
    this._playerActor.collideActor(this._idleActor);
    this._goal.collideActors(this._playerActor, this._idleActor);

    this._heartGroup.collide(this._heart);
    this._starGroup.collide(this._star);
    this._moonGroup.collide([ this._heart, this._star ]);

    this._agents.collide(this._playerActor);
    this._agents.collide(this._idleActor);

    if (this.inGame) {
      if (this.controls.left.isDown) {
        this._playerActor.walkLeft();
      }
      else if (this.controls.right.isDown) {
        this._playerActor.walkRight();
      }
      else {
        this._playerActor.stop();
        this._idleActor.stop();
      }

      if (this.controls.up.isDown) {
        this._playerActor.jump();
      }
      else {
        this._playerActor.cancelPowerJump();
      }
    }
    else {
      this._playerActor.stop();
      this._idleActor.stop();
    }
  }

  // --------------------------------------------------------------------------

  _makeManager (factory, ... args) {
    return new factory(this.game, ... args);
  }

  _getStageDefinitions (stageName) {
    return this._gameStageManager.getStage(stageName);
  }

  _makeActor (roleName) {
    return new Actor(this.game, roleName);
  }

  _changeActors (playerActor, idleActor) {
    this._playerActor      = playerActor;
    this._playerActor.idle = false;
    this._playerActor.stop();

    this._idleActor      = idleActor;
    this._idleActor.idle = true;
    this._idleActor.stop();

    this._toggleLayers();
  }

  _toggleLayers () {
    this._heartGroup.toggle(!this._heart.idle);
    this._starGroup.toggle(!this._star.idle);
  }

  _blink () {
    if (this._heart.idle)
      this.game.transitions.registerTransition('blink-blue');

    else if (this._star.idle)
      this.game.transitions.registerTransition('blink-pink');

    this.game.transitions.doTransition();
  }

  _closeBlinds () {
    this.game.transitions.registerTransition('blinds-close');
    this.game.transitions.registerTransitionCallback(this._goToNextStage, this);
    this.game.transitions.doTransition();
  }

  _togglePlayerActor () {
    if (!this.inGame) return;
    if (this.game.transitions.transitionRunning) return;
    if (!this._playerActor.standing) return;

    this._changeActors(this._idleActor, this._playerActor);

    this._blink();
  }

  _preRestartActors () {
    this.game.transitions.registerTransition('blinds-close');
    this.game.transitions.registerTransitionCallback(this._restartActors, this);
    this.game.transitions.doTransition();
  }

  _restartActors () {
    this._restartActor(this._heart, this.heartCoordinates);
    this._restartActor(this._star, this.starCoordinates);

    this.game.transitions.registerTransition('blinds-open');
    this.game.transitions.doTransition();

    this._changeActors(this._heart, this._star);
    this._objectsManager.reset();
  }

  _restartActor(actor, { x, y }) {
    actor.reset(x, y);
    actor.sink();
  }

  _actorHurt () {
    this.time.events.add(1500, this._preRestartActors, this);
  }

  _celebrate () {
    this._heart.emotion = 'cheering';
    this._star.emotion  = 'cheering';

    this.time.events.add(1000, this._closeBlinds, this);
  }

  _goToNextStage () {
    var nextStage = this._stageDefinitions.next;

    if (nextStage === null)
      this.state.start('CreditsAI');
    else
      this.state.start('Game', true, false, nextStage, 'blinds-open');
  }

  _unlockCurrentGameStage (err, unlockedStages) {
    for (var unlockedStage of unlockedStages) {
      if (unlockedStage.stage === this.stageName) {
        unlockedStage.locked = false;
        break;
      }
    }

    this.game.storage.store('stages', unlockedStages);
  }

  // --------------------------------------------------------------------------

  get heartCoordinates () {
    return this._stageDefinitions.actors.heart;
  }

  get starCoordinates () {
    return this._stageDefinitions.actors.star;
  }

  get goalCoordinates () {
    return this._stageDefinitions.actors.goal;
  }

  get inGame () {
    return !this.game.transitions.transitionRunning &&
      this._playerActor && this._playerActor.emotion === null;
  }

}

import ObjectsManager   from 'managers/ObjectsManager';
import GameStageManager from 'managers/GameStageManager';

import Goal   from 'objects/Goal';
import Actor  from 'objects/Actor';
import Agents from 'objects/Agents';

export default Game;
<|endoftext|>