<commit_before>/**
 * --------------------------------------------------------------------
 * jQuery tabs plugin
 * Author: Scott Jehl, scott@filamentgroup.com
 * Copyright (c) 2009 Filament Group
 * licensed under MIT (filamentgroup.com/examples/mit-license.txt)
 * --------------------------------------------------------------------
 */

/*
 * Edited to support GOV.UK markup and add acccessibility features
*/

jQuery.fn.tabs = function(settings){
	//configurable options
	var o = $.extend({
    trackState: true, //track tabs in history, url hash, back button, page load
    srcPath: 'jQuery.history.blank.html',
    autoRotate: false,
    alwaysScrollToTop: true,
    selected: null,
    wrapperTag : 'section',
    defaultTab : null,
    containerTag : 'div',
		scrollOnload : false
	},settings);

	var tabFormat = 'tabset',
    checkFormat = function ($tabsNav) {
      var format = tabFormat,
          $navContainer = $tabsNav.closest(o.containerTag);

          if ($navContainer.hasClass('programme-progression')) {
            if ($tabsNav.closest(o.containerTag).css('float') === 'none') {
              format = 'accordion';
            }
          } else { // is transaction start page tabs
            if ($tabsNav.find('li').css('float') === 'none') {
              format = 'accordion';
            }
          }

          // accordions default to all tabs closed, tabsets to open at the 1st
          if (format === 'accordion') {
            if (o.defaultTab === null) {
              o.defaultTab = -1;
            }
          } else {
            if (o.defaultTab === null) {
              o.defaultTab = 0;
            }
          }

          return format;
        };

  var setTabItems = function ($tabsBody, $tabsNav) {
    if (tabFormat === 'accordion') {
      return $tabsBody.find('header.js-heading-tab');
    }

    return $tabsNav.find('li');
  };

	var adapt = function ($tabs, $tabsNav, $tabsBody) {
    var $tabItems = $tabsNav.find('li'),
        $container = $tabsNav.closest(o.containerTag).parent(),
        $relatedArticle,
        $articleHeading,
        $articleInner;

    $.each($tabItems, function (idx) {
      var $tabAnchor = $(this).find('a'),
          tabId = $tabAnchor.attr('href').split('#')[1],
          $shiftLink = $('Return to top of section ↑');

      $relatedArticle = $container.find('#' + tabId);

      // get heading & store
      $articleHeading = $relatedArticle.find('header');

      if (!$articleHeading.length) {
        $articleHeading = $('
');
      } else {
        $articleHeading = $articleHeading.remove();
      }

      $articleHeading
        .addClass('js-heading-tab')
        .removeClass('visuallyhidden')

      $articleHeading.children().html('').append($tabAnchor);

      // get div.inner
      $articleInner = $relatedArticle.find('.inner');

      // if article has no inner div, add one & move the content into it
      if (!$articleInner.length) {
        $articleInner = $('
').html($relatedArticle.html());
      } else {
        $articleInner.addClass('js-tab-pane');
      }

      $articleInner.attr('id', tabId);

      // create a new blank article with the original's inner div
      $relatedArticle.replaceWith($('<' + o.wrapperTag  + ' />').append($articleInner));
      $relatedArticle = $articleInner.parent();
      $relatedArticle.prepend($articleHeading)
        .attr('id', tabId);
      $relatedArticle.addClass('js-tab-container');
      $articleInner.append($shiftLink);
    });

    $tabsNav.closest(o.containerTag).remove();
  };

	return $(this).each(function(){
		//reference to tabs container
		var tabs = $(this);

		//nav is first ul or ol
		var tabsNav = tabs.find('.js-tabs ul, .js-tabs ol');

    // exit early if there isn't anything to click
    if (tabsNav.length === 0) {
      return tabs;
    }

		//body is nav's next sibling
		var tabsBody = $(".js-tab-content");

		var tabIDprefix = 'tab-';

		var tabIDsuffix = '-enhanced';

		tabsBody
			.addClass('tabs-body')
			.attr('aria-live', 'polite');

    // check for mobile and adapt DOM if required
    tabFormat = checkFormat(tabsNav);
    if (tabFormat === 'accordion') {
      adapt(tabs, tabsNav);
    } else {
      //add class to nav, tab body
      tabsNav
        .addClass('tabs-nav')
        .attr('role','tablist');
    }

		//find tab panels, add class and aria
		tabsBody.find('.js-tab-pane').each(function(){
			$(this)
				.addClass('tabs-panel')
				.attr('role','tabpanel')
				.attr('aria-hidden', true)
				.attr('aria-expanded', false)
				.attr('aria-labelledby', tabIDprefix + $(this).attr('id'))
				.attr('id', $(this).attr('id') + tabIDsuffix)
				.hide();
		});

    var tabItems = setTabItems(tabsBody, tabsNav);

		//set role of each tab
		tabItems.find('a').each(function(idx){
      var id = $(this).attr('href').split('#')[1];

			$(this)
				.attr('role','tab')
				.attr('id', tabIDprefix + id)
				.attr('aria-controls', id)
				.attr('aria-flowto', id);
		});

		//generic select tab function
		function selectTab(tab,fromHashChange){
			if(o.trackState && !fromHashChange){
				var anchor = tab.attr('href').split('#')[1];
				$.historyLoad(anchor);
			} else {
				//unselect tabs
				tabItems.find('a')
					.attr('aria-selected', false)
					.attr('tabindex', -1);
            if (tabFormat === 'accordion') {
              tabItems.find('a').closest('.js-heading-tab').removeClass('active');
            } else {
              tabItems.find('a').parent().filter('.active').removeClass('active');
            }
				//set selected tab item
				tab
					.attr('aria-selected', true)
					.attr('tabindex', 0);
        if (tabFormat === 'accordion') {
          tab.closest('.js-heading-tab').addClass('active');
        } else {
					tab.parent().addClass('active');
        }
				//unselect panels
				tabsBody.find('.tabs-panel-selected')
					.attr('aria-hidden',true)
					.attr('aria-expanded', false)
					.removeClass('tabs-panel-selected')
					.hide();

				//select active panel
				var anchor = tab.attr('href').split('#')[1];

				$( "#" + anchor + tabIDsuffix )
					.addClass('tabs-panel-selected')
					.attr('aria-hidden',false)
					.attr('aria-expanded', true)
					.show();

				// set selected index
				o.selected = tabItems.find('a').index(tab);

				// fire tab changed event
				tabs.trigger('tabChanged', anchor);

			}
		}

		//deselect tab function
		function deselectTab(tab){
      tabItems.find('a')
        .attr('aria-selected', false)
        .attr('tabindex', -1);

      tabItems.find('a').closest('.js-heading-tab').removeClass('active');

      //unselect panels
      tabsBody.find('.tabs-panel-selected')
        .attr('aria-hidden',true)
        .attr('aria-expanded', false)
        .removeClass('tabs-panel-selected')
        .hide();
		}

		// keyboard navigation
		tabs.on('keydown', function(event) {
			if (event.keyCode < $.ui.keyCode.PAGE_UP || event.keyCode > $.ui.keyCode.DOWN)
				return;

			var selectedIndex,
			    selectedTabItem;

			switch (event.keyCode) {
				case $.ui.keyCode.RIGHT:
          event.preventDefault();
          selectedIndex = o.selected + 1;
				break;
				case $.ui.keyCode.DOWN:
          selectedIndex = o.selected + 1;
				break;
				case $.ui.keyCode.UP:
          selectedIndex = o.selected - 1;
				break;
				case $.ui.keyCode.LEFT:
          selectedIndex = o.selected - 1;
				break;
				case $.ui.keyCode.END:
          selectedIndex = tabItems.length - 1;
				break;
				case $.ui.keyCode.HOME:
          selectedIndex = 0;
				break;
				case $.ui.keyCode.PAGE_UP:
				if (!event.ctrlKey)
					return;
				selectedIndex = o.selected + 1;
				break;
				case $.ui.keyCode.PAGE_DOWN:
				if (!event.ctrlKey)
					return;
				selectedIndex = o.selected + 1;
				if (!event.ctrlKey)
					return;
				selectedIndex = o.selected - 1;
				break;
			}
			event.preventDefault();
			event.stopPropagation();

			if (selectedIndex !== undefined) {
				selectedIndex = selectedIndex >= tabItems.length ? 0 : selectedIndex < 0 ? tabItems.length - 1 : selectedIndex;

        selectedTabItem = tabItems.find('a').eq(selectedIndex);
        selectedTabItem.focus();
        o.selected = selectedIndex;
			}

			return false;
		});

		//if tabs are rotating, stop them upon user events
		tabs.bind('click keydown focus',function(){
      if(o.autoRotate){ clearInterval(tabRotator); }
		});

		//function to select a tab from the url hash
		function selectTabFromHash(hash, pageLoad){
			var currHash = hash || window.location.hash;
			if(currHash.indexOf("#") == 0){
        currHash = currHash.split("#")[1];
      }
			var hashedTab = tabItems.find('a[href$=#' +  currHash + ']');

      if(hashedTab.size() > 0){
        selectTab(hashedTab,true);
        if(o.scrollOnload && pageLoad){
          window.setTimeout(function(){ $(document).scrollTop(hashedTab.offset().top) }, 0);
        }
      }
      else {
        if (o.defaultTab > -1) {
          selectTab( tabItems.find('a').eq(o.defaultTab), true);
        }
      }
      //return true/false
      return !!hashedTab.size();
		}

		//if state tracking is enabled, set up the callback
		if(o.trackState){ $.historyInit(selectTabFromHash, o.srcPath); }

		//set tab from hash at page load, if no tab hash, select first tab
		selectTabFromHash(null, true);

		tabItems.on('click', 'a', function(){
      if ($(this).closest('.js-heading-tab').hasClass('active')) {
        deselectTab($(this));
      } else {
        selectTab($(this));
      }
			$(this).focus();
			return false;
		});

		if(o.alwaysScrollToTop){
			$(window)[0].scrollTo(0,0);
		}

    // related content box needs to know the top position of the footer
    // this changes when content is split into tabs
    if (typeof GOVUK.stopScrollingAtFooter !== 'undefined') {
      GOVUK.stopScrollingAtFooter.updateFooterTop();
    }
	});
};
<commit_msg>Wrap attribute selector query in quotes<commit_after>/**
 * --------------------------------------------------------------------
 * jQuery tabs plugin
 * Author: Scott Jehl, scott@filamentgroup.com
 * Copyright (c) 2009 Filament Group
 * licensed under MIT (filamentgroup.com/examples/mit-license.txt)
 * --------------------------------------------------------------------
 */

/*
 * Edited to support GOV.UK markup and add acccessibility features
*/

jQuery.fn.tabs = function(settings){
	//configurable options
	var o = $.extend({
    trackState: true, //track tabs in history, url hash, back button, page load
    srcPath: 'jQuery.history.blank.html',
    autoRotate: false,
    alwaysScrollToTop: true,
    selected: null,
    wrapperTag : 'section',
    defaultTab : null,
    containerTag : 'div',
		scrollOnload : false
	},settings);

	var tabFormat = 'tabset',
    checkFormat = function ($tabsNav) {
      var format = tabFormat,
          $navContainer = $tabsNav.closest(o.containerTag);

          if ($navContainer.hasClass('programme-progression')) {
            if ($tabsNav.closest(o.containerTag).css('float') === 'none') {
              format = 'accordion';
            }
          } else { // is transaction start page tabs
            if ($tabsNav.find('li').css('float') === 'none') {
              format = 'accordion';
            }
          }

          // accordions default to all tabs closed, tabsets to open at the 1st
          if (format === 'accordion') {
            if (o.defaultTab === null) {
              o.defaultTab = -1;
            }
          } else {
            if (o.defaultTab === null) {
              o.defaultTab = 0;
            }
          }

          return format;
        };

  var setTabItems = function ($tabsBody, $tabsNav) {
    if (tabFormat === 'accordion') {
      return $tabsBody.find('header.js-heading-tab');
    }

    return $tabsNav.find('li');
  };

	var adapt = function ($tabs, $tabsNav, $tabsBody) {
    var $tabItems = $tabsNav.find('li'),
        $container = $tabsNav.closest(o.containerTag).parent(),
        $relatedArticle,
        $articleHeading,
        $articleInner;

    $.each($tabItems, function (idx) {
      var $tabAnchor = $(this).find('a'),
          tabId = $tabAnchor.attr('href').split('#')[1],
          $shiftLink = $('Return to top of section ↑');

      $relatedArticle = $container.find('#' + tabId);

      // get heading & store
      $articleHeading = $relatedArticle.find('header');

      if (!$articleHeading.length) {
        $articleHeading = $('
');
      } else {
        $articleHeading = $articleHeading.remove();
      }

      $articleHeading
        .addClass('js-heading-tab')
        .removeClass('visuallyhidden')

      $articleHeading.children().html('').append($tabAnchor);

      // get div.inner
      $articleInner = $relatedArticle.find('.inner');

      // if article has no inner div, add one & move the content into it
      if (!$articleInner.length) {
        $articleInner = $('
').html($relatedArticle.html());
      } else {
        $articleInner.addClass('js-tab-pane');
      }

      $articleInner.attr('id', tabId);

      // create a new blank article with the original's inner div
      $relatedArticle.replaceWith($('<' + o.wrapperTag  + ' />').append($articleInner));
      $relatedArticle = $articleInner.parent();
      $relatedArticle.prepend($articleHeading)
        .attr('id', tabId);
      $relatedArticle.addClass('js-tab-container');
      $articleInner.append($shiftLink);
    });

    $tabsNav.closest(o.containerTag).remove();
  };

	return $(this).each(function(){
		//reference to tabs container
		var tabs = $(this);

		//nav is first ul or ol
		var tabsNav = tabs.find('.js-tabs ul, .js-tabs ol');

    // exit early if there isn't anything to click
    if (tabsNav.length === 0) {
      return tabs;
    }

		//body is nav's next sibling
		var tabsBody = $(".js-tab-content");

		var tabIDprefix = 'tab-';

		var tabIDsuffix = '-enhanced';

		tabsBody
			.addClass('tabs-body')
			.attr('aria-live', 'polite');

    // check for mobile and adapt DOM if required
    tabFormat = checkFormat(tabsNav);
    if (tabFormat === 'accordion') {
      adapt(tabs, tabsNav);
    } else {
      //add class to nav, tab body
      tabsNav
        .addClass('tabs-nav')
        .attr('role','tablist');
    }

		//find tab panels, add class and aria
		tabsBody.find('.js-tab-pane').each(function(){
			$(this)
				.addClass('tabs-panel')
				.attr('role','tabpanel')
				.attr('aria-hidden', true)
				.attr('aria-expanded', false)
				.attr('aria-labelledby', tabIDprefix + $(this).attr('id'))
				.attr('id', $(this).attr('id') + tabIDsuffix)
				.hide();
		});

    var tabItems = setTabItems(tabsBody, tabsNav);

		//set role of each tab
		tabItems.find('a').each(function(idx){
      var id = $(this).attr('href').split('#')[1];

			$(this)
				.attr('role','tab')
				.attr('id', tabIDprefix + id)
				.attr('aria-controls', id)
				.attr('aria-flowto', id);
		});

		//generic select tab function
		function selectTab(tab,fromHashChange){
			if(o.trackState && !fromHashChange){
				var anchor = tab.attr('href').split('#')[1];
				$.historyLoad(anchor);
			} else {
				//unselect tabs
				tabItems.find('a')
					.attr('aria-selected', false)
					.attr('tabindex', -1);
            if (tabFormat === 'accordion') {
              tabItems.find('a').closest('.js-heading-tab').removeClass('active');
            } else {
              tabItems.find('a').parent().filter('.active').removeClass('active');
            }
				//set selected tab item
				tab
					.attr('aria-selected', true)
					.attr('tabindex', 0);
        if (tabFormat === 'accordion') {
          tab.closest('.js-heading-tab').addClass('active');
        } else {
					tab.parent().addClass('active');
        }
				//unselect panels
				tabsBody.find('.tabs-panel-selected')
					.attr('aria-hidden',true)
					.attr('aria-expanded', false)
					.removeClass('tabs-panel-selected')
					.hide();

				//select active panel
				var anchor = tab.attr('href').split('#')[1];

				$( "#" + anchor + tabIDsuffix )
					.addClass('tabs-panel-selected')
					.attr('aria-hidden',false)
					.attr('aria-expanded', true)
					.show();

				// set selected index
				o.selected = tabItems.find('a').index(tab);

				// fire tab changed event
				tabs.trigger('tabChanged', anchor);

			}
		}

		//deselect tab function
		function deselectTab(tab){
      tabItems.find('a')
        .attr('aria-selected', false)
        .attr('tabindex', -1);

      tabItems.find('a').closest('.js-heading-tab').removeClass('active');

      //unselect panels
      tabsBody.find('.tabs-panel-selected')
        .attr('aria-hidden',true)
        .attr('aria-expanded', false)
        .removeClass('tabs-panel-selected')
        .hide();
		}

		// keyboard navigation
		tabs.on('keydown', function(event) {
			if (event.keyCode < $.ui.keyCode.PAGE_UP || event.keyCode > $.ui.keyCode.DOWN)
				return;

			var selectedIndex,
			    selectedTabItem;

			switch (event.keyCode) {
				case $.ui.keyCode.RIGHT:
          event.preventDefault();
          selectedIndex = o.selected + 1;
				break;
				case $.ui.keyCode.DOWN:
          selectedIndex = o.selected + 1;
				break;
				case $.ui.keyCode.UP:
          selectedIndex = o.selected - 1;
				break;
				case $.ui.keyCode.LEFT:
          selectedIndex = o.selected - 1;
				break;
				case $.ui.keyCode.END:
          selectedIndex = tabItems.length - 1;
				break;
				case $.ui.keyCode.HOME:
          selectedIndex = 0;
				break;
				case $.ui.keyCode.PAGE_UP:
				if (!event.ctrlKey)
					return;
				selectedIndex = o.selected + 1;
				break;
				case $.ui.keyCode.PAGE_DOWN:
				if (!event.ctrlKey)
					return;
				selectedIndex = o.selected + 1;
				if (!event.ctrlKey)
					return;
				selectedIndex = o.selected - 1;
				break;
			}
			event.preventDefault();
			event.stopPropagation();

			if (selectedIndex !== undefined) {
				selectedIndex = selectedIndex >= tabItems.length ? 0 : selectedIndex < 0 ? tabItems.length - 1 : selectedIndex;

        selectedTabItem = tabItems.find('a').eq(selectedIndex);
        selectedTabItem.focus();
        o.selected = selectedIndex;
			}

			return false;
		});

		//if tabs are rotating, stop them upon user events
		tabs.bind('click keydown focus',function(){
      if(o.autoRotate){ clearInterval(tabRotator); }
		});

		//function to select a tab from the url hash
		function selectTabFromHash(hash, pageLoad){
			var currHash = hash || window.location.hash;
			if(currHash.indexOf("#") == 0){
        currHash = currHash.split("#")[1];
      }
			var hashedTab = tabItems.find('a[href$="#' +  currHash + '"]');

      if(hashedTab.size() > 0){
        selectTab(hashedTab,true);
        if(o.scrollOnload && pageLoad){
          window.setTimeout(function(){ $(document).scrollTop(hashedTab.offset().top) }, 0);
        }
      }
      else {
        if (o.defaultTab > -1) {
          selectTab( tabItems.find('a').eq(o.defaultTab), true);
        }
      }
      //return true/false
      return !!hashedTab.size();
		}

		//if state tracking is enabled, set up the callback
		if(o.trackState){ $.historyInit(selectTabFromHash, o.srcPath); }

		//set tab from hash at page load, if no tab hash, select first tab
		selectTabFromHash(null, true);

		tabItems.on('click', 'a', function(){
      if ($(this).closest('.js-heading-tab').hasClass('active')) {
        deselectTab($(this));
      } else {
        selectTab($(this));
      }
			$(this).focus();
			return false;
		});

		if(o.alwaysScrollToTop){
			$(window)[0].scrollTo(0,0);
		}

    // related content box needs to know the top position of the footer
    // this changes when content is split into tabs
    if (typeof GOVUK.stopScrollingAtFooter !== 'undefined') {
      GOVUK.stopScrollingAtFooter.updateFooterTop();
    }
	});
};
<|endoftext|>


<commit_before>define({
    "_current" : "en",
    "user": "user",
    "username": "username",
    "firstname": "firstname",
    "lastname": "lastname",
    "my-sheets": "my sheets",
    "overview-of-sheets": "overview of sheets",
    "search": "search",
    "home" : "home",
    "add" : "add",
    "cancel" : "cancel",
    "memo" : "memo",
    "settings": "settings",
    "you" : "You",
    "take" : "take",
    "close" : "close",
    "send" : "send",
    "delete" : "delete",
    "confirm" : "confirm",
    "diff" : "diff",
    "reopen": "re-open",
    "ask-confirm" : "Are you sure",
    "ask-confirm-choice" : "Are you sure to choose",
    "to" : "to",
    "the" : "the",
    "at" : "at",
    "reason" : "reason",
    "checkin" : "check",
    "config" : {
      "take-validation": "Ask confirmation to take a ticket",
      "give-validation": "Ask confirmation to give a ticket",
      "reopen-validation": "Ask confirmation to re-open a ticket",
      "addPathology-validation" : "Ask confirmation to add a pathology",
      "addOrigin-validation" : "Ask confirmation to change origin of a ticket",
      "changePrimaryAffection-validation" : "Ask confirmation to change primary affection",
      "changeInformation-validation" : "Ask confirmation to change information",
      "delete-validation" : "Ask confirmation to delete a ticket",
      "resetCredConfig" : "Log out",
      "resetServerConfig" : "Reset Server Config",
      "choose-lang" : "Choose a language",
      "clearLocalDB" : "Clear Local DB"
    },
    "log" : {
      "add-path" : "add the disease",
      "set-origin" : "set origin to",
      "change-primary" : "set primary disease from",
      "reopen-fiche" : "re-open ticket",
      "cancel-del": "cancel deletion of ticket",
      "del-fiche" : "delete ticket",
      "close-fiche" : "close ticket",
      "create-fiche" : "create ticket",
      "take-fiche-from" : "take ticket from",
      "give-fiche-to" : "give ticket to",
      "add-checkin" : "has checked this patient",
      "has-updated-information" : "has updated informations",
      "old-prop" : "old owner"
    },
    "alert" : {
      "scan-fail":"Scanning of QRCode failed",
      "incorrect-format":"Incorrect QRCode format",
      "no-primaryAffection":"No primaryAffection choosen please select one before closing"
    },
    "fiche" : {
      "owner" : "owner",
      "birthdate" : "Birthdate",
      "birthdate-error-mess" : "Please enter a valid date",
      "sex" : "Sex",
      "origin" : "Origin",
      "team" : "Team",
      "history" : "history",
      "diseases" : "diseases",
      "add-path" : "Add a disease",
      "give-ticket" : "Define ticket owner",
      "add-origin" : "Add origin to ticket",
      "update-information" : "Update informations",
      "please-enter-informations" : "Please fill in those informations",
      "seen-by-doctor" : "Seen by doctor",
      "cancel-del" : "cancel deletion",
      "gender" : {
        "female" : "female",
        "male" : "male"
      },
      "pathologys" : {
        "unconscious" : "Unconscious",
        "cardio-respiratory-stop" : "Cardio Respiratory Stop",
        "little-care" : "Little Care",
        "bleeding" : "Bleeding",
        "difficulty-breathing" : "Difficulty Breathing",
        "malaise" : "Malaise",
        "trauma" : "Trauma",
        "medical-consultation" : "Medical Consultation",
      },
      "origins" : {
        "spontaneous" : "Spontaneous",
        "stretcher" : "Stretcher",
        "vpsp" : "VPSP",
        "with-witness" : "With witness",
        "with-security" : "With security",
      },
      "outputs" : {
        "left-in-place" :"Left in place",
        "simple" : "Simple",
        "monitoring-and-single-output" : "Monitoring and single output",
        "firemen-evacuation" : "Firemen evacuation",
        "evacuation" : "Evacuation",
      }
    }
});
<commit_msg>Update base.js<commit_after>define({
    "_current" : "en",
    "user": "user",
    "username": "username",
    "firstname": "firstname",
    "lastname": "lastname",
    "my-sheets": "my sheets",
    "overview-of-sheets": "overview of sheets",
    "search": "search",
    "home" : "home",
    "add" : "add",
    "cancel" : "cancel",
    "memo" : "memo",
    "settings": "settings",
    "you" : "You",
    "take" : "take",
    "close" : "close",
    "send" : "send",
    "delete" : "delete",
    "confirm" : "confirm",
    "diff" : "diff",
    "reopen": "re-open",
    "ask-confirm" : "Are you sure",
    "ask-confirm-choice" : "Are you sure to choose",
    "to" : "to",
    "the" : "the",
    "at" : "at",
    "reason" : "reason",
    "checkin" : "check",
    "config" : {
      "take-validation": "Ask confirmation to take a ticket",
      "give-validation": "Ask confirmation to give a ticket",
      "reopen-validation": "Ask confirmation to re-open a ticket",
      "addPathology-validation" : "Ask confirmation to add a pathology",
      "addOrigin-validation" : "Ask confirmation to change origin of a ticket",
      "changePrimaryAffection-validation" : "Ask confirmation to change primary affection",
      "changeInformation-validation" : "Ask confirmation to change information",
      "delete-validation" : "Ask confirmation to delete a ticket",
      "resetCredConfig" : "Log out",
      "resetServerConfig" : "Reset Server Config",
      "choose-lang" : "Choose a language",
      "clearLocalDB" : "Clear Local DB"
    },
    "log" : {
      "add-path" : "add the disease",
      "set-origin" : "set origin to",
      "change-primary" : "set primary disease from",
      "reopen-fiche" : "re-open ticket",
      "cancel-del": "cancel deletion of ticket",
      "del-fiche" : "delete ticket",
      "close-fiche" : "close ticket",
      "create-fiche" : "create ticket",
      "take-fiche-from" : "take ticket from",
      "give-fiche-to" : "give ticket to",
      "add-checkin" : "has checked this patient",
      "has-updated-information" : "has updated informations",
      "old-prop" : "old owner",
      "auto-merge" : "Conflict detected locally and merged !"
    },
    "alert" : {
      "scan-fail":"Scanning of QRCode failed",
      "incorrect-format":"Incorrect QRCode format",
      "no-primaryAffection":"No primaryAffection choosen please select one before closing"
    },
    "fiche" : {
      "owner" : "owner",
      "birthdate" : "Birthdate",
      "birthdate-error-mess" : "Please enter a valid date",
      "sex" : "Sex",
      "origin" : "Origin",
      "team" : "Team",
      "history" : "history",
      "diseases" : "diseases",
      "add-path" : "Add a disease",
      "give-ticket" : "Define ticket owner",
      "add-origin" : "Add origin to ticket",
      "update-information" : "Update informations",
      "please-enter-informations" : "Please fill in those informations",
      "seen-by-doctor" : "Seen by doctor",
      "cancel-del" : "cancel deletion",
      "gender" : {
        "female" : "female",
        "male" : "male"
      },
      "pathologys" : {
        "unconscious" : "Unconscious",
        "cardio-respiratory-stop" : "Cardio Respiratory Stop",
        "little-care" : "Little Care",
        "bleeding" : "Bleeding",
        "difficulty-breathing" : "Difficulty Breathing",
        "malaise" : "Malaise",
        "trauma" : "Trauma",
        "medical-consultation" : "Medical Consultation",
      },
      "origins" : {
        "spontaneous" : "Spontaneous",
        "stretcher" : "Stretcher",
        "vpsp" : "VPSP",
        "with-witness" : "With witness",
        "with-security" : "With security",
      },
      "outputs" : {
        "left-in-place" :"Left in place",
        "simple" : "Simple",
        "monitoring-and-single-output" : "Monitoring and single output",
        "firemen-evacuation" : "Firemen evacuation",
        "evacuation" : "Evacuation",
      }
    }
});
<|endoftext|>


<commit_before>$(document).ready(function() {
    // Code blocks highlighting
    $('pre code').each(function(i, block) {
        // Remove newline from CloudFlare's e-mail protection script
        $(this).find('script').each(function () {
            $(this).text($(this).text().trim());
        });

        // Add line numbers, unless it's bash or doesn't want to be highlighted
        if (!$(this).is('.language-bash') && !$(this).hasClass('nohighlight')) {
            var lines = $(this).text().trim().split('\n').length;
            var $numbering = $('
').addClass('pre-numbering');
            $(this).parent().addClass('has-numbering').prepend($numbering);

            for (var i = 1; i <= lines; i++){
                $numbering.append($('
').text(i));
            }
        }

        $(this).parent().addClass('highlighted');

        if (!$(this).hasClass('nohighlight')) {
          // Highlight code block
          hljs.highlightBlock(block);
        } else {
          // Fake highlighting for stylesheet things
          $(this).addClass('hljs');
        }
    });

    // Anchor headings
    $('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]').each(function() {
        $(this).wrapInner('');
    });

    // Update javascript variable currentSection
    var docElements = $('h1[id], h2[id]', '.docs');

    var currentSection = null;
    if (location.hash) {
      currentSection = location.hash;
    } else {
      currentSection = docElements[0];
    };
    $(document).on('scroll', function (event) {
        // Check to see what is on screen right now
        for (var i = 0; i < docElements.length; i++) {
            // Checks if the passed element is visible on the screen after scrolling
            // Source: http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling
            var docViewTop = $(window).scrollTop();
            var docViewBottom = docViewTop + $(window).height();

            var elemTop = $(docElements[i]).offset().top;
            var elemBottom = elemTop + $(docElements[i]).height();

            // Sets currentSection if element is top most visible element
            if ((elemTop <= docViewTop)) {
                currentSection = docElements[i];
            // Sets currentSection if element is more than 1/3 from the top
            } else if (elemTop <= (docViewTop + ($(window).height() / 3) )) {
                currentSection = docElements[i];
            };
        };
    });

    // Url hash selector. Only in docs class to avoid nav conflicts
    $(document).on('scroll', function (event) {
        // Changes browser hash without adding to history
        history.replaceState(undefined, undefined, location.href.split("#")[0]+"#"+currentSection.id);
    });

    // Sidebar
    var $headings = $('h1');
    if ($headings.length > 1) {
        var $sidebar = $('

');
        $headings.each(function () {
            $sidebar.append('
'+$(this).text()+'
');
            var $subHeadings = $(this).nextUntil('h1', 'h2');
            if ($subHeadings.length > 0) {
                var $subMenu = $('

');
                $subHeadings.each(function () {
                    $subMenu.append('
'+$(this).text()+'
');
                });
                $sidebar.append($subMenu);
            }
        });
        $sidebar.prependTo('#content-container');

        var $sidebarItems = $sidebar.children('li');

        var navHeight = $('nav.nav:first').height();
        var footerScrollTop = $('footer:last').offset().top;
        var prevTarget = 0,
            nextTarget = 0;
        $(window).scroll(function () {
            var scrollTop = $(this).scrollTop();

            $sidebar.toggleClass('nav-visible', (scrollTop < navHeight));
            $sidebar.toggleClass('footer-visible', (scrollTop + $(window).height() > footerScrollTop));

            $('ul.sidebar .active').removeClass('active');
            var $currentLink = $('ul.sidebar a[href$="#'+currentSection.id+'"]')
            if ($currentLink.parent().parent().is('.sidebar')) {
                $currentLink.parent().addClass('active');
            } else {
              ($currentLink.parent().parent().prev('li').addClass('active'));
            };
        });
        $(window).scroll(); // Trigger event
    }
});
<commit_msg>Don't replace location.hash on every scroll; not only is this inelegant, but when you replaceState some browsers, including Chrome, re-request favicon.ico. Instead, only replace when it's actually required to, so we don't hit favicon.ico on every scroll.<commit_after>$(document).ready(function() {
    // Code blocks highlighting
    $('pre code').each(function(i, block) {
        // Remove newline from CloudFlare's e-mail protection script
        $(this).find('script').each(function () {
            $(this).text($(this).text().trim());
        });

        // Add line numbers, unless it's bash or doesn't want to be highlighted
        if (!$(this).is('.language-bash') && !$(this).hasClass('nohighlight')) {
            var lines = $(this).text().trim().split('\n').length;
            var $numbering = $('
').addClass('pre-numbering');
            $(this).parent().addClass('has-numbering').prepend($numbering);

            for (var i = 1; i <= lines; i++){
                $numbering.append($('
').text(i));
            }
        }

        $(this).parent().addClass('highlighted');

        if (!$(this).hasClass('nohighlight')) {
          // Highlight code block
          hljs.highlightBlock(block);
        } else {
          // Fake highlighting for stylesheet things
          $(this).addClass('hljs');
        }
    });

    // Anchor headings
    $('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]').each(function() {
        $(this).wrapInner('');
    });

    // Update javascript variable currentSection
    var docElements = $('h1[id], h2[id]', '.docs');

    var currentSection = null;
    if (location.hash) {
      currentSection = location.hash;
    } else {
      currentSection = docElements[0];
    };
    $(document).on('scroll', function (event) {
        // Check to see what is on screen right now
        for (var i = 0; i < docElements.length; i++) {
            // Checks if the passed element is visible on the screen after scrolling
            // Source: http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling
            var docViewTop = $(window).scrollTop();
            var docViewBottom = docViewTop + $(window).height();

            var elemTop = $(docElements[i]).offset().top;
            var elemBottom = elemTop + $(docElements[i]).height();

            // Sets currentSection if element is top most visible element
            if ((elemTop <= docViewTop)) {
                currentSection = docElements[i];
            // Sets currentSection if element is more than 1/3 from the top
            } else if (elemTop <= (docViewTop + ($(window).height() / 3) )) {
                currentSection = docElements[i];
            };
        };
    });

    // Url hash selector. Only in docs class to avoid nav conflicts
    $(document).on('scroll', function (event) {
        // Changes browser hash without adding to history
        if (currentSection.id !== location.hash.substr(1)) {
            history.replaceState(undefined, undefined, location.href.split("#")[0]+"#"+currentSection.id);
        }
    });

    // Sidebar
    var $headings = $('h1');
    if ($headings.length > 1) {
        var $sidebar = $('

');
        $headings.each(function () {
            $sidebar.append('
'+$(this).text()+'
');
            var $subHeadings = $(this).nextUntil('h1', 'h2');
            if ($subHeadings.length > 0) {
                var $subMenu = $('

');
                $subHeadings.each(function () {
                    $subMenu.append('
'+$(this).text()+'
');
                });
                $sidebar.append($subMenu);
            }
        });
        $sidebar.prependTo('#content-container');

        var $sidebarItems = $sidebar.children('li');

        var navHeight = $('nav.nav:first').height();
        var footerScrollTop = $('footer:last').offset().top;
        var prevTarget = 0,
            nextTarget = 0;
        $(window).scroll(function () {
            var scrollTop = $(this).scrollTop();

            $sidebar.toggleClass('nav-visible', (scrollTop < navHeight));
            $sidebar.toggleClass('footer-visible', (scrollTop + $(window).height() > footerScrollTop));

            $('ul.sidebar .active').removeClass('active');
            var $currentLink = $('ul.sidebar a[href$="#'+currentSection.id+'"]')
            if ($currentLink.parent().parent().is('.sidebar')) {
                $currentLink.parent().addClass('active');
            } else {
              ($currentLink.parent().parent().prev('li').addClass('active'));
            };
        });
        $(window).scroll(); // Trigger event
    }
});
<|endoftext|>


<commit_before>Teikei.module('User', function(User, App, Backbone, Marionette, $, _) {

  User.Model = Backbone.Model.extend({

    initialize: function() {
      if (this.tokenIsPresent()) {
        this.setUpHeader();
        this.loadSessionFromCookie();
      }
    },

    signIn: function(signInData, callback) {
      // clear data that may exist from a former sign up:
      this.clear({silent: true});

      return this.save(signInData, {
        url: "/users/sign_in",
        success: callback.success,
        error: callback.error
      });
    },

    parse: function(data) {
      // Sign in: The `data` contains both a `user`-object and a `auth_token`.
      if ('user' in data && 'auth_token' in data) {
        this.setSessionInCookie(data.user.id, data.user.name, data.auth_token);
        this.setUpHeader();
        return data.user;
      }

      // Sign up: The `data` contains only the properties of the `user`-object.
      return data;
    },

    tokenIsPresent: function() {
      return $.cookie("auth_token") !== undefined;
    },

    signUp: function(signUpData, callback) {
      return this.save(signUpData, {
        url: "/api/v1/users",
        success: callback.success,
        error: callback.error
      });
    },

    signOut: function(callback) {
      return this.destroy({
        url: "/users/sign_out",
        success: callback.success,
        error: callback.error
      });
    },

    destroy: function() {
      this.unsetSessionInCookie();
      return Backbone.Model.prototype.destroy.apply(this, arguments);
    },

    setSessionInCookie: function(userId, userName, authToken) {
      $.cookie("user_id", userId);
      $.cookie("user_name", userName);
      $.cookie("auth_token", authToken);
    },

    unsetSessionInCookie: function() {
      $.removeCookie("user_id");
      $.removeCookie("user_name");
      $.removeCookie("auth_token");
    },

    loadSessionFromCookie: function() {
      this.set("id", parseInt($.cookie('user_id'), 10));
      this.set("name", $.cookie('user_name'));
    },

    setUpHeader: function() {
      var authToken = $.cookie("auth_token");
      if (authToken === undefined) {
        throw "The cookie is undefined. Invoke `setAuthTokenInCookie` before.";
      }
      var headerData = { auth_token: authToken };
      $.ajaxSetup({ headers: headerData });
    },

    resetHeader: function() {
      // TODO Remove the auth_token onSignOut.
    }

  });
});
<commit_msg>Use conversion argument provided by jQuery Cookie Plugin.<commit_after>Teikei.module('User', function(User, App, Backbone, Marionette, $, _) {

  User.Model = Backbone.Model.extend({

    initialize: function() {
      if (this.tokenIsPresent()) {
        this.setUpHeader();
        this.loadSessionFromCookie();
      }
    },

    signIn: function(signInData, callback) {
      // clear data that may exist from a former sign up:
      this.clear({silent: true});

      return this.save(signInData, {
        url: "/users/sign_in",
        success: callback.success,
        error: callback.error
      });
    },

    parse: function(data) {
      // Sign in: The `data` contains both a `user`-object and a `auth_token`.
      if ('user' in data && 'auth_token' in data) {
        this.setSessionInCookie(data.user.id, data.user.name, data.auth_token);
        this.setUpHeader();
        return data.user;
      }

      // Sign up: The `data` contains only the properties of the `user`-object.
      return data;
    },

    tokenIsPresent: function() {
      return $.cookie("auth_token") !== undefined;
    },

    signUp: function(signUpData, callback) {
      return this.save(signUpData, {
        url: "/api/v1/users",
        success: callback.success,
        error: callback.error
      });
    },

    signOut: function(callback) {
      return this.destroy({
        url: "/users/sign_out",
        success: callback.success,
        error: callback.error
      });
    },

    destroy: function() {
      this.unsetSessionInCookie();
      return Backbone.Model.prototype.destroy.apply(this, arguments);
    },

    setSessionInCookie: function(userId, userName, authToken) {
      $.cookie("user_id", userId);
      $.cookie("user_name", userName);
      $.cookie("auth_token", authToken);
    },

    unsetSessionInCookie: function() {
      $.removeCookie("user_id");
      $.removeCookie("user_name");
      $.removeCookie("auth_token");
    },

    loadSessionFromCookie: function() {
      this.set("id", $.cookie('user_id', Number));
      this.set("name", $.cookie('user_name'));
    },

    setUpHeader: function() {
      var authToken = $.cookie("auth_token");
      if (authToken === undefined) {
        throw "The cookie is undefined. Invoke `setAuthTokenInCookie` before.";
      }
      var headerData = { auth_token: authToken };
      $.ajaxSetup({ headers: headerData });
    },

    resetHeader: function() {
      // TODO Remove the auth_token onSignOut.
    }

  });
});
<|endoftext|>


<commit_before><commit_msg>Use let instead of var<commit_after><|endoftext|>


<commit_before>$(document).ready(function() {
  $("a.load_reviews").on("click", function(e){
 //Send AJAX LOW-LEVEL get request
    $.ajax({
      method: "GET",
      url: this.href
    }).done(function(response) {
 //get response
      $("div.reviews").html(response)
 //Load data into html
    });

    e.preventDefault();
  })
})
<commit_msg>move e.preventDefault(); up top<commit_after>$(document).ready(function() {
  $("a.load_reviews").on("click", function(e){
    e.preventDefault();
 //Send AJAX LOW-LEVEL get request
    $.ajax({
      method: "GET",
      url: this.href
    }).done(function(response) {
 //get response
      $("div.reviews").html(response)
 //Load data into html
    });
  });
});
<|endoftext|>


<commit_before>const fs = require('fs');
const fsextra = require('fs-extra');
const path = require('path');
const util = require('util');
const logger = require('winston');

const sanitizeHtml = require('sanitize-html');

const request = require('request-promise');
const toml = require('toml');
const tomlify = require('tomlify-j0.4');
const blackfriday = require('./blackfriday.js');

const del = require('delete');
const exec = require('sync-exec');

const fsPathCode = './citra-games-wiki/games';
const fsPathWiki = './citra-games-wiki.wiki';
const fsPathHugoContent = '../../site/content/game';
const fsPathHugoBoxart = '../../site/static/images/game/boxart';
const fsPathHugoIcon = '../../site/static/images/game/icons';
const fsPathHugoScreenshots = '../../site/static/images/screenshots0';
const fsPathHugoSavefiles = '../../site/static/savefiles/';

function gitPull(directory, repository) {
  if (fs.existsSync(directory)) {
      logger.info(`Fetching latest from Github : ${directory}`);
      logger.info(`git --git-dir=${directory} pull`);
      exec(`git --git-dir=${directory} pull`);
  } else {
      logger.info(`Cloning repository from Github : ${directory}`);
      logger.info(`git clone ${repository}`);
      exec(`git clone ${repository}`);
  }
}

function getDirectories (srcpath) {
  return fs.readdirSync(srcpath)
    .filter(file => fs.lstatSync(path.join(srcpath, file)).isDirectory())
}

async function getGithubIssues() {
  var results = [];

  // Only loop through the first x pages to prevent API limiting.
  for (var page = 0; page <= 15; page++) {
    let options = {
      url: `https://api.github.com/repos/citra-emu/citra/issues?per_page=99&page=${page}`,
      headers: { 'User-Agent': 'citrabot' }
    };

    logger.verbose(`Requesting Github Issue Page ${page}.`);
    var body = await request.get(options);
    var obj = JSON.parse(body);

    if (obj == null || obj.length == 0) {
      logger.verbose(`No more Github issues found -- on page ${page}.`);
      break;
    } else {
      results = results.concat(obj);
    }
  }

  return results;
}

async function getTestcases() {
  let options = {
    url: 'https://api.citra-emu.org/telemetry/testcase/',
    headers: { 'User-Agent': 'citrabot' },
  };

  var body = await request.get(options);
  return JSON.parse(body).map(x => {
    return {
      id: x.id,
      title: x.title,
      compatibility: x.compatibility.toString(),
      date: x.date,
      version: x.version,
      buildName: x.buildName,
      buildDate: x.buildDate,
      cpu: x.cpu,
      gpu: x.gpu,
      os: x.os,
      author: x.author
    }
  });
}

// Fetch game information stored in Github repository.
gitPull('./citra-games-wiki', 'https://github.com/citra-emu/citra-games-wiki.git');

// Fetch game articles stored in Github wiki.
gitPull('./citra-games-wiki.wiki', 'https://github.com/citra-emu/citra-games-wiki.wiki.git');

// Fetch all issues from Github.
var githubIssues = [];
var wikiEntries = {};
var testcases = [];

async function setup() {
  githubIssues = await getGithubIssues();
  logger.info(`Imported ${githubIssues.length} issues from Github.`);

  testcases = await getTestcases();
  logger.info(`Obtained ${testcases.length} testcases from Telemetry API.`);
};

setup().then(function() {
  // Make sure the output directories in Hugo exist.
  [fsPathHugoContent, fsPathHugoBoxart, fsPathHugoIcon, fsPathHugoSavefiles, fsPathHugoScreenshots].forEach(function (path) {
    if (fs.existsSync(path) == false) {
        logger.info(`Creating Hugo output directory: ${path}`);
        fs.mkdirSync(path);
    }
  });
})
.then(function() {
  // Transform wiki entries to lowercase
  const files = fs.readdirSync(fsPathWiki);

  logger.info(`Generating wiki database...`);
  files.forEach((file) => {
      wikiEntries[file.toLowerCase()] = file;
  });

  // Loop through each game and process it.
  getDirectories(fsPathCode).forEach(function(game) {
    processGame(game);
  });
})
.catch(function(err) {
  logger.error(err);
});

function processGame(game) {
  try {
    if (game == '.git' || game == '_validation') { return; }

    logger.info(`Processing game: ${game}`);

    // Copy the boxart for the game.
    fsextra.copySync(`${fsPathCode}/${game}/boxart.png`, `${fsPathHugoBoxart}/${game}.png`);

    // Copy the icon for the game.
    fsextra.copySync(`${fsPathCode}/${game}/icon.png`, `${fsPathHugoIcon}/${game}.png`);

    var model = toml.parse(fs.readFileSync(`${fsPathCode}/${game}/game.dat`, 'utf8'));
    let currentDate = new Date();
    model.date = `${currentDate.toISOString()}`;

    // Look up all testcases associated with the Title IDs.
    let releases = model.releases.map(y => y.title);
    let foundTestcases = testcases.filter(x => {
      return releases.includes(x.title);
    });

    // If no testcases exist in the toml file, create a blank array.
    if (!model.testcases) {
      model.testcases = [];
    }

    logger.info(`Found ${foundTestcases.length} testcases from telemetry, found ${model.testcases.length} in toml file.`);

    model.testcases = model.testcases.concat(foundTestcases);

    // Sort the testcases from most recent to least recent.
    model.testcases.sort(function(a, b){
      // Turn your strings into dates, and then subtract them
      // to get a value that is either negative, positive, or zero.
      return new Date(b.date) - new Date(a.date);
    });

    // SHORTCUTS BLOCK
    // Parse testcase information out of the dat to reinject as shortcut values.
    if (model.testcases == null || model.testcases.length == 0) {
      model.compatibility = "99";
      model.testcase_date = "2000-01-01";
    } else {
      let recent = model.testcases[0];
      model.compatibility = recent.compatibility;
      model.testcase_date = recent.date;
    }

    const toTrim = ["the", "a", "an"];

    let trimmedTitle = model.title.toLowerCase();
    toTrim.forEach(trim => {
        if (trimmedTitle.startsWith(trim + " ")) {
            trimmedTitle = trimmedTitle.substr(trim.length + 1);
        }
    });

    let section_id = `${trimmedTitle[0]}`;
    if (!section_id.match(/[a-z]+/)) {
        section_id = "#";
    }

    model.section_id = section_id;
    // END SHORTCUTS BLOCK

    // SAVEFILE BLOCK
    var fsPathCodeSavefilesGame = `${fsPathCode}/${game}/savefiles/`;
    var fsPathHugoSavefilesGame = `${fsPathHugoSavefiles}/${game}/`;
    if (fs.existsSync(fsPathCodeSavefilesGame)) {
      // Create the savefile directory for the game.
      if (fs.existsSync(fsPathHugoSavefilesGame) == false) {
          fs.mkdirSync(fsPathHugoSavefilesGame);
      }

      // Copy all savefiles into the output folder, and read their data.
      model.savefiles = [];
      fs.readdirSync(fsPathCodeSavefilesGame).forEach(file => {
        if (path.extname(file) == '.zip') {
          fsextra.copySync(`${fsPathCodeSavefilesGame}/${file}`, `${fsPathHugoSavefilesGame}/${file}`);
        } else if (path.extname(file) == '.dat') {
          // Read the data file into an object.
          let savefile = toml.parse(fs.readFileSync(`${fsPathCodeSavefilesGame}/${file}`, 'utf8'));

          let stats = fs.statSync(`${fsPathCodeSavefilesGame}/${file}`);

          // Store the contents of the file in memory for adding it into the markdown later.
          model.savefiles.push({
            date: new Date(util.inspect(stats.mtime)),
            filename: file.replace('.dat', '.zip'),
            title: savefile.title,
            description: savefile.description,
            author: savefile.author,
            title_id: savefile.title_id
          });
        }
      });
      // Finished copying all savefiles into the output folder, and reading their data.
    }
    // END SAVEFILE BLOCK

    // GITHUB ISSUES BLOCK
    model.issues = [];
    model.closed_issues = [];

    if (model.github_issues != null && model.github_issues.length > 0) {
      model.github_issues.forEach(function(number) {
        let issue = githubIssues.find(x => x.number == number);
        if (issue == null) {
          model.closed_issues.push(number);
        } else {
          model.issues.push({
            number: issue.number.toString(),
            title: issue.title,
            state: issue.state,
            created_at: issue.created_at,
            updated_at: issue.updated_at,
            labels: issue.labels.map(function(x) { return { name: x.name, color: x.color } })
          });
        }
      });

      github_issues = null;
    }
    // END GITHUB ISSUES BLOCK

    // Copy the screenshots for the game.
    let fsPathScreenshotInputGame = `${fsPathCode}/${game}/screenshots/`;
    let fsPathScreenshotOutputGame = `${fsPathHugoScreenshots}/${game}/`;
    if (fs.existsSync(fsPathScreenshotInputGame)) {
      // Create the savefile directory for each game.
      if (fs.existsSync(fsPathScreenshotOutputGame) == false) {
          fs.mkdirSync(fsPathScreenshotOutputGame);
      }

      // Copy all screenshots into the output folder.
      fs.readdirSync(fsPathScreenshotInputGame).forEach(file => {
        if (path.extname(file) == '.png') {
          fsextra.copySync(`${fsPathScreenshotInputGame}/${file}`, `${fsPathScreenshotOutputGame}/${file}`);
        }
      });
    }

    // WIKI BLOCK
    var wikiText = "";
    let fsPathWikiGame = `${fsPathWiki}/${wikiEntries[game.toLowerCase() + ".md"]}`;
    if (fs.existsSync(fsPathWikiGame)) {
      wikiText = fs.readFileSync(fsPathWikiGame, 'utf8');

      // Fix Blackfriday markdown rendering differences.
      wikiText = blackfriday.fixLists(wikiText);
      wikiText = blackfriday.fixLinks(wikiText);
    } else {
      wikiText = "## No wiki exists yet for this game.";
    }
    // END WIKI BLOCK

    let modelText = tomlify(model, null, 2);

    let contentOutput = `+++\r\n${modelText}\r\n+++\r\n\r\n${wikiText}\r\n`;
    fs.writeFileSync(`${fsPathHugoContent}/${game}.md`, contentOutput);
  } catch (ex) {
    logger.warn(`${game} failed to generate: ${ex}`);
    logger.error(ex);
  }
}
<commit_msg>Display weighted average of compatibility submissions (#78)<commit_after>const fs = require('fs');
const fsextra = require('fs-extra');
const path = require('path');
const util = require('util');
const logger = require('winston');

const sanitizeHtml = require('sanitize-html');

const request = require('request-promise');
const toml = require('toml');
const tomlify = require('tomlify-j0.4');
const blackfriday = require('./blackfriday.js');

const del = require('delete');
const exec = require('sync-exec');

const fsPathCode = './citra-games-wiki/games';
const fsPathWiki = './citra-games-wiki.wiki';
const fsPathHugoContent = '../../site/content/game';
const fsPathHugoBoxart = '../../site/static/images/game/boxart';
const fsPathHugoIcon = '../../site/static/images/game/icons';
const fsPathHugoScreenshots = '../../site/static/images/screenshots0';
const fsPathHugoSavefiles = '../../site/static/savefiles/';

function gitPull(directory, repository) {
  if (fs.existsSync(directory)) {
      logger.info(`Fetching latest from Github : ${directory}`);
      logger.info(`git --git-dir=${directory} pull`);
      exec(`git --git-dir=${directory} pull`);
  } else {
      logger.info(`Cloning repository from Github : ${directory}`);
      logger.info(`git clone ${repository}`);
      exec(`git clone ${repository}`);
  }
}

function getDirectories (srcpath) {
  return fs.readdirSync(srcpath)
    .filter(file => fs.lstatSync(path.join(srcpath, file)).isDirectory())
}

async function getGithubIssues() {
  var results = [];

  // Only loop through the first x pages to prevent API limiting.
  for (var page = 0; page <= 15; page++) {
    let options = {
      url: `https://api.github.com/repos/citra-emu/citra/issues?per_page=99&page=${page}`,
      headers: { 'User-Agent': 'citrabot' }
    };

    logger.verbose(`Requesting Github Issue Page ${page}.`);
    var body = await request.get(options);
    var obj = JSON.parse(body);

    if (obj == null || obj.length == 0) {
      logger.verbose(`No more Github issues found -- on page ${page}.`);
      break;
    } else {
      results = results.concat(obj);
    }
  }

  return results;
}

async function getTestcases() {
  let options = {
    url: 'https://api.citra-emu.org/telemetry/testcase/',
    headers: { 'User-Agent': 'citrabot' },
  };

  var body = await request.get(options);
  return JSON.parse(body).map(x => {
    return {
      id: x.id,
      title: x.title,
      compatibility: x.compatibility.toString(),
      date: x.date,
      version: x.version,
      buildName: x.buildName,
      buildDate: x.buildDate,
      cpu: x.cpu,
      gpu: x.gpu,
      os: x.os,
      author: x.author
    }
  });
}

// Fetch game information stored in Github repository.
gitPull('./citra-games-wiki', 'https://github.com/citra-emu/citra-games-wiki.git');

// Fetch game articles stored in Github wiki.
gitPull('./citra-games-wiki.wiki', 'https://github.com/citra-emu/citra-games-wiki.wiki.git');

// Fetch all issues from Github.
var githubIssues = [];
var wikiEntries = {};
var testcases = [];

async function setup() {
  githubIssues = await getGithubIssues();
  logger.info(`Imported ${githubIssues.length} issues from Github.`);

  testcases = await getTestcases();
  logger.info(`Obtained ${testcases.length} testcases from Telemetry API.`);
};

setup().then(function() {
  // Make sure the output directories in Hugo exist.
  [fsPathHugoContent, fsPathHugoBoxart, fsPathHugoIcon, fsPathHugoSavefiles, fsPathHugoScreenshots].forEach(function (path) {
    if (fs.existsSync(path) == false) {
        logger.info(`Creating Hugo output directory: ${path}`);
        fs.mkdirSync(path);
    }
  });
})
.then(function() {
  // Transform wiki entries to lowercase
  const files = fs.readdirSync(fsPathWiki);

  logger.info(`Generating wiki database...`);
  files.forEach((file) => {
      wikiEntries[file.toLowerCase()] = file;
  });

  // Loop through each game and process it.
  getDirectories(fsPathCode).forEach(function(game) {
    processGame(game);
  });
})
.catch(function(err) {
  logger.error(err);
});

function processGame(game) {
  try {
    if (game == '.git' || game == '_validation') { return; }

    logger.info(`Processing game: ${game}`);

    // Copy the boxart for the game.
    fsextra.copySync(`${fsPathCode}/${game}/boxart.png`, `${fsPathHugoBoxart}/${game}.png`);

    // Copy the icon for the game.
    fsextra.copySync(`${fsPathCode}/${game}/icon.png`, `${fsPathHugoIcon}/${game}.png`);

    var model = toml.parse(fs.readFileSync(`${fsPathCode}/${game}/game.dat`, 'utf8'));
    let currentDate = new Date();
    model.date = `${currentDate.toISOString()}`;

    // Look up all testcases associated with the Title IDs.
    let releases = model.releases.map(y => y.title);
    let foundTestcases = testcases.filter(x => {
      return releases.includes(x.title);
    });

    // If no testcases exist in the toml file, create a blank array.
    if (!model.testcases) {
      model.testcases = [];
    }

    logger.info(`Found ${foundTestcases.length} testcases from telemetry, found ${model.testcases.length} in toml file.`);

    model.testcases = model.testcases.concat(foundTestcases);

    // Sort the testcases from most recent to least recent.
    model.testcases.sort(function(a, b){
      // Turn your strings into dates, and then subtract them
      // to get a value that is either negative, positive, or zero.
      return new Date(b.date) - new Date(a.date);
    });

    // SHORTCUTS BLOCK
    // Parse testcase information out of the dat to reinject as shortcut values.
    if (model.testcases == null || model.testcases.length == 0) {
      model.compatibility = "99";
      model.testcase_date = "2000-01-01";
    } else {
      let recent = model.testcases[0];
      // The displayed compatibility rating is an weighted arithmetic mean of the submitted ratings.
      let numerator = 0;
      let denominator = 0;
      model.testcases.forEach(testcase => {
        // Build date is a better metric but testcases from the TOML files only have a submission date.
        let weigh_date = new Date(testcase.buildDate == undefined ? testcase.date : testcase.buildDate);
        // The test case is weighted on an exponential decay curve such that a test case is half as relevant as each month (30 days) passes.
        // The exponent is obtained by dividing the time in millisecond between the current date and date of testing by the number of milliseconds in 30 days (but negative because it's a decay).
        let weight = Math.pow(.5, (currentDate - weigh_date) / -(30 * 1000 * 3600 * 24));
        numerator += testcase.compatibility * weight;
        denominator += weight;
      });
      model.compatibility = Math.round(numerator / denominator).toString();
      model.testcase_date = recent.date;
    }

    const toTrim = ["the", "a", "an"];

    let trimmedTitle = model.title.toLowerCase();
    toTrim.forEach(trim => {
        if (trimmedTitle.startsWith(trim + " ")) {
            trimmedTitle = trimmedTitle.substr(trim.length + 1);
        }
    });

    let section_id = `${trimmedTitle[0]}`;
    if (!section_id.match(/[a-z]+/)) {
        section_id = "#";
    }

    model.section_id = section_id;
    // END SHORTCUTS BLOCK

    // SAVEFILE BLOCK
    var fsPathCodeSavefilesGame = `${fsPathCode}/${game}/savefiles/`;
    var fsPathHugoSavefilesGame = `${fsPathHugoSavefiles}/${game}/`;
    if (fs.existsSync(fsPathCodeSavefilesGame)) {
      // Create the savefile directory for the game.
      if (fs.existsSync(fsPathHugoSavefilesGame) == false) {
          fs.mkdirSync(fsPathHugoSavefilesGame);
      }

      // Copy all savefiles into the output folder, and read their data.
      model.savefiles = [];
      fs.readdirSync(fsPathCodeSavefilesGame).forEach(file => {
        if (path.extname(file) == '.zip') {
          fsextra.copySync(`${fsPathCodeSavefilesGame}/${file}`, `${fsPathHugoSavefilesGame}/${file}`);
        } else if (path.extname(file) == '.dat') {
          // Read the data file into an object.
          let savefile = toml.parse(fs.readFileSync(`${fsPathCodeSavefilesGame}/${file}`, 'utf8'));

          let stats = fs.statSync(`${fsPathCodeSavefilesGame}/${file}`);

          // Store the contents of the file in memory for adding it into the markdown later.
          model.savefiles.push({
            date: new Date(util.inspect(stats.mtime)),
            filename: file.replace('.dat', '.zip'),
            title: savefile.title,
            description: savefile.description,
            author: savefile.author,
            title_id: savefile.title_id
          });
        }
      });
      // Finished copying all savefiles into the output folder, and reading their data.
    }
    // END SAVEFILE BLOCK

    // GITHUB ISSUES BLOCK
    model.issues = [];
    model.closed_issues = [];

    if (model.github_issues != null && model.github_issues.length > 0) {
      model.github_issues.forEach(function(number) {
        let issue = githubIssues.find(x => x.number == number);
        if (issue == null) {
          model.closed_issues.push(number);
        } else {
          model.issues.push({
            number: issue.number.toString(),
            title: issue.title,
            state: issue.state,
            created_at: issue.created_at,
            updated_at: issue.updated_at,
            labels: issue.labels.map(function(x) { return { name: x.name, color: x.color } })
          });
        }
      });

      github_issues = null;
    }
    // END GITHUB ISSUES BLOCK

    // Copy the screenshots for the game.
    let fsPathScreenshotInputGame = `${fsPathCode}/${game}/screenshots/`;
    let fsPathScreenshotOutputGame = `${fsPathHugoScreenshots}/${game}/`;
    if (fs.existsSync(fsPathScreenshotInputGame)) {
      // Create the savefile directory for each game.
      if (fs.existsSync(fsPathScreenshotOutputGame) == false) {
          fs.mkdirSync(fsPathScreenshotOutputGame);
      }

      // Copy all screenshots into the output folder.
      fs.readdirSync(fsPathScreenshotInputGame).forEach(file => {
        if (path.extname(file) == '.png') {
          fsextra.copySync(`${fsPathScreenshotInputGame}/${file}`, `${fsPathScreenshotOutputGame}/${file}`);
        }
      });
    }

    // WIKI BLOCK
    var wikiText = "";
    let fsPathWikiGame = `${fsPathWiki}/${wikiEntries[game.toLowerCase() + ".md"]}`;
    if (fs.existsSync(fsPathWikiGame)) {
      wikiText = fs.readFileSync(fsPathWikiGame, 'utf8');

      // Fix Blackfriday markdown rendering differences.
      wikiText = blackfriday.fixLists(wikiText);
      wikiText = blackfriday.fixLinks(wikiText);
    } else {
      wikiText = "## No wiki exists yet for this game.";
    }
    // END WIKI BLOCK

    let modelText = tomlify(model, null, 2);

    let contentOutput = `+++\r\n${modelText}\r\n+++\r\n\r\n${wikiText}\r\n`;
    fs.writeFileSync(`${fsPathHugoContent}/${game}.md`, contentOutput);
  } catch (ex) {
    logger.warn(`${game} failed to generate: ${ex}`);
    logger.error(ex);
  }
}
<|endoftext|>


<commit_before>import RSVP from 'rsvp';

export function initialize() {
  // async/await is using window.Promise by default and we want async/await to
  // use RSVP instead which is properly integrated with Ember's runloop
  window.Promise = RSVP.Promise;
}

export default { initialize };
<commit_msg>Auto merge of #2170 - Turbo87:promise, r=locks<commit_after><|endoftext|>


<commit_before>/* jshint -W099 */
require([
	'dojo/dom',
	'dojo/io-query',
	'dojo/on',
	'dojo/_base/window',
	'dojo/query',
	'dojo/dom-attr',
	'dojo/dom-construct',
	'dojo/dom-style',
	'dojo/request/xhr',
	'dojo/_base/array',

	'dojo/NodeList-traverse',
	'dojo/domReady!'
	], function(dom, ioQuery, on, win, query, domAttr, domConstruct, domStyle, xhr, array) {
		var crs = 'EPSG:28992';
		var serverType = 'geoserver';

		var wrapper = dom.byId('wrapper');
		var divLayerControlCnt = dom.byId('layer-control-container');
		var divViewCnt = dom.byId('viewer-container');

		var setWrapperHeight = domStyle.set(wrapper, 'height', window.innerHeight-130 + 'px');
		var setLayerControlCntHeight = domStyle.set(divLayerControlCnt, 'height', window.innerHeight-130 + 'px');
		var setViewCntHeight = domStyle.set(divViewCnt, 'height', window.innerHeight-130 + 'px');

		var setCntsHeight = on(window, 'resize', function(evt) {
			domStyle.set(divLayerControlCnt, 'height', window.innerHeight-130 + 'px');
			domStyle.set(divViewCnt, 'height', window.innerHeight-130 + 'px');
			domStyle.set(wrapper, 'height', window.innerHeight-130 + 'px');
		});

		var divView = dom.byId('srv-layer-view');
		var divInfo = dom.byId('info-container');
		var info = dom.byId('info');
		var map;

		var origin = [-285401.920, 903401.920];
		var resolutions = [3440.64, 1720.32, 860.16, 430.08, 215.04, 107.52, 53.76, 26.88, 13.44, 6.72, 3.36, 1.68, 0.84, 0.42, 0.21];
		var extent = [-285401.92, 22598.08, 595401.9199999999, 903401.9199999999];

		var matrixIds0 = [];
		matrixIds0 = array.map(resolutions, function(resolution) {
			var indexResolution = resolutions.indexOf(resolution);
			return crs + ':' + indexResolution;
		});

		var tileGrid0 = new ol.tilegrid.WMTS({
			origin: origin,
			resolutions: resolutions,
			matrixIds: matrixIds0
		});

	    var matrixIds1 = [];
	    matrixIds1 = array.map(resolutions, function(resolution) {
			var indexResolution = resolutions.indexOf(resolution);
			return (indexResolution < 10 ? '0' : '') + indexResolution;
		});

	    var projection = new ol.proj.Projection({
	    	code: 'EPSG:28992',
	    	extent: [-285401.92, 22598.08, 595401.9199999999, 903401.9199999999]
	    });

	    var view = new ol.View({
			projection: projection,
			center: [220000, 499000],
			zoom: 5
		});

		map = new ol.Map({
			layers: [
		    	new ol.layer.Tile({
		    		overlay: false,
		    		opacity: 0.8,
		    		extent: extent,
		        	source : new ol.source.WMTS({
		        		attributions: [],
		        		url: 'http://geodata.nationaalgeoregister.nl/wmts',
		        		layer: 'brtachtergrondkaart',
		        		matrixSet: crs,
		        		format: 'image/png',
		        		tileGrid: tileGrid0,
		        		style: 'default',
		        	}),
		        	visible: true
		        })
			],
			target: 'map',
			view: view
		});

		map.on('singleclick', function(evt) {
			domAttr.set(info, 'innerHTML', '');
        	var viewResolution = (map.getView().getResolution());
        	var layersArray = map.getLayers().getArray();
        	var serviceArray = query('.js-layer-check[type=checkbox]:checked').closest('.js-service-id');

        	domStyle.set(divInfo, 'display', 'block');
			domStyle.set(divView, 'height', '75%');
			domStyle.set(divView, 'margin-bottom', '15px');
			domStyle.set(divInfo, 'height', '25%');
			domStyle.set(divInfo, 'height', domStyle.get(divInfo, 'height')-15 + 'px');

			map.updateSize();

			if(serviceArray.length === 0) {
				domConstruct.place('Niets gevonden.', info);
			}

        	array.forEach(serviceArray, function(service) {
        		var checkedElementen = query(service).query('.js-layer-check[type=checkbox]:checked');
        		var layerString = '';

        		array.forEach(checkedElementen, function(checkedElement) {
        			if(checkedElementen.indexOf(checkedElement) === 0) {
        				layerString = layerString.concat(checkedElement.dataset.layerName);
        			} else {
        				layerString = layerString.concat(',', checkedElement.dataset.layerName);
        			}
        		});

        		var sourceLayer = new ol.source.ImageWMS({
    	    		url: checkedElementen[0].dataset.layerEndpoint,
    	    		params: {'LAYERS': layerString, 'VERSION': checkedElementen[0].dataset.layerVersion, 'FEATURE_COUNT': '50'},
    	    		serverType: serverType
    	    	});

        		var encodingValue = 'UTF-8';
        		var url = sourceLayer.getGetFeatureInfoUrl(evt.coordinate, viewResolution, map.getView().getProjection(), {'INFO_FORMAT': 'text/html'});
        		url += '&' + 'encoding' + '=' + encodingValue;

        		xhr(jsRoutes.controllers.GetFeatureInfoProxy.proxy(url).url, {
					handleAs: "html"
				}).then(function(data) {
					domConstruct.place(data, info);

					//domStyle.set(divInfo, 'display', 'none');
					//domStyle.set(divView, 'height', '100%');
					//domStyle.set(divView, 'margin-bottom', '0px');
					//domStyle.set(divInfo, 'height', '0%');

				});
        	});
		});

		var serviceExpand = on(win.doc, '.js-service-link:click', function(e) {
			var serviceId = domAttr.get(this.parentNode, 'data-service-id');
			var serviceNode = this.parentNode;
			var serviceIconNode = query(this).query('.js-link-icon')[0];

			if(this.dataset.serviceStatus === "none") {
				xhr(jsRoutes.controllers.Application.allLayers(serviceId).url, {
					handleAs: "html"
				}).then(function(data){
					domConstruct.place(data, serviceNode);
					domAttr.set(serviceIconNode, 'class', 'glyphicon glyphicon-minus-sign js-link-icon');
				});
				this.dataset.serviceStatus = "created";
			} else if(this.dataset.serviceStatus == "created") {
				domStyle.set(query(this).siblings()[0], 'display', 'none');
				domAttr.set(serviceIconNode, 'class', 'glyphicon glyphicon-plus-sign js-link-icon');
				this.dataset.serviceStatus = "hidden";
			} else {
				domStyle.set(query(this).siblings()[0], 'display', 'block');
				domAttr.set(serviceIconNode, 'class', 'glyphicon glyphicon-minus-sign js-link-icon');
				this.dataset.serviceStatus = "created";
			}
		});

		var layerExpand = on(win.doc, '.js-layer-link:click', function(e) {
			var serviceId = domAttr.get(query(this).closest(".js-service-id")[0], 'data-service-id');
			var layerId = domAttr.get(this.parentNode, 'data-layer-id');
			var layerNode = this.parentNode;
			var layerIconNode = query(this).query('.js-link-icon')[0];

			if(this.dataset.layerStatus === "none") {
				xhr(jsRoutes.controllers.Application.layers(serviceId, layerId).url, {
					handleAs: "html"
				}).then(function(data){
					domConstruct.place(data, layerNode);
					domAttr.set(layerIconNode, 'class', 'glyphicon glyphicon-minus-sign js-link-icon');
				});
				this.dataset.layerStatus = "created";
			} else if(this.dataset.layerStatus === "created") {
				domStyle.set(query(this).siblings()[0], 'display', 'none');
				domAttr.set(layerIconNode, 'class', 'glyphicon glyphicon-plus-sign js-link-icon');
				this.dataset.layerStatus = "hidden";
			} else {
				domStyle.set(query(this).siblings()[0], 'display', 'block');
				domAttr.set(layerIconNode, 'class', 'glyphicon glyphicon-minus-sign js-link-icon');
				this.dataset.layerStatus = "created";
			}
		});

		var layerCheck = on(win.doc, '.js-layer-check:change', function(e) {
			var layerName = domAttr.get(this, 'data-layer-name');
			var layerEndpoint = domAttr.get(this, 'data-layer-endpoint');
			var layerVersion = domAttr.get(this, 'data-layer-version');

			var layerToAdd = new ol.source.ImageWMS({
		    		url: layerEndpoint,
		    		params: {'LAYERS': layerName, 'VERSION': layerVersion, 'CRS': 'EPSG:28922'},
		    		serverType: serverType
		    });

			if(domAttr.get(this, 'checked')) {
       			map.addLayer(
       					new ol.layer.Image({
       						source: new ol.source.ImageWMS({
       				    		url: layerEndpoint,
       				    		params: {'LAYERS': layerName, 'VERSION': '1.3.0'},
       				    		serverType: serverType
       						})
       					})
       			);
       			domAttr.set(this, 'data-layer-index', map.getLayers().getLength() - 1);
   			} else {
				var indexElement = domAttr.get(this, 'data-layer-index');

   				map.removeLayer(map.getLayers().removeAt(domAttr.get(this, 'data-layer-index')));
				domAttr.set(this, 'data-layer-index', '');

				var checkedInputs = query('.js-layer-check:checked');

				array.forEach(checkedInputs, function(checkedInput) {
					if(domAttr.get(checkedInput, 'data-layer-index') > indexElement) {
						domAttr.set(checkedInput, 'data-layer-index', domAttr.get(checkedInput, 'data-layer-index') -1);
					}
				});
			}
		});
});<commit_msg>Fixed resize bug aligning heights containers<commit_after>/* jshint -W099 */
require([
	'dojo/dom',
	'dojo/io-query',
	'dojo/on',
	'dojo/_base/window',
	'dojo/query',
	'dojo/dom-attr',
	'dojo/dom-construct',
	'dojo/dom-style',
	'dojo/request/xhr',
	'dojo/_base/array',

	'dojo/NodeList-traverse',
	'dojo/domReady!'
	], function(dom, ioQuery, on, win, query, domAttr, domConstruct, domStyle, xhr, array) {
		var crs = 'EPSG:28992';
		var serverType = 'geoserver';

		var wrapper = dom.byId('wrapper');
		var divLayerControlCnt = dom.byId('layer-control-container');
		var divViewCnt = dom.byId('viewer-container');
		var divView = dom.byId('srv-layer-view');
		var divInfo = dom.byId('info-container');
		var info = dom.byId('info');
		var map;

		var setWrapperHeight = domStyle.set(wrapper, 'height', window.innerHeight-130 + 'px');
		var setLayerControlCntHeight = domStyle.set(divLayerControlCnt, 'height', window.innerHeight-130 + 'px');
		var setViewCntHeight = domStyle.set(divViewCnt, 'height', window.innerHeight-130 + 'px');

		var setCntsHeight = on(window, 'resize', function(evt) {
			domStyle.set(divLayerControlCnt, 'height', window.innerHeight-130 + 'px');
			domStyle.set(wrapper, 'height', window.innerHeight-130 + 'px');

			if(domStyle.get(divInfo, 'display') === 'none') {
				domStyle.set(divViewCnt, 'height', window.innerHeight-130 + 'px');
			} else {
				domStyle.set(divViewCnt, 'height', window.innerHeight-130 + 'px');

				domStyle.set(divView, 'height', '75%');
				domStyle.set(divView, 'margin-bottom', '15px');
				domStyle.set(divInfo, 'height', '25%');
				domStyle.set(divInfo, 'height', domStyle.get(divInfo, 'height')-15 + 'px');

				map.updateSize();
			}
		});

		var origin = [-285401.920, 903401.920];
		var resolutions = [3440.64, 1720.32, 860.16, 430.08, 215.04, 107.52, 53.76, 26.88, 13.44, 6.72, 3.36, 1.68, 0.84, 0.42, 0.21];
		var extent = [-285401.92, 22598.08, 595401.9199999999, 903401.9199999999];

		var matrixIds0 = [];
		matrixIds0 = array.map(resolutions, function(resolution) {
			var indexResolution = resolutions.indexOf(resolution);
			return crs + ':' + indexResolution;
		});

		var tileGrid0 = new ol.tilegrid.WMTS({
			origin: origin,
			resolutions: resolutions,
			matrixIds: matrixIds0
		});

	    var matrixIds1 = [];
	    matrixIds1 = array.map(resolutions, function(resolution) {
			var indexResolution = resolutions.indexOf(resolution);
			return (indexResolution < 10 ? '0' : '') + indexResolution;
		});

	    var projection = new ol.proj.Projection({
	    	code: 'EPSG:28992',
	    	extent: [-285401.92, 22598.08, 595401.9199999999, 903401.9199999999]
	    });

	    var view = new ol.View({
			projection: projection,
			center: [220000, 499000],
			zoom: 5
		});

		map = new ol.Map({
			layers: [
		    	new ol.layer.Tile({
		    		overlay: false,
		    		opacity: 0.8,
		    		extent: extent,
		        	source : new ol.source.WMTS({
		        		attributions: [],
		        		url: 'http://geodata.nationaalgeoregister.nl/wmts',
		        		layer: 'brtachtergrondkaart',
		        		matrixSet: crs,
		        		format: 'image/png',
		        		tileGrid: tileGrid0,
		        		style: 'default',
		        	}),
		        	visible: true
		        })
			],
			target: 'map',
			view: view
		});

		map.on('singleclick', function(evt) {
			domAttr.set(info, 'innerHTML', '');
        	var viewResolution = (map.getView().getResolution());
        	var layersArray = map.getLayers().getArray();
        	var serviceArray = query('.js-layer-check[type=checkbox]:checked').closest('.js-service-id');

        	domStyle.set(divInfo, 'display', 'block');
			domStyle.set(divView, 'height', '75%');
			domStyle.set(divView, 'margin-bottom', '15px');
			domStyle.set(divInfo, 'height', '25%');
			domStyle.set(divInfo, 'height', domStyle.get(divInfo, 'height')-15 + 'px');

			map.updateSize();

			if(serviceArray.length === 0) {
				domConstruct.place('Niets gevonden.', info);
			}

        	array.forEach(serviceArray, function(service) {
        		var checkedElementen = query(service).query('.js-layer-check[type=checkbox]:checked');
        		var layerString = '';

        		array.forEach(checkedElementen, function(checkedElement) {
        			if(checkedElementen.indexOf(checkedElement) === 0) {
        				layerString = layerString.concat(checkedElement.dataset.layerName);
        			} else {
        				layerString = layerString.concat(',', checkedElement.dataset.layerName);
        			}
        		});

        		var sourceLayer = new ol.source.ImageWMS({
    	    		url: checkedElementen[0].dataset.layerEndpoint,
    	    		params: {'LAYERS': layerString, 'VERSION': checkedElementen[0].dataset.layerVersion, 'FEATURE_COUNT': '50'},
    	    		serverType: serverType
    	    	});

        		var encodingValue = 'UTF-8';
        		var url = sourceLayer.getGetFeatureInfoUrl(evt.coordinate, viewResolution, map.getView().getProjection(), {'INFO_FORMAT': 'text/html'});
        		url += '&' + 'encoding' + '=' + encodingValue;

        		xhr(jsRoutes.controllers.GetFeatureInfoProxy.proxy(url).url, {
					handleAs: "html"
				}).then(function(data) {
					domConstruct.place(data, info);

					//domStyle.set(divInfo, 'display', 'none');
					//domStyle.set(divView, 'height', '100%');
					//domStyle.set(divView, 'margin-bottom', '0px');
					//domStyle.set(divInfo, 'height', '0%');

				});
        	});
		});

		var serviceExpand = on(win.doc, '.js-service-link:click', function(e) {
			var serviceId = domAttr.get(this.parentNode, 'data-service-id');
			var serviceNode = this.parentNode;
			var serviceIconNode = query(this).query('.js-link-icon')[0];

			if(this.dataset.serviceStatus === "none") {
				xhr(jsRoutes.controllers.Application.allLayers(serviceId).url, {
					handleAs: "html"
				}).then(function(data){
					domConstruct.place(data, serviceNode);
					domAttr.set(serviceIconNode, 'class', 'glyphicon glyphicon-minus-sign js-link-icon');
				});
				this.dataset.serviceStatus = "created";
			} else if(this.dataset.serviceStatus == "created") {
				domStyle.set(query(this).siblings()[0], 'display', 'none');
				domAttr.set(serviceIconNode, 'class', 'glyphicon glyphicon-plus-sign js-link-icon');
				this.dataset.serviceStatus = "hidden";
			} else {
				domStyle.set(query(this).siblings()[0], 'display', 'block');
				domAttr.set(serviceIconNode, 'class', 'glyphicon glyphicon-minus-sign js-link-icon');
				this.dataset.serviceStatus = "created";
			}
		});

		var layerExpand = on(win.doc, '.js-layer-link:click', function(e) {
			var serviceId = domAttr.get(query(this).closest(".js-service-id")[0], 'data-service-id');
			var layerId = domAttr.get(this.parentNode, 'data-layer-id');
			var layerNode = this.parentNode;
			var layerIconNode = query(this).query('.js-link-icon')[0];

			if(this.dataset.layerStatus === "none") {
				xhr(jsRoutes.controllers.Application.layers(serviceId, layerId).url, {
					handleAs: "html"
				}).then(function(data){
					domConstruct.place(data, layerNode);
					domAttr.set(layerIconNode, 'class', 'glyphicon glyphicon-minus-sign js-link-icon');
				});
				this.dataset.layerStatus = "created";
			} else if(this.dataset.layerStatus === "created") {
				domStyle.set(query(this).siblings()[0], 'display', 'none');
				domAttr.set(layerIconNode, 'class', 'glyphicon glyphicon-plus-sign js-link-icon');
				this.dataset.layerStatus = "hidden";
			} else {
				domStyle.set(query(this).siblings()[0], 'display', 'block');
				domAttr.set(layerIconNode, 'class', 'glyphicon glyphicon-minus-sign js-link-icon');
				this.dataset.layerStatus = "created";
			}
		});

		var layerCheck = on(win.doc, '.js-layer-check:change', function(e) {
			var layerName = domAttr.get(this, 'data-layer-name');
			var layerEndpoint = domAttr.get(this, 'data-layer-endpoint');
			var layerVersion = domAttr.get(this, 'data-layer-version');

			var layerToAdd = new ol.source.ImageWMS({
		    		url: layerEndpoint,
		    		params: {'LAYERS': layerName, 'VERSION': layerVersion, 'CRS': 'EPSG:28922'},
		    		serverType: serverType
		    });

			if(domAttr.get(this, 'checked')) {
       			map.addLayer(
       					new ol.layer.Image({
       						source: new ol.source.ImageWMS({
       				    		url: layerEndpoint,
       				    		params: {'LAYERS': layerName, 'VERSION': '1.3.0'},
       				    		serverType: serverType
       						})
       					})
       			);
       			domAttr.set(this, 'data-layer-index', map.getLayers().getLength() - 1);
   			} else {
				var indexElement = domAttr.get(this, 'data-layer-index');

   				map.removeLayer(map.getLayers().removeAt(domAttr.get(this, 'data-layer-index')));
				domAttr.set(this, 'data-layer-index', '');

				var checkedInputs = query('.js-layer-check:checked');

				array.forEach(checkedInputs, function(checkedInput) {
					if(domAttr.get(checkedInput, 'data-layer-index') > indexElement) {
						domAttr.set(checkedInput, 'data-layer-index', domAttr.get(checkedInput, 'data-layer-index') -1);
					}
				});
			}
		});
});<|endoftext|>


<commit_before>// ==UserScript==
// @name WIP Limiter
// @namespace http://github.com/apiology/
// @description Add Kanban-style visual WIP limit indicators
// @match https://app.asana.com/*
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==

Array.prototype.flatMap = function flatMap(lambda) {
  return Array.prototype.concat.apply([], this.map(lambda));
};

((css) => {
  const head = document.getElementsByTagName('head')[0];
  if (!head) { return; }
  const style = document.createElement('style');
  style.type = 'text/css';
  style.innerHTML = css;
  head.appendChild(style);
})(`
  .wip-limit-under { }
  .wip-limit-over {
    background-color: rgb(214, 65, 65) !important;
  }
  .wip-limit-on-edge {
    background-color: rgb(239, 190, 67) !important;
  }
`);

class Section {
  constructor(header) {
    this.header = header;
  }

  title() {
    const textareas =
      this.header.getElementsByClassName(this.textAreaClassName());
    if (textareas.length !== 1) {
      return null;
    }

    return textareas[0].value;
  }

  wipLimit() {
    const headerTitle = this.title();
    const wipFinder = /.*\[(\d*)\]:$/;
    const results = wipFinder.exec(headerTitle);
    if (results !== null) {
      return parseInt(results[1], 10);
    }
    return null;
  }

  countChildren() {
    const count = this.children().length;
    return count;
  }

  headerAndChildren() {
    // shallow copy
    const all = this.children().slice();
    all.unshift(this.header);
    return all;
  }

  markBackgroundColor() {
    const wipLimit = this.wipLimit();
    if (wipLimit === null) {
      this.markAsUnderLimit();
    } else {
      const childCount = this.countChildren();
      if (wipLimit === childCount) {
        this.markAsOnEdge();
      } else if (wipLimit < childCount) {
        this.markAsOverLimit();
      } else {
        this.markAsUnderLimit();
      }
    }
  }

  elementsToMark() {
    const all = this.headerAndChildren();
    let subElements = [];
    for (const task of all) {
      const overlays = task.getElementsByClassName('task-row-overlay');
      if (overlays !== null) {
        subElements = subElements.concat(Array.from(overlays));
      }
    }
    return all.concat(subElements);
  }

  markAsOnEdge() {
    for (const child of this.elementsToMark()) {
      child.classList.remove('wip-limit-under');
      child.classList.remove('wip-limit-over');
      child.classList.add('wip-limit-on-edge');
    }
  }

  markAsOverLimit() {
    for (const child of this.elementsToMark()) {
      child.classList.remove('wip-limit-under');
      child.classList.add('wip-limit-over');
      child.classList.remove('wip-limit-on-edge');
    }
  }

  markAsUnderLimit() {
    for (const child of this.elementsToMark()) {
      child.classList.add('wip-limit-under');
      child.classList.remove('wip-limit-over');
      child.classList.remove('wip-limit-on-edge');
    }
  }

  children() {
    let curNode = this.nextTaskSibling(this.header);
    const childList = [];
    while (curNode != null) {
      if (this.isHeader(curNode)) {
        curNode = null;
      } else {
        childList.push(curNode);
        curNode = this.nextTaskSibling(curNode);
      }
    }
    return childList;
  }
}

class MyTasksSection extends Section {
  isHeader(element) {
    return element.classList.contains('bar-row');
  }

  nextTaskSibling(row) {
    return row.nextSibling;
  }

  textAreaClassName() {
    return 'task-row-text-input';
  }

  static findTaskListElements() {
    return Array.of(document.getElementsByClassName('grid'))
      .filter(e => e.tagName === 'table')
      .flatMap(e => Array.of(e.getElementsByTagName('tbody')));
  }
}

class ProjectSection extends Section {
  isHeader(element) {
    return element.classList.contains('sectionRow');
  }

  nextTaskSibling(row) {
    const uncle = row.parentNode.nextSibling;
    if (uncle === null) {
      return null;
    }
    return uncle.firstChild;
  }

  textAreaClassName() {
    return 'taskName-input';
  }
}

// create an observer instance
const observer = new MutationObserver((mutations, observer) => {
  mutations.forEach((mutation) => {
    console.log('Mutation!');
    console.log(mutation.type);
    console.log(mutation.target);
  });
});

// configuration of the observer:
const config = { attributes: true, childList: true, characterData: true };

const subscribeToTaskListChanges = () => {
  // TODO: Better name than 'container'
  console.log('Looking for task list elements...');
  for (const taskListElement of MyTasksSection.findTaskListElements()) {
    // pass in the target node, as well as the observer options
    console.log('registering observer on:');
    console.log(taskListElement);
    // observer.observe(taskListElement, config);
  }
  console.log('Done looking for task list elements.');
};

if (document.body) {
  console.log('already loaded; running now');
  subscribeToTaskListChanges();
  console.log('ran!');
} else {
  console.log('registering listener');
  document.addEventListener('DOMContentLoaded',
                            subscribeToTaskListChanges,
                            false);
  console.log('registered listener');
}

setInterval(() => {
  //
  // The DOM/CSS for tasks in the 'my task' screen differs between the
  // 'My Tasks' screen and the project screens:
  //
  const myTasksSectionHeaders = document.getElementsByClassName('bar-row');
  for (const headerElement of myTasksSectionHeaders) {
    const header = new MyTasksSection(headerElement);
    header.markBackgroundColor();
  }
  const projectSectionHeaders = document.getElementsByClassName('sectionRow');
  for (const headerElement of projectSectionHeaders) {
    const header = new ProjectSection(headerElement);
    header.markBackgroundColor();
  }
}, 1000);
<commit_msg>Wait for subscription<commit_after>// ==UserScript==
// @name WIP Limiter
// @namespace http://github.com/apiology/
// @description Add Kanban-style visual WIP limit indicators
// @match https://app.asana.com/*
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==

Array.prototype.flatMap = function flatMap(lambda) {
  return Array.prototype.concat.apply([], this.map(lambda));
};

((css) => {
  const head = document.getElementsByTagName('head')[0];
  if (!head) { return; }
  const style = document.createElement('style');
  style.type = 'text/css';
  style.innerHTML = css;
  head.appendChild(style);
})(`
  .wip-limit-under { }
  .wip-limit-over {
    background-color: rgb(214, 65, 65) !important;
  }
  .wip-limit-on-edge {
    background-color: rgb(239, 190, 67) !important;
  }
`);

class Section {
  constructor(header) {
    this.header = header;
  }

  title() {
    const textareas =
      this.header.getElementsByClassName(this.textAreaClassName());
    if (textareas.length !== 1) {
      return null;
    }

    return textareas[0].value;
  }

  wipLimit() {
    const headerTitle = this.title();
    const wipFinder = /.*\[(\d*)\]:$/;
    const results = wipFinder.exec(headerTitle);
    if (results !== null) {
      return parseInt(results[1], 10);
    }
    return null;
  }

  countChildren() {
    const count = this.children().length;
    return count;
  }

  headerAndChildren() {
    // shallow copy
    const all = this.children().slice();
    all.unshift(this.header);
    return all;
  }

  markBackgroundColor() {
    const wipLimit = this.wipLimit();
    if (wipLimit === null) {
      this.markAsUnderLimit();
    } else {
      const childCount = this.countChildren();
      if (wipLimit === childCount) {
        this.markAsOnEdge();
      } else if (wipLimit < childCount) {
        this.markAsOverLimit();
      } else {
        this.markAsUnderLimit();
      }
    }
  }

  elementsToMark() {
    const all = this.headerAndChildren();
    let subElements = [];
    for (const task of all) {
      const overlays = task.getElementsByClassName('task-row-overlay');
      if (overlays !== null) {
        subElements = subElements.concat(Array.from(overlays));
      }
    }
    return all.concat(subElements);
  }

  markAsOnEdge() {
    for (const child of this.elementsToMark()) {
      child.classList.remove('wip-limit-under');
      child.classList.remove('wip-limit-over');
      child.classList.add('wip-limit-on-edge');
    }
  }

  markAsOverLimit() {
    for (const child of this.elementsToMark()) {
      child.classList.remove('wip-limit-under');
      child.classList.add('wip-limit-over');
      child.classList.remove('wip-limit-on-edge');
    }
  }

  markAsUnderLimit() {
    for (const child of this.elementsToMark()) {
      child.classList.add('wip-limit-under');
      child.classList.remove('wip-limit-over');
      child.classList.remove('wip-limit-on-edge');
    }
  }

  children() {
    let curNode = this.nextTaskSibling(this.header);
    const childList = [];
    while (curNode != null) {
      if (this.isHeader(curNode)) {
        curNode = null;
      } else {
        childList.push(curNode);
        curNode = this.nextTaskSibling(curNode);
      }
    }
    return childList;
  }
}

class MyTasksSection extends Section {
  isHeader(element) {
    return element.classList.contains('bar-row');
  }

  nextTaskSibling(row) {
    return row.nextSibling;
  }

  textAreaClassName() {
    return 'task-row-text-input';
  }

  static findTaskListElements() {
    return Array.of(document.getElementsByClassName('grid'))
      .filter(e => e.tagName === 'table')
      .flatMap(e => Array.of(e.getElementsByTagName('tbody')));
  }
}

class ProjectSection extends Section {
  isHeader(element) {
    return element.classList.contains('sectionRow');
  }

  nextTaskSibling(row) {
    const uncle = row.parentNode.nextSibling;
    if (uncle === null) {
      return null;
    }
    return uncle.firstChild;
  }

  textAreaClassName() {
    return 'taskName-input';
  }
}

// create an observer instance
const observer = new MutationObserver((mutations, observer) => {
  mutations.forEach((mutation) => {
    console.log('Mutation!');
    console.log(mutation.type);
    console.log(mutation.target);
  });
});

// configuration of the observer:
const config = { attributes: true, childList: true, characterData: true };

let registeredTaskLists = false;

const subscribeToTaskListChanges = () => {
  if (!registeredTaskLists) {
    console.log('Looking for task list elements...');
    for (const taskListElement of MyTasksSection.findTaskListElements()) {
      // pass in the target node, as well as the observer options
      console.log('registering observer on:');
      console.log(taskListElement);

      // assume that if we found one task list, they're all in place
      registeredTaskLists = true;
    }
    console.log('Done looking for task list elements.');
  }
};

if (document.body) {
  console.log('already loaded; running now');
  subscribeToTaskListChanges();
  console.log('ran!');
} else {
  console.log('registering listener');
  document.addEventListener('DOMContentLoaded',
                            subscribeToTaskListChanges,
                            false);
  console.log('registered listener');
}

setInterval(() => {
  subscribeToTaskListChanges();

  //
  // The DOM/CSS for tasks in the 'my task' screen differs between the
  // 'My Tasks' screen and the project screens:
  //
  const myTasksSectionHeaders = document.getElementsByClassName('bar-row');
  for (const headerElement of myTasksSectionHeaders) {
    const header = new MyTasksSection(headerElement);
    header.markBackgroundColor();
  }
  const projectSectionHeaders = document.getElementsByClassName('sectionRow');
  for (const headerElement of projectSectionHeaders) {
    const header = new ProjectSection(headerElement);
    header.markBackgroundColor();
  }
}, 1000);
<|endoftext|>


<commit_before><commit_msg>Update banner for Gatsby Builds (#21099)<commit_after><|endoftext|>