<commit_before>(function() {
  'use strict';

  global.helper = {};

  /**
   * Parsed JSON schemas
   */
  helper.parsed = {};

  /**
   * Dereferenced JSON schemas
   */
  helper.dereferenced = {};

  /**
   * Bundled JSON schemas
   */
  helper.bundled = {};

  /**
   * Returns a function that throws an error if called.
   *
   * @param {function} done
   */
  helper.shouldNotGetCalled = function shouldNotGetCalled(done) {
    return function shouldNotGetCalledFN(err) {
      if (!(err instanceof Error)) {
        err = new Error('This function should not have gotten called.');
      }
      done(err);
    };
  };

  /**
   * Tests the {@link $RefParser.resolve} method,
   * and asserts that the given file paths resolve to the given values.
   *
   * @param {string} filePath - The file path that should be resolved
   * @param {*} resolvedValue - The resolved value of the file
   * @param {...*} [params] - Additional file paths and resolved values
   * @returns {Function}
   */
  helper.testResolve = function testResolve(filePath, resolvedValue, params) {
    var schemaFile = path.rel(arguments[0]);
    var parsedSchema = arguments[1];
    var expectedFiles = [], expectedValues = [];
    for (var i = 0; i < arguments.length; i++) {
      expectedFiles.push(path.abs(arguments[i]));
      expectedValues.push(arguments[++i]);
    }

    return function(done) {
      var parser = new $RefParser();
      parser
        .resolve(schemaFile)
        .then(function($refs) {
          expect(parser.schema).to.deep.equal(parsedSchema);
          expect(parser.$refs).to.equal($refs);

          // Resolved file paths
          expect($refs.paths()).to.have.same.members(expectedFiles);
          if (userAgent.isNode) {
            expect($refs.paths(['fs'])).to.have.same.members(expectedFiles);
            expect($refs.paths('http', 'https')).to.be.an('array').with.lengthOf(0);
          }
          else {
            expect($refs.paths(['http', 'https'])).to.have.same.members(expectedFiles);
            expect($refs.paths('fs')).to.be.an('array').with.lengthOf(0);
          }

          // Resolved values
          var values = $refs.values();
          expect(values).to.have.keys(expectedFiles);
          expectedFiles.forEach(function(file, i) {
            var actual = values[file];
            var expected = expectedValues[i];
            if (actual && actual.constructor && actual.constructor.name === 'Buffer') {
              // Convert Buffers to POJOs for comparison
              actual = actual.toJSON();
            }
            expect(actual).to.deep.equal(expected, file);
          });

          done();
        })
        .catch(helper.shouldNotGetCalled(done));
    }
  };

})();
<commit_msg>Fixed broken tests in Node v0.10<commit_after>(function() {
  'use strict';

  global.helper = {};

  /**
   * Parsed JSON schemas
   */
  helper.parsed = {};

  /**
   * Dereferenced JSON schemas
   */
  helper.dereferenced = {};

  /**
   * Bundled JSON schemas
   */
  helper.bundled = {};

  /**
   * Returns a function that throws an error if called.
   *
   * @param {function} done
   */
  helper.shouldNotGetCalled = function shouldNotGetCalled(done) {
    return function shouldNotGetCalledFN(err) {
      if (!(err instanceof Error)) {
        err = new Error('This function should not have gotten called.');
      }
      done(err);
    };
  };

  /**
   * Tests the {@link $RefParser.resolve} method,
   * and asserts that the given file paths resolve to the given values.
   *
   * @param {string} filePath - The file path that should be resolved
   * @param {*} resolvedValue - The resolved value of the file
   * @param {...*} [params] - Additional file paths and resolved values
   * @returns {Function}
   */
  helper.testResolve = function testResolve(filePath, resolvedValue, params) {
    var schemaFile = path.rel(arguments[0]);
    var parsedSchema = arguments[1];
    var expectedFiles = [], expectedValues = [];
    for (var i = 0; i < arguments.length; i++) {
      expectedFiles.push(path.abs(arguments[i]));
      expectedValues.push(arguments[++i]);
    }

    return function(done) {
      var parser = new $RefParser();
      parser
        .resolve(schemaFile)
        .then(function($refs) {
          expect(parser.schema).to.deep.equal(parsedSchema);
          expect(parser.$refs).to.equal($refs);

          // Resolved file paths
          expect($refs.paths()).to.have.same.members(expectedFiles);
          if (userAgent.isNode) {
            expect($refs.paths(['fs'])).to.have.same.members(expectedFiles);
            expect($refs.paths('http', 'https')).to.be.an('array').with.lengthOf(0);
          }
          else {
            expect($refs.paths(['http', 'https'])).to.have.same.members(expectedFiles);
            expect($refs.paths('fs')).to.be.an('array').with.lengthOf(0);
          }

          // Resolved values
          var values = $refs.values();
          expect(values).to.have.keys(expectedFiles);
          expectedFiles.forEach(function(file, i) {
            var actual = convertNodeBuffersToPOJOs(values[file]);
            var expected = expectedValues[i];
            expect(actual).to.deep.equal(expected, file);
          });

          done();
        })
        .catch(helper.shouldNotGetCalled(done));
    }
  };

  /**
   * Converts Buffer objects to POJOs, so they can be compared using Chai
   */
  function convertNodeBuffersToPOJOs(value) {
    if (value && value.constructor && value.constructor.name === 'Buffer') {
      // Convert Buffers to POJOs for comparison
      value = value.toJSON();

      if (userAgent.isNode && /v0\.10/.test(process.version)) {
        // Node v0.10 serializes buffers differently
        value = {type: 'Buffer', data: actual};
      }
    }
    return value;
  }

})();
<|endoftext|>


<commit_before>const udify = require('../../../data/udify')

module.exports = async function createRole(obj
, { input: { name, parent, resources } }
, { log, state: { dbPool, loaders } }) {
  const conn = await dbPool.getConnection()
  let id

  try {
    await conn.beginTransaction()
    const [ { insertId } ] = await udify.insert(conn, 'bm_web_roles', { name, 'parent_role_id': parent })
    const [ allResources ] = await conn.execute('SELECT resource_id AS id FROM bm_web_resources')

    id = insertId

    for (let allResource of allResources) {
      const resource = find(resources, { id: allResource.id })

      if (!resource) {
        log.info('hello', id)
        await udify.insert(conn, 'bm_web_role_resources', { value: 0, 'role_id': id, 'resource_id': allResource.id })
        continue
      }

      const ids = resource.permissions // @TODO reduce and Promise.all
        .filter(perm => perm.allowed)
        .map(perm => perm.id)

      if (!ids.length) {
        await udify.insert(conn, 'bm_web_role_resources', { value: 0, 'role_id': id, 'resource_id': allResource.id })
        continue
      }

      await conn.query(`INSERT INTO bm_web_role_resources
        (role_id, resource_id, value)
        VALUES (?, ?, (
          SELECT
            SUM(value)
          FROM
            bm_web_resource_permissions
          WHERE
            permission_id IN (?)
        ))
      `, [ id, resource.id, ids ])
    }

    await conn.commit()
  } catch (e) {
    log.error(e)

    if (!conn.connection._fatalError) {
      conn.rollback()
    }
  } finally {
    conn.release()
  }

  if (!id) throw new Error('An error occurred')

  return loaders.role.ids.load(id)
}
<commit_msg>fix(createRole): removed erroneous log<commit_after>const udify = require('../../../data/udify')

module.exports = async function createRole(obj
, { input: { name, parent, resources } }
, { log, state: { dbPool, loaders } }) {
  const conn = await dbPool.getConnection()
  let id

  try {
    await conn.beginTransaction()
    const [ { insertId } ] = await udify.insert(conn, 'bm_web_roles', { name, 'parent_role_id': parent })
    const [ allResources ] = await conn.execute('SELECT resource_id AS id FROM bm_web_resources')

    id = insertId

    for (let allResource of allResources) {
      const resource = find(resources, { id: allResource.id })

      if (!resource) {
        await udify.insert(conn, 'bm_web_role_resources', { value: 0, 'role_id': id, 'resource_id': allResource.id })
        continue
      }

      const ids = resource.permissions // @TODO reduce and Promise.all
        .filter(perm => perm.allowed)
        .map(perm => perm.id)

      if (!ids.length) {
        await udify.insert(conn, 'bm_web_role_resources', { value: 0, 'role_id': id, 'resource_id': allResource.id })
        continue
      }

      await conn.query(`INSERT INTO bm_web_role_resources
        (role_id, resource_id, value)
        VALUES (?, ?, (
          SELECT
            SUM(value)
          FROM
            bm_web_resource_permissions
          WHERE
            permission_id IN (?)
        ))
      `, [ id, resource.id, ids ])
    }

    await conn.commit()
  } catch (e) {
    log.error(e)

    if (!conn.connection._fatalError) {
      conn.rollback()
    }
  } finally {
    conn.release()
  }

  if (!id) throw new Error('An error occurred')

  return loaders.role.ids.load(id)
}
<|endoftext|>


<commit_before>import MarkdownIt from 'markdown-it'

export default ({ app }, inject) => {
<%
const plugins = options.use || []
delete options.use
options = serialize(options)
options = options === '{}' ? undefined : options
%>
  const md = new MarkdownIt(<%= options %>)
<%
  for (config of plugins) {
    const hasOpts = Array.isArray(config);
    const plugin = hasOpts ? config.shift(): config
    const opts = hasOpts ? config : []
%>
  md.use(require('<%= plugin %>')<% for(opt of opts) { %>, <%= serialize(opt) %> <% } %>)
<% } %>
  inject('md', md)
}
<commit_msg>fix(markdownit): intropDefault for plugin imports (#347)<commit_after>import MarkdownIt from 'markdown-it'

const handlePlugin = (plugin) => plugin.default || plugin

export default ({ app }, inject) => {
<%
const plugins = options.use || []
delete options.use
options = serialize(options)
options = options === '{}' ? undefined : options
%>
  const md = new MarkdownIt(<%= options %>)
<%
  for (config of plugins) {
    const hasOpts = Array.isArray(config);
    const plugin = hasOpts ? config.shift(): config
    const opts = hasOpts ? config : []
%>
  md.use(handlePlugin(require('<%= plugin %>'))<% for(opt of opts) { %>, <%= serialize(opt) %> <% } %>)
<% } %>
  inject('md', md)
}
<|endoftext|>


<commit_before>
//Creates the map
var imageMap = L.map("imageMap", {
    crs: L.CRS.Simple,
    zoomControl: false,
    unitsPer1000px: 1000
});
//Creates custom pin
var customPin = L.icon({
    iconUrl: "../../images/pinNormal.svg",
    shadowUrl: "../../images/pinshadow.svg",
    iconSize: [38, 58], // size of the icon
    shadowSize: [80, 120], // size of the shadow
    iconAnchor: [15, 58], // point of the icon which will correspond to marker's location
    shadowAnchor: [11, 62],  // the same for the shadow
    popupAnchor: [3, -45]
});
var hoverPin = L.icon({
    iconUrl: "../../images/pinLit.svg",
    shadowUrl: "../../images/pinshadow.svg",
    iconSize: [38, 58], // size of the icon
    shadowSize: [80, 120], // size of the shadow
    iconAnchor: [15, 58], // point of the icon which will correspond to marker's location
    shadowAnchor: [11, 62],  // the same for the shadow
    popupAnchor: [3, -45]
});
//Changing map size/location when window is resized
$(window).resize(function () {
    setTimeout(
        function () {
            imageMap.invalidateSize();
        }, 1000);

});
var markerGroup = L.featureGroup().addTo(imageMap);
//Setting the bounds
var height = $("#image-container img").height();
var width = $("#image-container img").width();
var bound = [[1, 1], [height, width]];

//Disabling all the controls for the map
imageMap.fitBounds(bound);
imageMap.dragging.disable();
imageMap.touchZoom.disable();
imageMap.doubleClickZoom.disable();
imageMap.scrollWheelZoom.disable();
imageMap.boxZoom.disable();
imageMap.keyboard.disable();
imageMap.setView([0, 0]);
if (imageMap.tap) imageMap.tap.disable();

//Test marker

//Setting the correct size for the map if the window is resized

imageMap.on('click', function (e) {
    mapOnClick(e);
});

//Button control
$(".leaflet-map-pane").attr("id", "map-pane");
function popupState() {
    if ($("#map-pane").hasClass("hidden")) {
        $("#map-pane").removeClass("hidden");
        imageMap.on('click', function (e) {
            mapOnClick(e);
        });
    }
    else {
        $("#map-pane").addClass("hidden");
        imageMap.off('click');
    }
}
//Array of all the popups and markers
var markersArray = new Array();
var popupsArray = new Array();
var locations = [[]];

//listener for clicks
function mapOnClick(e) {
    createMarker(e.latlng, true);
}
//Creating individual markers. Needed because onClick event sends a different object than createMarkers()
//clickBool determines wether the markers and popups are created by clicking on map or by fetching data from DB
function createMarker(latlng, clickBool) {
    var uniqID = Math.round(new Date().getTime() +(Math.random() * 100));
    var marker = new L.marker(latlng, { icon: customPin }).addTo(markerGroup);
    var popup = new L.Popup();
    //Removes marker if popup is empty
    marker.on('popupclose', function (e) {
        if (($("#popup" + uniqID).html().indexOf("popup-comment")) === -1) {
            imageMap.removeLayer(marker);
        }
    });
    popup.options.autoPan = false;
    popup.options.closeOnClick = true;
    //Focusing the textarea of the popup
    marker.on("click", function () {
        setTimeout(
            function () {
                $("#popuptext" + uniqID).focus();
            }, 50);

    });
    popup.myData = { id: uniqID };
    popupsArray.push(popup);
    markersArray.push(marker);
    locations.push(latlng);
    marker.bindPopup(popup);
    marker.myData = { id: uniqID };
    if (clickBool) {
        popup.setContent(createBtn(uniqID));
        marker.openPopup();
        $(".popup-textarea").focus();
        return;
    }

    return uniqID;
}
//Creates initial text
function createBtn(uniqID) {

    var btn = "<button onclick='commentClick(" + uniqID + ")' class='btn btn-success popup-btn'> </button>";
    Math.floor(Math.random() * 100);
    var strng = "

You

<textarea id='popuptext" + uniqID + "' rows= '2' class='form-control popup-textarea' o id='popuptext" + uniqID + "' ></textarea >
<input type='checkbox' class='urgency-popup'>Urgent
  " + btn + "
 ";

    return strng;
}

//Creating a new comment row
function createCommentRow(user, comment, uniqID, parent, urgency) {

    var urgencyEl; //Urgency element
    if (urgency === 1) {
        urgencyEl = "

";
    }
    else urgencyEl = "";
    var row = "

" + user + "

" + comment + "
" + urgencyEl + "
";
    popupX = popupsArray[popupsArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))];
    popupX.setContent(appendRow(row, uniqID, parent));

}
//Since the whole popup has to be recreated, this method clones it's previous HTML and adds a new comment row
function appendRow(row, uniqID, parent) {
    markerX = markersArray[markersArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))];
    var popupContent = markerX.getPopup().getContent();
    //When changing the HTML of a popup, this code will have to be updated!
    var openingTag = "
";
    var div = $(document.createElement('div'));
    div.addClass("container-fluid popup-comment-container").attr("id", "popup" + uniqID);
    var inputBox = createInputRow(uniqID, parent);

    if (popupContent === undefined) {
        $(row).appendTo(div);

    }
    else {
        $(popupContent.slice(openingTag.length, popupContent.length - 3 - inputBox.length)).appendTo(div);
        $(row).appendTo(div);

    }
    //A new input section has to be created each time to keep things consistent, otherwise it messes up the HTML
    return openingTag + div.html() + "
" + inputBox;

}

//Creates markers from existing comments in the DB
function createMarkers(comment, user, lat, lng, parent,urgency, reload) {
    if (lat !== 0 && lng !== 0) {
        var latCollection = locations.map(function (value, index) { return value[1]; });
        var lngCollection = locations.map(function (value, index) { return value[2]; });
        var uniqID;
        if ($.inArray(lat, latCollection) !== -1 && $.inArray(lng, lngCollection) !== -1) {

            if ($.inArray(lat, latCollection) === $.inArray(lng, lngCollection)) {
                var idCollection = locations.map(function (value, index) { return value[0]; });
                uniqID = idCollection[$.inArray(lat, latCollection)];
                createCommentRow(user, comment, uniqID, parent,urgency);

            }
        }
        else {
            var latlng = L.latLng(lat, lng);
            uniqID = createMarker(latlng, false);
            locations.push([uniqID, lat, lng]);
            createCommentRow(user, comment, uniqID, parent, urgency);
        }

    }
}

//These two are only for markers that are being created from the DB
function createInputRow(uniqID, parent) {
    var btn = "<button data-parent='" + parent + "' class='btn btn-success popup-btn reply-button'> </button>";
    setTimeout(
        function () {
            $("#popuptext" + uniqID).keypress(function (e) {
                if (e.which === 13) {
                    commentClick(uniqID);
                }
            });
        }, 50);
    return "

You

<textarea id='popuptext" + uniqID + "' rows= '2' class='form-control popup-textarea'  id='popuptext" + uniqID + "' ></textarea >  " + btn + "

";
}

//Listeners
$(document).ready(function () {
    $(document).on("mouseover", ".open-pin", function () {
        var loc = $(this).data("location").split(' ');
        var lat = loc[0];
        var lng = loc[2];
        var latCollection = locations.map(function (value, index) { return value[1]; });
        var lngCollection = locations.map(function (value, index) { return value[2]; });

        if ($.inArray(parseInt(lat), latCollection) !== -1 && $.inArray(parseInt(lng), lngCollection) !== -1) {

            var latlng = L.latLng(lat, lng);
            var idCollection = locations.map(function (value, index) { return value[0]; });
            var uniqID = idCollection[$.inArray(parseInt(lat), latCollection)];
            markerX = markersArray[markersArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))];
            markerX.setIcon(hoverPin);
        }
    }).on("mouseleave", ".open-pin", function () {
        var loc = $(this).data("location").split(' ');
        var lat = loc[0];
        var lng = loc[2];
        var latCollection = locations.map(function (value, index) { return value[1]; });
        var lngCollection = locations.map(function (value, index) { return value[2]; });

        if ($.inArray(parseInt(lat), latCollection) !== -1 && $.inArray(parseInt(lng), lngCollection) !== -1) {

            var latlng = L.latLng(lat, lng);
            var idCollection = locations.map(function (value, index) { return value[0]; });
            var uniqID = idCollection[$.inArray(parseInt(lat), latCollection)];
            markerX = markersArray[markersArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))];
            markerX.setIcon(customPin);

        }
    }).on("click", ".open-pin", function () {
        var loc = $(this).data("location").split(' ');
        var lat = loc[0];
        var lng = loc[2];
        var latCollection = locations.map(function (value, index) { return value[1]; });
        var lngCollection = locations.map(function (value, index) { return value[2]; });

        if ($.inArray(parseInt(lat), latCollection) !== -1 && $.inArray(parseInt(lng), lngCollection) !== -1) {

            var latlng = L.latLng(lat, lng);
            var idCollection = locations.map(function (value, index) { return value[0]; });
            var uniqID = idCollection[$.inArray(parseInt(lat), latCollection)];
            markerX = markersArray[markersArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))].openPopup();
        }

    });
    $(document).on("keypress", ".popup-textarea", function (e) {
        if (e.which === 13) {
            $('.leaflet-popup-content button').click();
            // prevent duplicate submission
            return false;
        }
    });

})<commit_msg>Improved pins.<commit_after>
//Creates the map
var imageMap = L.map("imageMap", {
    crs: L.CRS.Simple,
    zoomControl: false,
    unitsPer1000px: 1000
});
//Creates custom pin
var customPin = L.icon({
    iconUrl: "../../images/pinNormal.svg",
    shadowUrl: "../../images/pinshadow.svg",
    iconSize: [38, 58], // size of the icon
    shadowSize: [80, 120], // size of the shadow
    iconAnchor: [15, 58], // point of the icon which will correspond to marker's location
    shadowAnchor: [11, 62],  // the same for the shadow
    popupAnchor: [3, -45]
});
var hoverPin = L.icon({
    iconUrl: "../../images/pinLit.svg",
    shadowUrl: "../../images/pinshadow.svg",
    iconSize: [38, 58], // size of the icon
    shadowSize: [80, 120], // size of the shadow
    iconAnchor: [15, 58], // point of the icon which will correspond to marker's location
    shadowAnchor: [11, 62],  // the same for the shadow
    popupAnchor: [3, -45]
});
//Changing map size/location when window is resized
$(window).resize(function () {
    setTimeout(
        function () {
            imageMap.invalidateSize();
        }, 1000);

});
var markerGroup = L.featureGroup().addTo(imageMap);
//Setting the bounds
var height = $("#image-container img").height();
var width = $("#image-container img").width();
var bound = [[1, 1], [height, width]];

//Disabling all the controls for the map
imageMap.fitBounds(bound);
imageMap.dragging.disable();
imageMap.touchZoom.disable();
imageMap.doubleClickZoom.disable();
imageMap.scrollWheelZoom.disable();
imageMap.boxZoom.disable();
imageMap.keyboard.disable();
imageMap.setView([0, 0]);
if (imageMap.tap) imageMap.tap.disable();

//Test marker

//Setting the correct size for the map if the window is resized

imageMap.on('click', function (e) {
    mapOnClick(e);
});

//Button control
$(".leaflet-map-pane").attr("id", "map-pane");
function popupState() {
    if ($("#map-pane").hasClass("hidden")) {
        $("#map-pane").removeClass("hidden");
        imageMap.on('click', function (e) {
            mapOnClick(e);
        });
    }
    else {
        $("#map-pane").addClass("hidden");
        imageMap.off('click');
    }
}
//Array of all the popups and markers
var markersArray = new Array();
var popupsArray = new Array();
var locations = [[]];

//listener for clicks
function mapOnClick(e) {
    createMarker(e.latlng, true);
}
//Creating individual markers. Needed because onClick event sends a different object than createMarkers()
//clickBool determines wether the markers and popups are created by clicking on map or by fetching data from DB
function createMarker(latlng, clickBool) {
    var uniqID = Math.round(new Date().getTime() +(Math.random() * 100));
    var marker = new L.marker(latlng, { icon: customPin }).addTo(markerGroup);
    var popup = new L.Popup();
    //Removes marker if popup is empty
    marker.on('popupclose', function (e) {
        if (($("#popup" + uniqID).html().indexOf("popup-comment")) === -1) {
            imageMap.removeLayer(marker);
        }
    });
    popup.options.autoPan = false;
    popup.options.closeOnClick = true;
    //Focusing the textarea of the popup
    marker.on("click", function () {
        setTimeout(
            function () {
                $("#popuptext" + uniqID).focus();
            }, 50);

    });
    popup.myData = { id: uniqID };
    popupsArray.push(popup);
    markersArray.push(marker);
    locations.push(latlng);
    marker.bindPopup(popup);
    marker.myData = { id: uniqID };
    if (clickBool) {
        popup.setContent(createBtn(uniqID));
        marker.openPopup();
        $(".popup-textarea").focus();
        return;
    }

    return uniqID;
}
//Creates initial text
function createBtn(uniqID) {

    var btn = "<button onclick='commentClick(" + uniqID + ")' class='btn btn-success popup-btn'> </button>";
    Math.floor(Math.random() * 100);
    var strng = "

You

<textarea id='popuptext" + uniqID + "' rows= '2' class='form-control popup-textarea' o id='popuptext" + uniqID + "' ></textarea >
<input type='checkbox' class='urgency-popup'>Urgent
  " + btn + "
 ";

    return strng;
}

//Creating a new comment row
function createCommentRow(user, comment, uniqID, parent, urgency) {

    var urgencyEl; //Urgency element
    if (urgency === 1) {
        urgencyEl = "

";
    }
    else urgencyEl = "";
    var row = "

" + user + "

" + comment + "
" + urgencyEl + "
";
    popupX = popupsArray[popupsArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))];
    popupX.setContent(appendRow(row, uniqID, parent));

}
//Since the whole popup has to be recreated, this method clones it's previous HTML and adds a new comment row
function appendRow(row, uniqID, parent) {
    markerX = markersArray[markersArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))];
    var popupContent = markerX.getPopup().getContent();
    //When changing the HTML of a popup, this code will have to be updated!
    var openingTag = "
";
    var div = $(document.createElement('div'));
    div.addClass("container-fluid popup-comment-container").attr("id", "popup" + uniqID);
    var inputBox = createInputRow(uniqID, parent);

    if (popupContent === undefined) {
        $(row).appendTo(div);

    }
    else {
        $(popupContent.slice(openingTag.length, popupContent.length - 3 - inputBox.length)).appendTo(div);
        $(row).appendTo(div);

    }
    //A new input section has to be created each time to keep things consistent, otherwise it messes up the HTML
    return openingTag + div.html() + "
" + inputBox;

}

//Creates markers from existing comments in the DB
function createMarkers(comment, user, lat, lng, parent,urgency, reload) {
    if (lat !== 0 && lng !== 0) {
        var latCollection = locations.map(function (value, index) { return value[1]; });
        var lngCollection = locations.map(function (value, index) { return value[2]; });
        var uniqID;
        if ($.inArray(lat, latCollection) !== -1 && $.inArray(lng, lngCollection) !== -1) {

            if ($.inArray(lat, latCollection) === $.inArray(lng, lngCollection)) {
                var idCollection = locations.map(function (value, index) { return value[0]; });
                uniqID = idCollection[$.inArray(lat, latCollection)];
                createCommentRow(user, comment, uniqID, parent,urgency);

            }
        }
        else {
            var latlng = L.latLng(lat, lng);
            uniqID = createMarker(latlng, false);
            locations.push([uniqID, lat, lng]);
            createCommentRow(user, comment, uniqID, parent, urgency);
        }

    }
}

//These two are only for markers that are being created from the DB
function createInputRow(uniqID, parent) {
    var btn = "<button data-parent='" + parent + "' class='btn btn-success popup-btn reply-button'> </button>";
    setTimeout(
        function () {
            $("#popuptext" + uniqID).keypress(function (e) {
                if (e.which === 13) {
                    commentClick(uniqID);
                }
            });
        }, 50);
    return "

You

<textarea id='popuptext" + uniqID + "' rows= '2' class='form-control popup-textarea'  id='popuptext" + uniqID + "' ></textarea >  " + btn + "

";
}

//Listeners
$(document).ready(function () {
    $(document).on("mouseover", ".open-pin", function () {
        var loc = $(this).data("location").split(' ');
        var lat = loc[0];
        var lng = loc[2];
        var latCollection = locations.map(function (value, index) { return value[1]; });
        var lngCollection = locations.map(function (value, index) { return value[2]; });

        if ($.inArray(parseInt(lat), latCollection) !== -1 && $.inArray(parseInt(lng), lngCollection) !== -1) {

            var latlng = L.latLng(lat, lng);
            var idCollection = locations.map(function (value, index) { return value[0]; });
            var uniqID = idCollection[$.inArray(parseInt(lat), latCollection)];
            markerX = markersArray[markersArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))];
            markerX.setIcon(hoverPin);
        }

        }).on("mouseleave", ".open-pin", function () {
        var loc = $(this).data("location").split(' ');
        var lat = loc[0];
        var lng = loc[2];
        var latCollection = locations.map(function (value, index) { return value[1]; });
        var lngCollection = locations.map(function (value, index) { return value[2]; });

        if ($.inArray(parseInt(lat), latCollection) !== -1 && $.inArray(parseInt(lng), lngCollection) !== -1) {

            var latlng = L.latLng(lat, lng);
            var idCollection = locations.map(function (value, index) { return value[0]; });
            var uniqID = idCollection[$.inArray(parseInt(lat), latCollection)];
            markerX = markersArray[markersArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))];
            markerX.setIcon(customPin);

        }
        }).on("click", ".open-pin", function () {

            var clickedComment = $(this);
            if (clickedComment.context.text === "Close pin") {

                $(".leaflet-popup-close-button")[0].click();
                $(this).text("Open pin");
            }
            else {
                $("#map-pane").removeClass("hidden");
                $(this).text("Close pin");

                var loc = $(this).data("location").split(' ');
                var lat = loc[0];
                var lng = loc[2];
                var latCollection = locations.map(function (value, index) { return value[1]; });
                var lngCollection = locations.map(function (value, index) { return value[2]; });

                if ($.inArray(parseInt(lat), latCollection) !== -1 && $.inArray(parseInt(lng), lngCollection) !== -1) {

                    var latlng = L.latLng(lat, lng);
                    var idCollection = locations.map(function (value, index) { return value[0]; });
                    var uniqID = idCollection[$.inArray(parseInt(lat), latCollection)];
                    markerX = markersArray[markersArray.findIndex(x => parseInt(x.myData.id) === parseInt(uniqID))].openPopup();
                }
            }

            $(".open-pin").each(function (index) {
                if ($(clickedComment).attr("id") !== $(this).attr("id")) {
                    $(this).text("Open pin");
                }
            });

        });

    $(document).on("keypress", ".popup-textarea", function (e) {
        if (e.which === 13) {
            $('.leaflet-popup-content button').click();
            // prevent duplicate submission
            return false;
        }
    });
})<|endoftext|>


<commit_before>const { dirname, resolve } = require('path');

const Storage = function () {};
Storage.prototype = {};

/**
 * @memberOf Jymfony.Component.Autoloader
 */
class DescriptorStorage {
    /**
     * Constructor.
     *
     * @param {Jymfony.Component.Autoloader.ClassLoader} classLoader
     * @param {string} filename
     * @param {Storage} storage
     */
    constructor(classLoader, filename = undefined, storage = new Storage()) {
        /**
         * @type {Jymfony.Component.Autoloader.ClassLoader}
         *
         * @private
         */
        this._classLoader = classLoader;

        /**
         * @type {string}
         *
         * @private
         */
        this._filename = filename;

        /**
         * @type {Storage}
         *
         * @private
         */
        this._storage = storage;
    }

    /**
     * Sets a new file to be processed.
     *
     * @param {string} filename
     *
     * @returns {Jymfony.Component.Autoloader.DescriptorStorage}
     */
    setFile(filename) {
        return new DescriptorStorage(this._classLoader, resolve(filename), this._storage);
    }

    /**
     * Registers a decorator descriptor.
     *
     * @param {DecoratorDescriptor} descriptor
     * @param {Identifier} alias
     */
    register(descriptor, alias = descriptor.name) {
        const name = alias.name;
        this._storage[this._filename + name] = descriptor;
    }

    /**
     * Register decorators as exported by export * from ..
     *
     * @param {string} source
     */
    registerAllFrom(source) {
        try {
            source = require.resolve(source, { paths: [ dirname(this._filename) ] });
        } catch (e) {
            return;
        }

        this._classLoader.getCode(source);

        for (const [ name, descriptor ] of __jymfony.getEntries(this._storage)) {
            if (name.startsWith(source + '@')) {
                this._storage[name.replace(new RegExp('^' + __jymfony.regex_quote(source)), this._filename)] = descriptor;
            }
        }
    }

    /**
     * Imports a decorator descriptor.
     *
     * @param {string} source
     * @param {string} descriptorName
     *
     * @returns {DecoratorDescriptor}
     */
    import(source, descriptorName) {
        source = require.resolve(source, { paths: [ dirname(this._filename) ] });
        this._classLoader.getCode(source);

        return this._storage[source + descriptorName];
    }
}

module.exports = DescriptorStorage;
<commit_msg>[Autoloader] throw error if decorator import fails<commit_after>const { dirname, resolve } = require('path');

const Storage = function () {};
Storage.prototype = {};

/**
 * @memberOf Jymfony.Component.Autoloader
 */
class DescriptorStorage {
    /**
     * Constructor.
     *
     * @param {Jymfony.Component.Autoloader.ClassLoader} classLoader
     * @param {string} filename
     * @param {Storage} storage
     */
    constructor(classLoader, filename = undefined, storage = new Storage()) {
        /**
         * @type {Jymfony.Component.Autoloader.ClassLoader}
         *
         * @private
         */
        this._classLoader = classLoader;

        /**
         * @type {string}
         *
         * @private
         */
        this._filename = filename;

        /**
         * @type {Storage}
         *
         * @private
         */
        this._storage = storage;
    }

    /**
     * Sets a new file to be processed.
     *
     * @param {string} filename
     *
     * @returns {Jymfony.Component.Autoloader.DescriptorStorage}
     */
    setFile(filename) {
        return new DescriptorStorage(this._classLoader, resolve(filename), this._storage);
    }

    /**
     * Registers a decorator descriptor.
     *
     * @param {DecoratorDescriptor} descriptor
     * @param {Identifier} alias
     */
    register(descriptor, alias = descriptor.name) {
        const name = alias.name;
        this._storage[this._filename + name] = descriptor;
    }

    /**
     * Register decorators as exported by export * from ..
     *
     * @param {string} source
     */
    registerAllFrom(source) {
        try {
            source = require.resolve(source, { paths: [ dirname(this._filename) ] });
        } catch (e) {
            return;
        }

        this._classLoader.getCode(source);

        for (const [ name, descriptor ] of __jymfony.getEntries(this._storage)) {
            if (name.startsWith(source + '@')) {
                this._storage[name.replace(new RegExp('^' + __jymfony.regex_quote(source)), this._filename)] = descriptor;
            }
        }
    }

    /**
     * Imports a decorator descriptor.
     *
     * @param {string} source
     * @param {string} descriptorName
     *
     * @returns {DecoratorDescriptor}
     */
    import(source, descriptorName) {
        source = require.resolve(source, { paths: [ dirname(this._filename) ] });
        this._classLoader.getCode(source);

        const key = source + descriptorName;
        if (undefined === this._storage[key]) {
            throw new Error(__jymfony.sprintf('Cannot find decorator %s in "%s"', descriptorName, source));
        }

        return this._storage[key];
    }
}

module.exports = DescriptorStorage;
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {
  var OptionsPage = options.OptionsPage;

  // The offset of the first profile in either the address list or the credit
  // card list. Consists of the header and the horizontal rule.
  const addressOffset = 2;
  const creditCardOffset = 3;

  /////////////////////////////////////////////////////////////////////////////
  // AutoFillOptions class:
  //
  // TODO(jhawkins): Replace <select> with a DOMUI List.

  /**
   * Encapsulated handling of AutoFill options page.
   * @constructor
   */
  function AutoFillOptions() {
    this.numAddresses = 0;
    this.numCreditCards = 0;
    this.activeNavTab = null;
    this.addressIDs = null;
    this.creditCardIDs = null;
    OptionsPage.call(this, 'autoFillOptions',
                     templateData.autoFillOptionsTitle,
                     'autoFillOptionsPage');
  }

  cr.addSingletonGetter(AutoFillOptions);

  AutoFillOptions.prototype = {
    __proto__: OptionsPage.prototype,

    initializePage: function() {
      OptionsPage.prototype.initializePage.call(this);

      var self = this;
      $('profileList').onchange = function(event) {
        self.updateButtonState_();
      };
      $('addAddressButton').onclick = function(event) {
        self.showAddAddressOverlay_();
      };
      $('addCreditCardButton').onclick = function(event) {
        self.showAddCreditCardOverlay_();
      };
      $('autoFillEditButton').onclick = function(event) {
        self.editProfile_();
      };
      $('autoFillRemoveButton').onclick = function(event) {
        self.removeProfile_();
      };

      Preferences.getInstance().addEventListener('autofill.enabled',
          this.updateEnabledState_.bind(this));
    },

    /**
     * Sets the enabled state of the button controls based on the current state
     * of the |autoFillEnabled| checkbox.
     * @private
     */
    updateEnabledState_: function() {
      var disabled = !$('autoFillEnabled').checked;
      $('addAddressButton').disabled = disabled;
      $('addCreditCardButton').disabled = disabled;
      $('autoFillEditButton').disabled = disabled;
      $('autoFillRemoveButton').disabled = disabled;
    },

    /**
     * Shows the 'Add address' overlay, specifically by loading the
     * 'Edit address' overlay, emptying the input fields and modifying the
     * overlay title.
     * @private
     */
    showAddAddressOverlay_: function() {
      var title = localStrings.getString('addAddressTitle');
      AutoFillEditAddressOverlay.setTitle(title);
      AutoFillEditAddressOverlay.clearInputFields();
      OptionsPage.showOverlay('autoFillEditAddressOverlay');
    },

    /**
     * Shows the 'Edit address' overlay, using the data in |address| to fill the
     * input fields. |address| is a list with one item, an associative array
     * that contains the address data.
     * @private
     */
    showEditAddressOverlay_: function(address) {
      var title = localStrings.getString('editAddressTitle');
      AutoFillEditAddressOverlay.setTitle(title);
      AutoFillEditAddressOverlay.loadAddress(address[0]);
      OptionsPage.showOverlay('autoFillEditAddressOverlay');
    },

    /**
     * Shows the 'Add credit card' overlay, specifically by loading the
     * 'Edit credit card' overlay, emptying the input fields and modifying the
     * overlay title.
     * @private
     */
    showAddCreditCardOverlay_: function() {
      var title = localStrings.getString('addCreditCardTitle');
      AutoFillEditCreditCardOverlay.setTitle(title);
      AutoFillEditCreditCardOverlay.clearInputFields();
      OptionsPage.showOverlay('autoFillEditCreditCardOverlay');
    },

    /**
     * Shows the 'Edit credit card' overlay, using the data in |credit_card| to
     * fill the input fields. |address| is a list with one item, an associative
     * array that contains the credit card data.
     * @private
     */
    showEditCreditCardOverlay_: function(creditCard) {
      var title = localStrings.getString('editCreditCardTitle');
      AutoFillEditCreditCardOverlay.setTitle(title);
      AutoFillEditCreditCardOverlay.loadCreditCard(creditCard[0]);
      OptionsPage.showOverlay('autoFillEditCreditCardOverlay');
    },

    /**
     * Resets the address list. This method leaves the header and horizontal
     * rule unchanged.
     * @private
     */
    resetAddresses_: function() {
      var profiles = $('profileList');
      for (var i = 0; i <  this.numAddresses; ++i)
        profiles.remove(addressOffset);
      this.numAddresses = 0;
    },

    /**
     * Resets the credit card list. This method leaves the header and horizontal
     * rule unchanged.
     * @private
     */
    resetCreditCards_: function() {
      var profiles = $('profileList');
      var offset = this.numAddresses + addressOffset + creditCardOffset;
      for (var i = 0; i <  this.numCreditCards; ++i)
        profiles.remove(offset);
      this.numCreditCards = 0;
    },

    /**
     * Updates the address list with the given entries.
     * @private
     * @param {Array} address List of addresses.
     */
    updateAddresses_: function(addresses) {
      this.resetAddresses_();
      var profileList = $('profileList');
      var blankAddress = profileList.options[addressOffset];
      this.numAddresses = addresses.length;
      this.addressIDs = new Array(this.numAddresses);
      for (var i = 0; i < this.numAddresses; i++) {
        var address = addresses[i];
        var option = new Option(address['label']);
        this.addressIDs[i] = address['uniqueID'];
        profileList.add(option, blankAddress);
      }

      AutoFillEditCreditCardOverlay.setBillingAddresses(addresses);
      this.updateButtonState_();
    },

    /**
     * Updates the credit card list with the given entries.
     * @private
     * @param {Array} creditCards List of credit cards.
     */
    updateCreditCards_: function(creditCards) {
      this.resetCreditCards_();
      var profileList = $('profileList');
      this.numCreditCards = creditCards.length;
      this.creditCardIDs = new Array(this.numCreditCards);
      for (var i = 0; i < this.numCreditCards; i++) {
        var creditCard = creditCards[i];
        var option = new Option(creditCard['label']);
        this.creditCardIDs[i] = creditCard['uniqueID'];
        profileList.add(option, null);
      }

      this.updateButtonState_();
    },

    /**
     * Sets the enabled state of the AutoFill Edit and Remove buttons based on
     * the current selection in the profile list.
     * @private
     */
    updateButtonState_: function() {
      $('autoFillRemoveButton').disabled = $('autoFillEditButton').disabled =
          ($('profileList').selectedIndex == -1);
    },

    /**
     * Calls into the browser to load either an address or a credit card,
     * depending on the selected index.  The browser calls back into either
     * editAddress() or editCreditCard() which show their respective editors.
     * @private
     */
    editProfile_: function() {
      var idx = $('profileList').selectedIndex;
      if ((profileIndex = this.getAddressIndex_(idx)) != -1) {
        chrome.send('editAddress', [String(this.addressIDs[profileIndex])]);
      } else if ((profileIndex = this.getCreditCardIndex_(idx)) != -1) {
        chrome.send('editCreditCard',
                    [String(this.creditCardIDs[profileIndex])]);
      }
    },

    /**
     * Removes the currently selected profile, whether it's an address or a
     * credit card.
     * @private
     */
    removeProfile_: function() {
      var idx = $('profileList').selectedIndex;
      if ((profileIndex = this.getAddressIndex_(idx)) != -1)
        chrome.send('removeAddress', [String(this.addressIDs[profileIndex])]);
      else if ((profileIndex = this.getCreditCardIndex_(idx)) != -1)
        chrome.send('removeCreditCard',
                    [String(this.creditCardIDs[profileIndex])]);
    },

    /**
     * Returns the index into the address list based on |index|, the index into
     * the select control. Returns -1 if this is not an address index.
     * @private
     */
    getAddressIndex_: function(index) {
      index -= addressOffset;
      if (index >= 0 && index < this.numAddresses)
        return index;

      return -1;
    },

    /**
     * Returns the index into the credit card list based on |index|, the index
     * into the select control. Returns -1 if this is not a credit card index.
     * @private
     */
    getCreditCardIndex_: function(index) {
      index -= addressOffset + this.numAddresses + creditCardOffset;
      if (index >= 0 && index < this.numCreditCards)
        return index;

      return -1;
    },

    /**
     * Returns true if |index| points to a credit card profile.
     * @private
     */
    profileIndexIsCreditCard_: function(index) {
      index -= addressOffset + this.numAddresses + creditCardOffset;
      return (index >= 0 && index < this.numCreditCards);
    }
  };

  AutoFillOptions.updateAddresses = function(addresses) {
    AutoFillOptions.getInstance().updateAddresses_(addresses);
  };

  AutoFillOptions.editAddress = function(address) {
    AutoFillOptions.getInstance().showEditAddressOverlay_(address);
  };

  AutoFillOptions.updateCreditCards = function(creditCards) {
    AutoFillOptions.getInstance().updateCreditCards_(creditCards);
  };

  AutoFillOptions.editCreditCard = function(creditCard) {
    AutoFillOptions.getInstance().showEditCreditCardOverlay_(creditCard);
  };

  // Export
  return {
    AutoFillOptions: AutoFillOptions
  };

});

<commit_msg>DOMUI: Fix a bug in the AutoFill tab.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {
  var OptionsPage = options.OptionsPage;

  // The offset of the first profile in either the address list or the credit
  // card list. Consists of the header and the horizontal rule.
  const addressOffset = 2;
  const creditCardOffset = 3;

  /////////////////////////////////////////////////////////////////////////////
  // AutoFillOptions class:
  //
  // TODO(jhawkins): Replace <select> with a DOMUI List.

  /**
   * Encapsulated handling of AutoFill options page.
   * @constructor
   */
  function AutoFillOptions() {
    this.numAddresses = 0;
    this.numCreditCards = 0;
    this.activeNavTab = null;
    this.addressIDs = null;
    this.creditCardIDs = null;
    OptionsPage.call(this, 'autoFillOptions',
                     templateData.autoFillOptionsTitle,
                     'autoFillOptionsPage');
  }

  cr.addSingletonGetter(AutoFillOptions);

  AutoFillOptions.prototype = {
    __proto__: OptionsPage.prototype,

    initializePage: function() {
      OptionsPage.prototype.initializePage.call(this);

      var self = this;
      $('profileList').onchange = function(event) {
        self.updateButtonState_();
      };
      $('addAddressButton').onclick = function(event) {
        self.showAddAddressOverlay_();
      };
      $('addCreditCardButton').onclick = function(event) {
        self.showAddCreditCardOverlay_();
      };
      $('autoFillEditButton').onclick = function(event) {
        self.editProfile_();
      };
      $('autoFillRemoveButton').onclick = function(event) {
        self.removeProfile_();
      };

      Preferences.getInstance().addEventListener('autofill.enabled',
          this.updateButtonState_.bind(this));
    },

    /**
     * Shows the 'Add address' overlay, specifically by loading the
     * 'Edit address' overlay, emptying the input fields and modifying the
     * overlay title.
     * @private
     */
    showAddAddressOverlay_: function() {
      var title = localStrings.getString('addAddressTitle');
      AutoFillEditAddressOverlay.setTitle(title);
      AutoFillEditAddressOverlay.clearInputFields();
      OptionsPage.showOverlay('autoFillEditAddressOverlay');
    },

    /**
     * Shows the 'Edit address' overlay, using the data in |address| to fill the
     * input fields. |address| is a list with one item, an associative array
     * that contains the address data.
     * @private
     */
    showEditAddressOverlay_: function(address) {
      var title = localStrings.getString('editAddressTitle');
      AutoFillEditAddressOverlay.setTitle(title);
      AutoFillEditAddressOverlay.loadAddress(address[0]);
      OptionsPage.showOverlay('autoFillEditAddressOverlay');
    },

    /**
     * Shows the 'Add credit card' overlay, specifically by loading the
     * 'Edit credit card' overlay, emptying the input fields and modifying the
     * overlay title.
     * @private
     */
    showAddCreditCardOverlay_: function() {
      var title = localStrings.getString('addCreditCardTitle');
      AutoFillEditCreditCardOverlay.setTitle(title);
      AutoFillEditCreditCardOverlay.clearInputFields();
      OptionsPage.showOverlay('autoFillEditCreditCardOverlay');
    },

    /**
     * Shows the 'Edit credit card' overlay, using the data in |credit_card| to
     * fill the input fields. |address| is a list with one item, an associative
     * array that contains the credit card data.
     * @private
     */
    showEditCreditCardOverlay_: function(creditCard) {
      var title = localStrings.getString('editCreditCardTitle');
      AutoFillEditCreditCardOverlay.setTitle(title);
      AutoFillEditCreditCardOverlay.loadCreditCard(creditCard[0]);
      OptionsPage.showOverlay('autoFillEditCreditCardOverlay');
    },

    /**
     * Resets the address list. This method leaves the header and horizontal
     * rule unchanged.
     * @private
     */
    resetAddresses_: function() {
      var profiles = $('profileList');
      for (var i = 0; i <  this.numAddresses; ++i)
        profiles.remove(addressOffset);
      this.numAddresses = 0;
    },

    /**
     * Resets the credit card list. This method leaves the header and horizontal
     * rule unchanged.
     * @private
     */
    resetCreditCards_: function() {
      var profiles = $('profileList');
      var offset = this.numAddresses + addressOffset + creditCardOffset;
      for (var i = 0; i <  this.numCreditCards; ++i)
        profiles.remove(offset);
      this.numCreditCards = 0;
    },

    /**
     * Updates the address list with the given entries.
     * @private
     * @param {Array} address List of addresses.
     */
    updateAddresses_: function(addresses) {
      this.resetAddresses_();
      var profileList = $('profileList');
      var blankAddress = profileList.options[addressOffset];
      this.numAddresses = addresses.length;
      this.addressIDs = new Array(this.numAddresses);
      for (var i = 0; i < this.numAddresses; i++) {
        var address = addresses[i];
        var option = new Option(address['label']);
        this.addressIDs[i] = address['uniqueID'];
        profileList.add(option, blankAddress);
      }

      AutoFillEditCreditCardOverlay.setBillingAddresses(addresses);
      this.updateButtonState_();
    },

    /**
     * Updates the credit card list with the given entries.
     * @private
     * @param {Array} creditCards List of credit cards.
     */
    updateCreditCards_: function(creditCards) {
      this.resetCreditCards_();
      var profileList = $('profileList');
      this.numCreditCards = creditCards.length;
      this.creditCardIDs = new Array(this.numCreditCards);
      for (var i = 0; i < this.numCreditCards; i++) {
        var creditCard = creditCards[i];
        var option = new Option(creditCard['label']);
        this.creditCardIDs[i] = creditCard['uniqueID'];
        profileList.add(option, null);
      }

      this.updateButtonState_();
    },

    /**
     * Sets the enabled state of the AutoFill Add Address and Credit Card
     * buttons on the current state of the |autoFillEnabled| checkbox.
     * Sets the enabled state of the AutoFill Edit and Remove buttons based on
     * the current selection in the profile list.
     * @private
     */
    updateButtonState_: function() {
      var disabled = !$('autoFillEnabled').checked;
      $('addAddressButton').disabled = disabled;
      $('addCreditCardButton').disabled = disabled;
      $('autoFillRemoveButton').disabled = $('autoFillEditButton').disabled =
          disabled || ($('profileList').selectedIndex == -1);
    },

    /**
     * Calls into the browser to load either an address or a credit card,
     * depending on the selected index.  The browser calls back into either
     * editAddress() or editCreditCard() which show their respective editors.
     * @private
     */
    editProfile_: function() {
      var idx = $('profileList').selectedIndex;
      if ((profileIndex = this.getAddressIndex_(idx)) != -1) {
        chrome.send('editAddress', [String(this.addressIDs[profileIndex])]);
      } else if ((profileIndex = this.getCreditCardIndex_(idx)) != -1) {
        chrome.send('editCreditCard',
                    [String(this.creditCardIDs[profileIndex])]);
      }
    },

    /**
     * Removes the currently selected profile, whether it's an address or a
     * credit card.
     * @private
     */
    removeProfile_: function() {
      var idx = $('profileList').selectedIndex;
      if ((profileIndex = this.getAddressIndex_(idx)) != -1)
        chrome.send('removeAddress', [String(this.addressIDs[profileIndex])]);
      else if ((profileIndex = this.getCreditCardIndex_(idx)) != -1)
        chrome.send('removeCreditCard',
                    [String(this.creditCardIDs[profileIndex])]);
    },

    /**
     * Returns the index into the address list based on |index|, the index into
     * the select control. Returns -1 if this is not an address index.
     * @private
     */
    getAddressIndex_: function(index) {
      index -= addressOffset;
      if (index >= 0 && index < this.numAddresses)
        return index;

      return -1;
    },

    /**
     * Returns the index into the credit card list based on |index|, the index
     * into the select control. Returns -1 if this is not a credit card index.
     * @private
     */
    getCreditCardIndex_: function(index) {
      index -= addressOffset + this.numAddresses + creditCardOffset;
      if (index >= 0 && index < this.numCreditCards)
        return index;

      return -1;
    },

    /**
     * Returns true if |index| points to a credit card profile.
     * @private
     */
    profileIndexIsCreditCard_: function(index) {
      index -= addressOffset + this.numAddresses + creditCardOffset;
      return (index >= 0 && index < this.numCreditCards);
    }
  };

  AutoFillOptions.updateAddresses = function(addresses) {
    AutoFillOptions.getInstance().updateAddresses_(addresses);
  };

  AutoFillOptions.editAddress = function(address) {
    AutoFillOptions.getInstance().showEditAddressOverlay_(address);
  };

  AutoFillOptions.updateCreditCards = function(creditCards) {
    AutoFillOptions.getInstance().updateCreditCards_(creditCards);
  };

  AutoFillOptions.editCreditCard = function(creditCard) {
    AutoFillOptions.getInstance().showEditCreditCardOverlay_(creditCard);
  };

  // Export
  return {
    AutoFillOptions: AutoFillOptions
  };

});

<|endoftext|>


<commit_before>import defaultOptions from '@/config/i18next';
import { ipcRenderer } from 'electron';
import i18next from 'i18next';

if (!i18next.isInitialized) {
  i18next.init({
    fallbackLng: defaultOptions.fallbackLng,
    whitelist: defaultOptions.whitelist,
    ns: defaultOptions.ns,
    defaultNS: defaultOptions.defaultNS,
  });
}

function changeLanguage({ lng, resources }) {
  for (const lng of Object.keys(resources)) {
    const languageObject = resources[lng];
    for (const namespace of Object.keys(languageObject)) {
      const resource = languageObject[namespace];
      if (!i18next.hasResourceBundle(lng, namespace)) {
        i18next.addResourceBundle(lng, namespace, resource);
      }
    }
  }

  i18next.changeLanguage(lng);
}

ipcRenderer.on('language-changed', (event, message) => {
  changeLanguage(message);
});

const initialLanguageData = ipcRenderer.sendSync('get-initial-language-data');
changeLanguage(initialLanguageData);

export default class i18n {
  static getMessage(key, ...args) {
    return i18next.t(key, ...args);
  }
}
<commit_msg>Cache translations in the render process<commit_after>import defaultOptions from '@/config/i18next';
import { ipcRenderer } from 'electron';
import i18next from 'i18next';
import { memoize } from '@/utils';

if (!i18next.isInitialized) {
  i18next.init({
    fallbackLng: defaultOptions.fallbackLng,
    whitelist: defaultOptions.whitelist,
    ns: defaultOptions.ns,
    defaultNS: defaultOptions.defaultNS,
  });
}

function changeLanguage({ lng, resources }) {
  for (const lng of Object.keys(resources)) {
    const languageObject = resources[lng];
    for (const namespace of Object.keys(languageObject)) {
      const resource = languageObject[namespace];
      if (!i18next.hasResourceBundle(lng, namespace)) {
        i18next.addResourceBundle(lng, namespace, resource);
      }
    }
  }

  i18next.changeLanguage(lng);
}

ipcRenderer.on('language-changed', (event, message) => {
  changeLanguage(message);
});

const initialLanguageData = ipcRenderer.sendSync('get-initial-language-data');
changeLanguage(initialLanguageData);

export default {
  getMessage: memoize((key, ...args) => i18next.t(key, ...args)),
};
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import HTTPStatus from 'http-status'
import Head from 'next-server/head'

export default class Error extends React.Component {
  static getInitialProps ({ res, err }) {
    const statusCode = res ? res.statusCode : (err ? err.statusCode : null)
    return { statusCode }
  }

  render () {
    const { statusCode } = this.props
    const title = statusCode === 404
      ? 'This page could not be found'
      : HTTPStatus[statusCode] || 'An unexpected error has occurred'

    return

        <meta name='viewport' content='width=device-width, initial-scale=1.0' />
        <title>{statusCode}: {title}</title>


<commit_before>'use strict';

var nock    = require('../.')
  , nockBack= nock.back
  , tap     = require('tap')
  , http    = require('http')
  , fs      = require('fs')
  , exists  = fs.existsSync;

nock.enableNetConnect();

var originalMode = nockBack.currentMode;

function testNock (t) {
  var dataCalled = false;

  var scope = nock('http://www.google.com')
    .get('/')
    .reply(200, "Hello World!");

  var req = http.request({
      host: "www.google.com"
    , path: '/'
    , port: 80
    }, function(res) {

      t.equal(res.statusCode, 200);
      res.once('end', function() {
          t.ok(dataCalled);
          scope.done();
          t.end();
        });
      res.on('data', function(data) {
          dataCalled = true;
          t.ok(data instanceof Buffer, "data should be buffer");
          t.equal(data.toString(), "Hello World!", "response should match");
        });
    });

  req.end();
}

function nockBackWithFixture (t, scopesLoaded) {
  var scopesLength = scopesLoaded ? 1 : 0;

  nockBack('goodRequest.json', function (done) {
    t.true(this.scopes.length === scopesLength);
    http.get('http://www.google.com').end();
    this.assertScopesFinished();
    done();
    t.end();
  });
}

function setOriginalModeOnEnd(t, nockBack) {
  t.once('end', function() {
    nockBack.setMode(originalMode);
  });
}

tap.test('nockBack throws an exception when fixtures is not set', function (t) {

  try {
    nockBack();
  } catch (e) {
    t.ok(true, 'excpected exception');
    t.end();
    return;
  }

  t.fail(true, false, 'test should have ended');

});

tap.test('nockBack wild tests', function (nw) {

  //  Manually disable net connectivity to confirm that dryrun enables it.
  nock.disableNetConnect();

  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('wild');

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('nock back doesn\'t do anything', {skip: process.env.AIRPLANE}, function (t) {
    nockBackWithFixture(t, false);
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});

tap.test('nockBack dryrun tests', function (nw) {

  //  Manually disable net connectivity to confirm that dryrun enables it.
  nock.disableNetConnect();

  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('dryrun');

  nw.test('goes to internet even when no nockBacks are running', {skip: process.env.AIRPLANE}, function(t) {
    var req = http.request({
        host: "www.amazon.com"
      , path: '/'
      , port: 80
      }, function(res) {

        res.on('data', function() {
          //node v 0.10 requires this listener
        });
        t.ok([200, 301, 302].indexOf(res.statusCode) >= 0);
        t.end();

      });

    req.on('error', function(err) {

      //  This should never happen.
      t.assert(false);
      t.end();

    });

    req.end();
  });

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('uses recorded fixtures', function (t) {
    nockBackWithFixture(t, true);
  });

  nw.test('goes to internet, doesn\'t record new fixtures', {skip: process.env.AIRPLANE}, function (t) {
    var dataCalled = false;

    var fixture = 'someDryrunFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      var req = http.request({
          host: "www.amazon.com"
        , path: '/'
        , port: 80
        }, function(res) {

          t.ok([200, 301, 302].indexOf(res.statusCode) >= 0);
          res.on('end', function() {
            var doneFails = false;

            t.ok(dataCalled);
            try {
              done();
              t.false(exists(fixtureLoc));
              scope.done();
            } catch(err) {
              doneFails = true;
            }
            t.ok(doneFails);
            t.end();
          });

          res.on('data', function(data) {
            dataCalled = true;
          });

        });

      req.once('error', function(err) {
        if (err.code !== 'ECONNREFUSED') {
          throw err;
        }
        t.end();
      });

      req.end();
    });
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});

tap.test('nockBack record tests', function (nw) {
  nockBack.setMode('record');

  nw.test('it records when configured correctly', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };

    var fixture = 'someFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      fs.unlinkSync(fixtureLoc);
      t.end();
    });

  });

  //Adding this test because there was an issue when not calling
  //nock.activate() after calling nock.restore()
  nw.test('it can record twice', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };
    var fixture = 'someFixture2.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;
    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      fs.unlinkSync(fixtureLoc);
      t.end();
    });

  });

  nw.test('it shouldn\'t allow outside calls', function (t) {

    var fixture = 'wrongUri.json';

    nockBack(fixture, function (done) {

      http.get('http://www.amazon.com', function(res) {
        throw "should not request this";
      }).on('error', function(err) {
        t.equal(err.message, 'Nock: Not allow net connect for "www.amazon.com:80/"');
        done();
        t.end();
      });

    });

  });

  nw.test('it loads your recorded tests', function (t) {

    nockBack('goodRequest.json', function (done) {
      t.true(this.scopes.length > 0);
      http.get('http://www.google.com').end();
      this.assertScopesFinished();
      done();
      t.end();
    });

  });

  nw.test('it can filter after recording', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };

    var fixture = 'filteredFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    var afterRecord = function(scopes) {
       // You would do some filtering here, but for this test we'll just return an empty array
      return [];
    }

    nockBack(fixture, {afterRecord: afterRecord}, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      nockBack(fixture, function (done) {
        t.true(this.scopes.length === 0);
        done();

        fs.unlinkSync(fixtureLoc);
        t.end();
      });
    });
  });

  nw.end();

  setOriginalModeOnEnd(nw, nockBack);
});

tap.test('nockBack lockdown tests', function (nw) {
  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('lockdown');

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('nock back loads scope', function (t) {
    nockBackWithFixture(t, true);
  });

  nw.test('no unnocked http calls work', function (t) {
    var req = http.request({
        host: "google.com"
      , path: '/'
      }, function(res) {
        throw new Error('should not come here!');
      });

    req.on('error', function (err) {
      t.equal(err.message.trim(), 'Nock: Not allow net connect for "google.com:80/"');
      t.end();
    });

    req.end();
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});
<commit_msg>www.amazon.com does not return any data<commit_after>'use strict';

var nock    = require('../.')
  , nockBack= nock.back
  , tap     = require('tap')
  , http    = require('http')
  , fs      = require('fs')
  , exists  = fs.existsSync;

nock.enableNetConnect();

var originalMode = nockBack.currentMode;

function testNock (t) {
  var dataCalled = false;

  var scope = nock('http://www.google.com')
    .get('/')
    .reply(200, "Hello World!");

  var req = http.request({
      host: "www.google.com"
    , path: '/'
    , port: 80
    }, function(res) {

      t.equal(res.statusCode, 200);
      res.once('end', function() {
          t.ok(dataCalled);
          scope.done();
          t.end();
        });
      res.on('data', function(data) {
          dataCalled = true;
          t.ok(data instanceof Buffer, "data should be buffer");
          t.equal(data.toString(), "Hello World!", "response should match");
        });
    });

  req.end();
}

function nockBackWithFixture (t, scopesLoaded) {
  var scopesLength = scopesLoaded ? 1 : 0;

  nockBack('goodRequest.json', function (done) {
    t.true(this.scopes.length === scopesLength);
    http.get('http://www.google.com').end();
    this.assertScopesFinished();
    done();
    t.end();
  });
}

function setOriginalModeOnEnd(t, nockBack) {
  t.once('end', function() {
    nockBack.setMode(originalMode);
  });
}

tap.test('nockBack throws an exception when fixtures is not set', function (t) {

  try {
    nockBack();
  } catch (e) {
    t.ok(true, 'excpected exception');
    t.end();
    return;
  }

  t.fail(true, false, 'test should have ended');

});

tap.test('nockBack wild tests', function (nw) {

  //  Manually disable net connectivity to confirm that dryrun enables it.
  nock.disableNetConnect();

  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('wild');

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('nock back doesn\'t do anything', {skip: process.env.AIRPLANE}, function (t) {
    nockBackWithFixture(t, false);
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});

tap.test('nockBack dryrun tests', function (nw) {

  //  Manually disable net connectivity to confirm that dryrun enables it.
  nock.disableNetConnect();

  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('dryrun');

  nw.test('goes to internet even when no nockBacks are running', {skip: process.env.AIRPLANE}, function(t) {
    var req = http.request({
        host: "www.amazon.com"
      , path: '/'
      , port: 80
      }, function(res) {

        res.on('data', function() {
          //node v 0.10 requires this listener
        });
        t.ok([200, 301, 302].indexOf(res.statusCode) >= 0);
        t.end();

      });

    req.on('error', function(err) {

      //  This should never happen.
      t.assert(false);
      t.end();

    });

    req.end();
  });

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('uses recorded fixtures', function (t) {
    nockBackWithFixture(t, true);
  });

  nw.test('goes to internet, doesn\'t record new fixtures', {skip: process.env.AIRPLANE}, function (t) {
    var dataCalled = false;

    var fixture = 'someDryrunFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      var req = http.request({
          host: "amazon.com"
        , path: '/'
        , port: 80
        }, function(res) {

          t.ok([200, 301, 302].indexOf(res.statusCode) >= 0);
          res.on('end', function() {
            var doneFails = false;

            t.ok(dataCalled);
            try {
              done();
              t.false(exists(fixtureLoc));
              scope.done();
            } catch(err) {
              doneFails = true;
            }
            t.ok(doneFails);
            t.end();
          });

          res.on('data', function(data) {
            dataCalled = true;
          });

        });

      req.once('error', function(err) {
        if (err.code !== 'ECONNREFUSED') {
          throw err;
        }
        t.end();
      });

      req.end();
    });
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});

tap.test('nockBack record tests', function (nw) {
  nockBack.setMode('record');

  nw.test('it records when configured correctly', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };

    var fixture = 'someFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      fs.unlinkSync(fixtureLoc);
      t.end();
    });

  });

  //Adding this test because there was an issue when not calling
  //nock.activate() after calling nock.restore()
  nw.test('it can record twice', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };
    var fixture = 'someFixture2.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;
    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      fs.unlinkSync(fixtureLoc);
      t.end();
    });

  });

  nw.test('it shouldn\'t allow outside calls', function (t) {

    var fixture = 'wrongUri.json';

    nockBack(fixture, function (done) {

      http.get('http://www.amazon.com', function(res) {
        throw "should not request this";
      }).on('error', function(err) {
        t.equal(err.message, 'Nock: Not allow net connect for "www.amazon.com:80/"');
        done();
        t.end();
      });

    });

  });

  nw.test('it loads your recorded tests', function (t) {

    nockBack('goodRequest.json', function (done) {
      t.true(this.scopes.length > 0);
      http.get('http://www.google.com').end();
      this.assertScopesFinished();
      done();
      t.end();
    });

  });

  nw.test('it can filter after recording', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };

    var fixture = 'filteredFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    var afterRecord = function(scopes) {
       // You would do some filtering here, but for this test we'll just return an empty array
      return [];
    }

    nockBack(fixture, {afterRecord: afterRecord}, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      nockBack(fixture, function (done) {
        t.true(this.scopes.length === 0);
        done();

        fs.unlinkSync(fixtureLoc);
        t.end();
      });
    });
  });

  nw.end();

  setOriginalModeOnEnd(nw, nockBack);
});

tap.test('nockBack lockdown tests', function (nw) {
  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('lockdown');

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('nock back loads scope', function (t) {
    nockBackWithFixture(t, true);
  });

  nw.test('no unnocked http calls work', function (t) {
    var req = http.request({
        host: "google.com"
      , path: '/'
      }, function(res) {
        throw new Error('should not come here!');
      });

    req.on('error', function (err) {
      t.equal(err.message.trim(), 'Nock: Not allow net connect for "google.com:80/"');
      t.end();
    });

    req.end();
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});
<|endoftext|>


<commit_before>// get accurate timing.
// This file must be loaded after prettify.js for this to work.
PR_SHOULD_USE_CONTINUATION = false;

var attribToHtml, textToHtml;

var getInnerHtml;

(function () {
  /** is the given node's innerHTML normally unescaped? */
  function isRawContent(node) {
    return 'XMP' === node.tagName;
  }

  var newlineRe = /[\r\n]/g;
  /**
   * Are newlines and adjacent spaces significant in the given node's innerHTML?
   */
  function isPreformatted(node, content) {
    // PRE means preformatted, and is a very common case, so don't create
    // unnecessary computed style objects.
    if ('PRE' === node.tagName) { return true; }
    if (!newlineRe.test(content)) { return true; }  // Don't care
    var whitespace = '';
    // For disconnected nodes, IE has no currentStyle.
    if (node.currentStyle) {
      whitespace = node.currentStyle.whiteSpace;
    } else if (window.getComputedStyle) {
      // Firefox makes a best guess if node is disconnected whereas Safari
      // returns the empty string.
      whitespace = window.getComputedStyle(node, null).whiteSpace;
    }
    return !whitespace || whitespace === 'pre';
  }

  // Define regexps here so that the interpreter doesn't have to create an
  // object each time the function containing them is called.
  // The language spec requires a new object created even if you don't access
  // the $1 members.
  var pr_amp = /&/g;
  var pr_lt = /</g;
  var pr_gt = />/g;
  var pr_quot = /\"/g;

  /** escapest html special characters to html. */
  textToHtml = function (str) {
    return str.replace(pr_amp, '&')
        .replace(pr_lt, '<')
        .replace(pr_gt, '>');
  };

  /** like textToHtml but escapes double quotes to be attribute safe. */
  attribToHtml = function (str) {
    return str.replace(pr_amp, '&')
        .replace(pr_lt, '<')
        .replace(pr_gt, '>')
        .replace(pr_quot, '"');
  };

  var PR_innerHtmlWorks = null;
  getInnerHtml = function (node) {
    // inner html is hopelessly broken in Safari 2.0.4 when the content is
    // an html description of well formed XML and the containing tag is a PRE
    // tag, so we detect that case and emulate innerHTML.
    if (null === PR_innerHtmlWorks) {
      var testNode = document.createElement('PRE');
      testNode.appendChild(
          document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
      PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
    }

    if (PR_innerHtmlWorks) {
      var content = node.innerHTML;
      // XMP tags contain unescaped entities so require special handling.
      if (isRawContent(node)) {
        content = textToHtml(content);
      } else if (!isPreformatted(node, content)) {
        content = content.replace(/(
)[\r\n]+/g, '$1')
            .replace(/(?:[\r\n]+[ \t]*)+/g, ' ');
      }
      return content;
    }

    var out = [];
    for (var child = node.firstChild; child; child = child.nextSibling) {
      normalizedHtml(child, out);
    }
    return out.join('');
  };
})();

function normalizedHtml(node, out, opt_sortAttrs) {
  switch (node.nodeType) {
    case 1:  // an element
      var name = node.tagName.toLowerCase();

      out.push('<', name);
      var attrs = node.attributes;
      var n = attrs.length;
      if (n) {
        if (opt_sortAttrs) {
          var sortedAttrs = [];
          for (var i = n; --i >= 0;) { sortedAttrs[i] = attrs[i]; }
          sortedAttrs.sort(function (a, b) {
              return (a.name < b.name) ? -1 : a.name === b.name ? 0 : 1;
            });
          attrs = sortedAttrs;
        }
        for (var i = 0; i < n; ++i) {
          var attr = attrs[i];
          if (!attr.specified) { continue; }
          out.push(' ', attr.name.toLowerCase(),
                   '="', attribToHtml(attr.value), '"');
        }
      }
      out.push('>');
      for (var child = node.firstChild; child; child = child.nextSibling) {
        normalizedHtml(child, out, opt_sortAttrs);
      }
      if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
        out.push('<\/', name, '>');
      }
      break;
    case 3: case 4: // text
      out.push(textToHtml(node.nodeValue));
      break;
  }
}

/**
 * @param golden a mapping from IDs of prettyprinted chunks to an abbreviated
 *     form of the expected output.  See "var goldens" in prettify_test.html
 *     for an example.
 */
function go(goldens) {
  startClock();
  prettyPrint(function () { stopClock(); runTests(goldens); });
}

function runTests(goldens) {
  /** number of characters in common at the end up to max. */
  function commonPrefix(a, b) {
    var n = Math.min(a.length, b.length);
    var i;
    for (i = 0; i < n; ++i) {
      if (a.charAt(i) !== b.charAt(i)) { break; }
    }
    return i;
  }

  /** number of characters in common at the end up to max. */
  function commonSuffix(a, b, max) {
    var n = Math.min(a.length - max, b.length - max);
    var i;
    for (i = 0; i < n; ++i) {
      if (a.charAt(a.length - i - 1) !== b.charAt(b.length - i - 1)) { break; }
    }
    return i;
  }

  /** convert a plain text string to html by escaping html special chars. */
  function html(plainText) {
    return attribToHtml(plainText).replace(/\xa0/g, ' ');
  }

  /**
   * get normalized markup.  innerHTML varies enough across browsers that we
   * can't use it.
   */
  function normalizedInnerHtml(node) {
    var out = [];
    for (var child = node.firstChild; child; child = child.nextSibling) {
      normalizedHtml(child, out, true);
    }
    out = out.join('');
    // more normalization to work around problems with non-ascii chars in
    // regexps in Safari
    for (var i = 0; (i = out.indexOf('\xa0')) >= 0;) {
      out = out.substring(0, i) + ' ' + out.substring(i + 1);
    }
    return out;
  }

  var htmlOut = [];
  var failures = 0;
  document.getElementById('errorReport').innerHTML =
      '
Running tests…<\/h1>';
  htmlOut.push('
Test results<\/h1>');
  for (var lang in goldens) {
    var container = document.getElementById(lang);
    // Convert abbreviations that start with `.
    var golden = goldens[lang].replace(/`([A-Z]{3})/g, function (_, lbl) {
        return (lbl == 'END'
            ? '<\/span>'
            : '');
      })
      // Line numbers
      .replace(/`#(?![0-9])/, '
')
      .replace(/`#([0-9])/g, '

');
    var actual = normalizedInnerHtml(container);
    if (golden !== actual) {  // test failed
      // write out
      var pre = commonPrefix(golden, actual);
      var post = commonSuffix(golden, actual, pre);

      ++failures;
      htmlOut.push(
          '
'
          + html(lang) + '<\/a> Failed<\/h2>');
      htmlOut.push(
          '<tt>' + html(golden.substring(0, pre)) +
          '»' +
          html(golden.substring(pre, golden.length - post)) +
          '<\/span>«' +
          html(golden.substring(golden.length - post)) +

          '
!==
' +

          html(actual.substring(0, pre)) +
          '»' +
          html(actual.substring(pre, actual.length - post)) +
          '<\/span>«' +
          html(actual.substring(actual.length - post)) + '<\/tt>');
    } else {
      htmlOut.push(
          '
' + html(lang) + '<\/a> OK<\/h2>');
    }
  }
  var summary = (failures ? (failures + ' test(s) failed') : 'Tests Passed');
  htmlOut.push('
' + summary + '<\/h2>');
  document.title += ' \u2014 ' + summary;
  document.getElementById('errorReport').innerHTML =
      htmlOut.join('').replace(/<br>/g, '<br>\n');
}

var startTime = null;
function startClock() {
  startTime = (new Date).getTime();
}

function stopClock() {
  var delta = (new Date).getTime() - startTime;
  startTime = null;
  document.getElementById('timing').innerHTML = 'Took ' + delta + ' ms';
}
<commit_msg>normalize newlines in tests<commit_after>// get accurate timing.
// This file must be loaded after prettify.js for this to work.
PR_SHOULD_USE_CONTINUATION = false;

var attribToHtml, textToHtml;

var getInnerHtml;

(function () {
  /** is the given node's innerHTML normally unescaped? */
  function isRawContent(node) {
    return 'XMP' === node.tagName;
  }

  var newlineRe = /[\r\n]/g;
  /**
   * Are newlines and adjacent spaces significant in the given node's innerHTML?
   */
  function isPreformatted(node, content) {
    // PRE means preformatted, and is a very common case, so don't create
    // unnecessary computed style objects.
    if ('PRE' === node.tagName) { return true; }
    if (!newlineRe.test(content)) { return true; }  // Don't care
    var whitespace = '';
    // For disconnected nodes, IE has no currentStyle.
    if (node.currentStyle) {
      whitespace = node.currentStyle.whiteSpace;
    } else if (window.getComputedStyle) {
      // Firefox makes a best guess if node is disconnected whereas Safari
      // returns the empty string.
      whitespace = window.getComputedStyle(node, null).whiteSpace;
    }
    return !whitespace || whitespace === 'pre';
  }

  // Define regexps here so that the interpreter doesn't have to create an
  // object each time the function containing them is called.
  // The language spec requires a new object created even if you don't access
  // the $1 members.
  var pr_amp = /&/g;
  var pr_lt = /</g;
  var pr_gt = />/g;
  var pr_quot = /\"/g;

  /** escapest html special characters to html. */
  textToHtml = function (str) {
    return str.replace(pr_amp, '&')
        .replace(pr_lt, '<')
        .replace(pr_gt, '>');
  };

  /** like textToHtml but escapes double quotes to be attribute safe. */
  attribToHtml = function (str) {
    return str.replace(pr_amp, '&')
        .replace(pr_lt, '<')
        .replace(pr_gt, '>')
        .replace(pr_quot, '"');
  };

  var PR_innerHtmlWorks = null;
  getInnerHtml = function (node) {
    // inner html is hopelessly broken in Safari 2.0.4 when the content is
    // an html description of well formed XML and the containing tag is a PRE
    // tag, so we detect that case and emulate innerHTML.
    if (null === PR_innerHtmlWorks) {
      var testNode = document.createElement('PRE');
      testNode.appendChild(
          document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
      PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
    }

    if (PR_innerHtmlWorks) {
      var content = node.innerHTML;
      // XMP tags contain unescaped entities so require special handling.
      if (isRawContent(node)) {
        content = textToHtml(content);
      } else if (!isPreformatted(node, content)) {
        content = content.replace(/(
)[\r\n]+/g, '$1')
            .replace(/(?:[\r\n]+[ \t]*)+/g, ' ');
      }
      return content;
    }

    var out = [];
    for (var child = node.firstChild; child; child = child.nextSibling) {
      normalizedHtml(child, out);
    }
    return out.join('');
  };
})();

function normalizedHtml(node, out, opt_sortAttrs) {
  switch (node.nodeType) {
    case 1:  // an element
      var name = node.tagName.toLowerCase();

      out.push('<', name);
      var attrs = node.attributes;
      var n = attrs.length;
      if (n) {
        if (opt_sortAttrs) {
          var sortedAttrs = [];
          for (var i = n; --i >= 0;) { sortedAttrs[i] = attrs[i]; }
          sortedAttrs.sort(function (a, b) {
              return (a.name < b.name) ? -1 : a.name === b.name ? 0 : 1;
            });
          attrs = sortedAttrs;
        }
        for (var i = 0; i < n; ++i) {
          var attr = attrs[i];
          if (!attr.specified) { continue; }
          out.push(' ', attr.name.toLowerCase(),
                   '="', attribToHtml(attr.value), '"');
        }
      }
      out.push('>');
      for (var child = node.firstChild; child; child = child.nextSibling) {
        normalizedHtml(child, out, opt_sortAttrs);
      }
      if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
        out.push('<\/', name, '>');
      }
      break;
    case 3: case 4: // text
      out.push(textToHtml(node.nodeValue));
      break;
  }
}

/**
 * @param golden a mapping from IDs of prettyprinted chunks to an abbreviated
 *     form of the expected output.  See "var goldens" in prettify_test.html
 *     for an example.
 */
function go(goldens) {
  startClock();
  prettyPrint(function () { stopClock(); runTests(goldens); });
}

function runTests(goldens) {
  /** number of characters in common at the end up to max. */
  function commonPrefix(a, b) {
    var n = Math.min(a.length, b.length);
    var i;
    for (i = 0; i < n; ++i) {
      if (a.charAt(i) !== b.charAt(i)) { break; }
    }
    return i;
  }

  /** number of characters in common at the end up to max. */
  function commonSuffix(a, b, max) {
    var n = Math.min(a.length - max, b.length - max);
    var i;
    for (i = 0; i < n; ++i) {
      if (a.charAt(a.length - i - 1) !== b.charAt(b.length - i - 1)) { break; }
    }
    return i;
  }

  /** convert a plain text string to html by escaping html special chars. */
  function html(plainText) {
    return attribToHtml(plainText).replace(/\xa0/g, ' ');
  }

  /**
   * get normalized markup.  innerHTML varies enough across browsers that we
   * can't use it.
   */
  function normalizedInnerHtml(node) {
    var out = [];
    for (var child = node.firstChild; child; child = child.nextSibling) {
      normalizedHtml(child, out, true);
    }
    out = out.join('');
    // more normalization to work around problems with non-ascii chars in
    // regexps in Safari
    for (var i = 0; (i = out.indexOf('\xa0')) >= 0;) {
      out = out.substring(0, i) + ' ' + out.substring(i + 1);
    }
    return out.replace(/\r\n?/g, '\n');
  }

  var htmlOut = [];
  var failures = 0;
  document.getElementById('errorReport').innerHTML =
      '
Running tests…<\/h1>';
  htmlOut.push('
Test results<\/h1>');
  for (var lang in goldens) {
    var container = document.getElementById(lang);
    // Convert abbreviations that start with `.
    var golden = goldens[lang].replace(/`([A-Z]{3})/g, function (_, lbl) {
        return (lbl == 'END'
            ? '<\/span>'
            : '');
      })
      // Line numbers
      .replace(/`#(?![0-9])/, '
')
      .replace(/`#([0-9])/g, '

');
    var actual = normalizedInnerHtml(container);
    if (golden !== actual) {  // test failed
      // write out
      var pre = commonPrefix(golden, actual);
      var post = commonSuffix(golden, actual, pre);

      ++failures;
      htmlOut.push(
          '
'
          + html(lang) + '<\/a> Failed<\/h2>');
      htmlOut.push(
          '<tt>' + html(golden.substring(0, pre)) +
          '»' +
          html(golden.substring(pre, golden.length - post)) +
          '<\/span>«' +
          html(golden.substring(golden.length - post)) +

          '
!==
' +

          html(actual.substring(0, pre)) +
          '»' +
          html(actual.substring(pre, actual.length - post)) +
          '<\/span>«' +
          html(actual.substring(actual.length - post)) + '<\/tt>');
    } else {
      htmlOut.push(
          '
' + html(lang) + '<\/a> OK<\/h2>');
    }
  }
  var summary = (failures ? (failures + ' test(s) failed') : 'Tests Passed');
  htmlOut.push('
' + summary + '<\/h2>');
  document.title += ' \u2014 ' + summary;
  document.getElementById('errorReport').innerHTML =
      htmlOut.join('').replace(/<br>/g, '<br>\n');
}

var startTime = null;
function startClock() {
  startTime = (new Date).getTime();
}

function stopClock() {
  var delta = (new Date).getTime() - startTime;
  startTime = null;
  document.getElementById('timing').innerHTML = 'Took ' + delta + ' ms';
}
<|endoftext|>


<commit_before>import createContext from 'create-react-context';

const FullscreenContext = createContext({
  fullscreen: false,
  requestFullscreen () {}
});
FullscreenContext.Provider.displayName = 'FullscreenContext.Provider';
FullscreenContext.Consumer.displayName = 'FullscreenContext.Consumer';

export default FullscreenContext;
<commit_msg>Dummy consumer methods filled out for FullscreenContext.<commit_after>import createContext from 'create-react-context';

import { logWarning } from './utils/console';

const FullscreenContext = createContext({
  fullscreen: false,
  requestFullscreen () {
    logWarning(
      'Fullscreen request ignored since there is no ' +
      'FullscreenContextProvider ancestor.'
    );
  },
  requestExitFullscreen () {
    logWarning(
      'Exit fullscreen request ignored since there is no ' +
      'FullscreenContextProvider ancestor.'
    );
  }
});
FullscreenContext.Provider.displayName = 'FullscreenContext.Provider';
FullscreenContext.Consumer.displayName = 'FullscreenContext.Consumer';

export default FullscreenContext;
<|endoftext|>