<commit_before>var sdf = require("../src/simpleDateFormat.js");
var moment = require("moment");

describe("simple date format with default pattern", function() {
  it("formats with ISO pattern", function() {
    /*
     * It's not identical with Java's `SimpleDateFormat` behavior because it's
     * uses the default format defined in locale. Currently I'm not sure how to
     * solve this problem.
     */
    expect(new sdf.SimpleDateFormat().format(moment([1999, 11, 1]))).toBe("1999-12-01");
  });

  it("applies the given pattern to this date format", function() {
    var formatter = new sdf.SimpleDateFormat();
    var d = moment([1999, 11, 1]);
    expect(formatter.format(d)).toBe("1999-12-01");
    formatter.applyPattern("MM/dd/yy");
    expect(formatter.format(d)).toBe("12/01/99");
  });
});

describe("simple date format with default locale", function () {
  /*
   * All the tests below assumes the SimpleDateFormat's default locale is
   * EN_US which means every text in English and the first day of the week
   * is Sunday.
   */

	it("formats era designator", function() {
    var d = moment();
    expect(new sdf.SimpleDateFormat("G").format(d)).toBe("AD");
  });

  it("formats year", function() {
    var d = moment([1989, 11, 6]);
    expect(new sdf.SimpleDateFormat("y").format(d)).toBe("1989");
    expect(new sdf.SimpleDateFormat("yy").format(d)).toBe("89");
    expect(new sdf.SimpleDateFormat("yyy").format(d)).toBe("1989");
    expect(new sdf.SimpleDateFormat("yyyy").format(d)).toBe("1989");
  });

  it("formats week year", function() {
    /*
     * A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the
     * first and last weeks (inclusive) have the same week year value.
     * Therefore, the first and last days of a week year may have different
     * calendar year values.
     *
     * For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is
     * MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible
     * setting), then week 1 of 1998 starts on December 29, 1997, and ends on
     * January 4, 1998. The week year is 1998 for the last three days of
     * calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week
     * 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the
     * first three days of 1998 then are part of week 53 of 1997 and their week
     * year is 1997.
     */

    var d = moment([1997, 11, 28]);
    expect(new sdf.SimpleDateFormat("Y").format(d)).toBe("1998");
    expect(new sdf.SimpleDateFormat("YY").format(d)).toBe("98");
    expect(new sdf.SimpleDateFormat("YYY").format(d)).toBe("1998");
    expect(new sdf.SimpleDateFormat("YYYY").format(d)).toBe("1998");
  });

  it("formats month in year (context sensitive)", function() {
    var d = moment([2017, 5, 5]);
    expect(new sdf.SimpleDateFormat("M").format(d)).toBe("6");
    expect(new sdf.SimpleDateFormat("MM").format(d)).toBe("06");
    expect(new sdf.SimpleDateFormat("MMM").format(d)).toBe("Jun");
    expect(new sdf.SimpleDateFormat("MMMM").format(d)).toBe("June");
  });

  it("formats month in year (standalone form)", function() {
    /*
     * In English there is no difference in standalon and context sensitive
     * forms, however here is a thread that explains a the difference between
     * them:
     * http://stackoverflow.com/questions/32840336/standalone-form-of-month-name-in-java-date-format
     */

    var d = moment([2017, 5, 5]);
    expect(new sdf.SimpleDateFormat("L").format(d)).toBe("6");
    expect(new sdf.SimpleDateFormat("LL").format(d)).toBe("06");
    expect(new sdf.SimpleDateFormat("LLL").format(d)).toBe("Jun");
    expect(new sdf.SimpleDateFormat("LLLL").format(d)).toBe("June");
  });

  it("formats week in year", function() {
    var d = moment([1997, 11, 28]);
    expect(new sdf.SimpleDateFormat("w").format(d)).toBe("1");
    expect(new sdf.SimpleDateFormat("ww").format(d)).toBe("01");
  });

  it("formats week in month", function() {
    var d = moment([1997, 11, 28]);
    expect(new sdf.SimpleDateFormat("W").format(d)).toBe("5");
  });

  it("formats day in year", function() {
    var d = moment([1997, 0, 3]);
    expect(new sdf.SimpleDateFormat("D").format(d)).toBe("3");
    expect(new sdf.SimpleDateFormat("DD").format(d)).toBe("03");
    expect(new sdf.SimpleDateFormat("DDD").format(d)).toBe("003");
  });

  it("formats day in month", function() {
    var d = moment([2017, 5, 5]);
    expect(new sdf.SimpleDateFormat("d").format(d)).toBe("5");
    expect(new sdf.SimpleDateFormat("dd").format(d)).toBe("05");
  });

  it("formats the day of week in month", function() {
    //it is the second Wendesday in May
    var d = moment([2017, 4, 10]);
    expect(new sdf.SimpleDateFormat("F").format(d)).toBe("2");
  });

  it("formats the day name in week", function() {
    var d = moment([2017, 4, 10]);
    expect(new sdf.SimpleDateFormat("E").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EE").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EEE").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EEEE").format(d)).toBe("Wednesday");
  });

  it("formats the day number in week", function() {
    //first day of the week is always Monday, does not matter which locale you use
    expect(new sdf.SimpleDateFormat("u").format(moment([2017, 4, 8]))).toBe("1");
    expect(new sdf.SimpleDateFormat("u").format(moment([2017, 4, 7]))).toBe("7");
  });

  it("formats the am/pm markers", function() {
    expect(new sdf.SimpleDateFormat("a").format(moment([2017, 4, 20, 16, 30, 0, 0]))).toBe("PM");
    expect(new sdf.SimpleDateFormat("a").format(moment([2017, 4, 20, 10, 30, 0, 0]))).toBe("AM");
  });

  it("formats hour in day", function() {
    expect(new sdf.SimpleDateFormat("H").format(moment([2017, 4, 20, 0, 0, 0, 0]))).toBe("0");
    expect(new sdf.SimpleDateFormat("H").format(moment([2017, 4, 20, 23, 0, 0, 0]))).toBe("23");
    expect(new sdf.SimpleDateFormat("k").format(moment([2017, 4, 20, 0, 0, 0, 0]))).toBe("24");
    expect(new sdf.SimpleDateFormat("K").format(moment([2017, 4, 20, 0, 0, 0, 0]))).toBe("0");
    expect(new sdf.SimpleDateFormat("K").format(moment([2017, 4, 20, 23, 0, 0, 0]))).toBe("11");
    expect(new sdf.SimpleDateFormat("h").format(moment([2017, 4, 20, 0, 0, 0, 0]))).toBe("12");
  });

  it("formats minute in hour", function() {
    expect(new sdf.SimpleDateFormat("m")).format(moment([2017, 4, 20, 17, 14, 0, 0])).toBe("14");
  });

  it("formats second in minute", function() {
    expext(new sdf.SimpleDateForamt("s").format(moment([2017, 4, 20, 17, 16, 59, 0]))).toBe("59");
  });

  it("combines patterns", function() {
    var d = moment([2001, 6, 4, 12, 8, 56]);
    expect(new sdf.SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z").format(d)).toBe("2001.07.04 AD at 12:08:56 PDT");
    expect(new sdf.SimpleDateFormat("EEE, MMM d, ''yy").format(d)).toBe("Wed, Jul 4, '01");
    expect(new sdf.SimpleDateFormat("h:mm a").format(d)).toBe("12:08 PM");
    expect(new sdf.SimpleDateFormat("hh 'o''clock' a, zzzz").format(d)).toBe("12 o'clock PM, Pacific Daylight Time");
    expect(new sdf.SimpleDateFormat("K:mm a, z").format(d)).toBe("0:08 PM, PDT");
    expect(new sdf.SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa").format(d)).toBe("02001.July.04 AD 12:08 PM");
    expect(new sdf.SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(d)).toBe("Wed, 4 Jul 2001 12:08:56 -0700");
    expect(new sdf.SimpleDateFormat("yyMMddHHmmssZ").format(d)).toBe("010704120856-0700");
    expect(new sdf.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(d)).toBe("2001-07-04T12:08:56.235-0700");
    expect(new sdf.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(d)).toBe("2001-07-04T12:08:56.235-07:00");
    expect(new sdf.SimpleDateFormat("YYYY-'W'ww-u").format(d)).toBe("2001-W27-3");
  });
});
<commit_msg>Fix typos in tests.<commit_after>var sdf = require("../src/simpleDateFormat.js");
var moment = require("moment");

describe("simple date format with default pattern", function() {
  it("formats with ISO pattern", function() {
    /*
     * It's not identical with Java's `SimpleDateFormat` behavior because it's
     * uses the default format defined in locale. Currently I'm not sure how to
     * solve this problem.
     */
    expect(new sdf.SimpleDateFormat().format(moment([1999, 11, 1]))).toBe("1999-12-01");
  });

  it("applies the given pattern to this date format", function() {
    var formatter = new sdf.SimpleDateFormat();
    var d = moment([1999, 11, 1]);
    expect(formatter.format(d)).toBe("1999-12-01");
    formatter.applyPattern("MM/dd/yy");
    expect(formatter.format(d)).toBe("12/01/99");
  });
});

describe("simple date format with default locale", function () {
  /*
   * All the tests below assumes the SimpleDateFormat's default locale is
   * EN_US which means every text in English and the first day of the week
   * is Sunday.
   */

	it("formats era designator", function() {
    var d = moment();
    expect(new sdf.SimpleDateFormat("G").format(d)).toBe("AD");
  });

  it("formats year", function() {
    var d = moment([1989, 11, 6]);
    expect(new sdf.SimpleDateFormat("y").format(d)).toBe("1989");
    expect(new sdf.SimpleDateFormat("yy").format(d)).toBe("89");
    expect(new sdf.SimpleDateFormat("yyy").format(d)).toBe("1989");
    expect(new sdf.SimpleDateFormat("yyyy").format(d)).toBe("1989");
  });

  it("formats week year", function() {
    /*
     * A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the
     * first and last weeks (inclusive) have the same week year value.
     * Therefore, the first and last days of a week year may have different
     * calendar year values.
     *
     * For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is
     * MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible
     * setting), then week 1 of 1998 starts on December 29, 1997, and ends on
     * January 4, 1998. The week year is 1998 for the last three days of
     * calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week
     * 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the
     * first three days of 1998 then are part of week 53 of 1997 and their week
     * year is 1997.
     */

    var d = moment([1997, 11, 28]);
    expect(new sdf.SimpleDateFormat("Y").format(d)).toBe("1998");
    expect(new sdf.SimpleDateFormat("YY").format(d)).toBe("98");
    expect(new sdf.SimpleDateFormat("YYY").format(d)).toBe("1998");
    expect(new sdf.SimpleDateFormat("YYYY").format(d)).toBe("1998");
  });

  it("formats month in year (context sensitive)", function() {
    var d = moment([2017, 5, 5]);
    expect(new sdf.SimpleDateFormat("M").format(d)).toBe("6");
    expect(new sdf.SimpleDateFormat("MM").format(d)).toBe("06");
    expect(new sdf.SimpleDateFormat("MMM").format(d)).toBe("Jun");
    expect(new sdf.SimpleDateFormat("MMMM").format(d)).toBe("June");
  });

  it("formats month in year (standalone form)", function() {
    /*
     * In English there is no difference in standalon and context sensitive
     * forms, however here is a thread that explains a the difference between
     * them:
     * http://stackoverflow.com/questions/32840336/standalone-form-of-month-name-in-java-date-format
     */

    var d = moment([2017, 5, 5]);
    expect(new sdf.SimpleDateFormat("L").format(d)).toBe("6");
    expect(new sdf.SimpleDateFormat("LL").format(d)).toBe("06");
    expect(new sdf.SimpleDateFormat("LLL").format(d)).toBe("Jun");
    expect(new sdf.SimpleDateFormat("LLLL").format(d)).toBe("June");
  });

  it("formats week in year", function() {
    var d = moment([1997, 11, 28]);
    expect(new sdf.SimpleDateFormat("w").format(d)).toBe("1");
    expect(new sdf.SimpleDateFormat("ww").format(d)).toBe("01");
  });

  it("formats week in month", function() {
    var d = moment([1997, 11, 28]);
    expect(new sdf.SimpleDateFormat("W").format(d)).toBe("5");
  });

  it("formats day in year", function() {
    var d = moment([1997, 0, 3]);
    expect(new sdf.SimpleDateFormat("D").format(d)).toBe("3");
    expect(new sdf.SimpleDateFormat("DD").format(d)).toBe("03");
    expect(new sdf.SimpleDateFormat("DDD").format(d)).toBe("003");
  });

  it("formats day in month", function() {
    var d = moment([2017, 5, 5]);
    expect(new sdf.SimpleDateFormat("d").format(d)).toBe("5");
    expect(new sdf.SimpleDateFormat("dd").format(d)).toBe("05");
  });

  it("formats the day of week in month", function() {
    //it is the second Wendesday in May
    var d = moment([2017, 4, 10]);
    expect(new sdf.SimpleDateFormat("F").format(d)).toBe("2");
  });

  it("formats the day name in week", function() {
    var d = moment([2017, 4, 10]);
    expect(new sdf.SimpleDateFormat("E").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EE").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EEE").format(d)).toBe("Wed");
    expect(new sdf.SimpleDateFormat("EEEE").format(d)).toBe("Wednesday");
  });

  it("formats the day number in week", function() {
    //first day of the week is always Monday, does not matter which locale you use
    expect(new sdf.SimpleDateFormat("u").format(moment([2017, 4, 8]))).toBe("1");
    expect(new sdf.SimpleDateFormat("u").format(moment([2017, 4, 7]))).toBe("7");
  });

  it("formats the am/pm markers", function() {
    expect(new sdf.SimpleDateFormat("a").format(moment([2017, 4, 20, 16, 30, 0, 0]))).toBe("PM");
    expect(new sdf.SimpleDateFormat("a").format(moment([2017, 4, 20, 10, 30, 0, 0]))).toBe("AM");
  });

  it("formats hour in day", function() {
    expect(new sdf.SimpleDateFormat("H").format(moment([2017, 4, 20, 0, 0, 0, 0]))).toBe("0");
    expect(new sdf.SimpleDateFormat("H").format(moment([2017, 4, 20, 23, 0, 0, 0]))).toBe("23");
    expect(new sdf.SimpleDateFormat("k").format(moment([2017, 4, 20, 0, 0, 0, 0]))).toBe("24");
    expect(new sdf.SimpleDateFormat("K").format(moment([2017, 4, 20, 0, 0, 0, 0]))).toBe("0");
    expect(new sdf.SimpleDateFormat("K").format(moment([2017, 4, 20, 23, 0, 0, 0]))).toBe("11");
    expect(new sdf.SimpleDateFormat("h").format(moment([2017, 4, 20, 0, 0, 0, 0]))).toBe("12");
  });

  it("formats minute in hour", function() {
    expect(new sdf.SimpleDateFormat("m").format(moment([2017, 4, 20, 17, 14, 0, 0]))).toBe("14");
  });

  it("formats second in minute", function() {
    expect(new sdf.SimpleDateFormat("s").format(moment([2017, 4, 20, 17, 16, 59, 0]))).toBe("59");
  });

  it("combines patterns", function() {
    var d = moment([2001, 6, 4, 12, 8, 56]);
    expect(new sdf.SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z").format(d)).toBe("2001.07.04 AD at 12:08:56 PDT");
    expect(new sdf.SimpleDateFormat("EEE, MMM d, ''yy").format(d)).toBe("Wed, Jul 4, '01");
    expect(new sdf.SimpleDateFormat("h:mm a").format(d)).toBe("12:08 PM");
    expect(new sdf.SimpleDateFormat("hh 'o''clock' a, zzzz").format(d)).toBe("12 o'clock PM, Pacific Daylight Time");
    expect(new sdf.SimpleDateFormat("K:mm a, z").format(d)).toBe("0:08 PM, PDT");
    expect(new sdf.SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa").format(d)).toBe("02001.July.04 AD 12:08 PM");
    expect(new sdf.SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(d)).toBe("Wed, 4 Jul 2001 12:08:56 -0700");
    expect(new sdf.SimpleDateFormat("yyMMddHHmmssZ").format(d)).toBe("010704120856-0700");
    expect(new sdf.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(d)).toBe("2001-07-04T12:08:56.235-0700");
    expect(new sdf.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(d)).toBe("2001-07-04T12:08:56.235-07:00");
    expect(new sdf.SimpleDateFormat("YYYY-'W'ww-u").format(d)).toBe("2001-W27-3");
  });
});
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

/* More information about these options at jshint.com/docs/options */
/* jshint browser: true, camelcase: true, curly: true, devel: true,
   eqeqeq: true, forin: false, globalstrict: true, node: true,
   quotmark: single, undef: true, unused: strict */
/* global mozRTCIceCandidate, mozRTCPeerConnection, Promise,
mozRTCSessionDescription, webkitRTCPeerConnection, MediaStreamTrack */
/* exported trace,requestUserMedia */

'use strict';

var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
var webrtcDetectedVersion = null;
var webrtcMinimumVersion = null;

function trace(text) {
  // This function is used for logging.
  if (text[text.length - 1] === '\n') {
    text = text.substring(0, text.length - 1);
  }
  if (window.performance) {
    var now = (window.performance.now() / 1000).toFixed(3);
    console.log(now + ': ' + text);
  } else {
    console.log(text);
  }
}

if (navigator.mozGetUserMedia) {
  console.log('This appears to be Firefox');

  webrtcDetectedBrowser = 'firefox';

  // the detected firefox version.
  webrtcDetectedVersion =
    parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);

  // the minimum firefox version still supported by adapter.
  webrtcMinimumVersion = 31;

  // The RTCPeerConnection object.
  window.RTCPeerConnection = function(pcConfig, pcConstraints) {
    if (webrtcDetectedVersion < 38) {
      // .urls is not supported in FF < 38.
      // create RTCIceServers with a single url.
      if (pcConfig && pcConfig.iceServers) {
        var newIceServers = [];
        for (var i = 0; i < pcConfig.iceServers.length; i++) {
          var server = pcConfig.iceServers[i];
          if (server.hasOwnProperty('urls')) {
            for (var j = 0; j < server.urls.length; j++) {
              var newServer = {
                url: server.urls[j]
              };
              if (server.urls[j].indexOf('turn') === 0) {
                newServer.username = server.username;
                newServer.credential = server.credential;
              }
              newIceServers.push(newServer);
            }
          } else {
            newIceServers.push(pcConfig.iceServers[i]);
          }
        }
        pcConfig.iceServers = newIceServers;
      }
    }
    return new mozRTCPeerConnection(pcConfig, pcConstraints);
  };

  // The RTCSessionDescription object.
  window.RTCSessionDescription = mozRTCSessionDescription;

  // The RTCIceCandidate object.
  window.RTCIceCandidate = mozRTCIceCandidate;

  // getUserMedia constraints shim.
  getUserMedia = (webrtcDetectedVersion < 38) ?
      function(c, onSuccess, onError) {
    var constraintsToFF37 = function(c) {
      if (typeof c !== 'object' || c.require) {
        return c;
      }
      var require = [];
      Object.keys(c).forEach(function(key) {
        var r = c[key] = (typeof c[key] === 'object') ?
            c[key] : {ideal: c[key]};
        if (r.exact !== undefined) {
          r.min = r.max = r.exact;
          delete r.exact;
        }
        if (r.min !== undefined || r.max !== undefined) {
          require.push(key);
        }
        if (r.ideal !== undefined) {
          c.advanced = c.advanced || [];
          var oc = {};
          oc[key] = {min: r.ideal, max: r.ideal};
          c.advanced.push(oc);
          delete r.ideal;
          if (!Object.keys(r).length) {
            delete c[key];
          }
        }
      });
      if (require.length) {
        c.require = require;
      }
      return c;
    };
    console.log('spec: ' + JSON.stringify(c));
    c.audio = constraintsToFF37(c.audio);
    c.video = constraintsToFF37(c.video);
    console.log('ff37: ' + JSON.stringify(c));
    return navigator.mozGetUserMedia(c, onSuccess, onError);
  } : navigator.mozGetUserMedia.bind(navigator);

  navigator.getUserMedia = getUserMedia;

  // Shim for mediaDevices on older versions.
  if (!navigator.mediaDevices) {
    navigator.mediaDevices = {getUserMedia: requestUserMedia};
  }
  navigator.mediaDevices.enumerateDevices =
      navigator.mediaDevices.enumerateDevices || function() {
    return new Promise(function(resolve) {
      var infos = [
        {kind: 'audioinput', deviceId: 'default', label:'', groupId:''},
        {kind: 'videoinput', deviceId: 'default', label:'', groupId:''}
      ];
      resolve(infos);
    });
  };
  if (webrtcDetectedVersion < 41) {
    // Work around http://bugzil.la/1169665
    var orgEnumerateDevices =
        navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
    navigator.mediaDevices.enumerateDevices = function() {
      return orgEnumerateDevices().catch(function(e) {
        if (e.name === 'NotFoundError') {
          return [];
        }
        throw e;
      });
    };
  }
  // Attach a media stream to an element.
  attachMediaStream = function(element, stream) {
    console.log('Attaching media stream');
    element.mozSrcObject = stream;
  };

  reattachMediaStream = function(to, from) {
    console.log('Reattaching media stream');
    to.mozSrcObject = from.mozSrcObject;
  };

} else if (navigator.webkitGetUserMedia) {
  console.log('This appears to be Chrome');

  webrtcDetectedBrowser = 'chrome';

  // the detected chrome version.
  webrtcDetectedVersion =
    parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);

  // the minimum chrome version still supported by adapter.
  webrtcMinimumVersion = 38;

  // The RTCPeerConnection object.
  window.RTCPeerConnection = function(pcConfig, pcConstraints) {
    return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  };
  // add promise support
  ['createOffer', 'createAnswer'].forEach(function(method) {
    var nativeMethod = webkitRTCPeerConnection.prototype[method];
    webkitRTCPeerConnection.prototype[method] = function() {
      var self = this;
      if (arguments.length < 1 || (arguments.length === 1 &&
          typeof(arguments[0]) === 'object')) {
        var opts = arguments.length === 1 ? arguments[0] : undefined;
        return new Promise(function(resolve, reject) {
          nativeMethod.apply(self, [resolve, reject, opts]);
        });
      } else {
        return nativeMethod.apply(this, arguments);
      }
    };
  });

  ['setLocalDescription', 'setRemoteDescription',
      'addIceCandidate'].forEach(function(method) {
    var nativeMethod = webkitRTCPeerConnection.prototype[method];
    webkitRTCPeerConnection.prototype[method] = function() {
      var args = arguments;
      var self = this;
      return new Promise(function(resolve, reject) {
        nativeMethod.apply(self, [args[0],
            function() {
              resolve();
              if (args.length >= 2) {
                args[1].apply(null, []);
              }
            },
            function(err) {
              reject(err);
              if (args.length >= 3) {
                args[2].apply(null, [err]);
              }
            }]
          );
      });
    };
  });

  // getUserMedia constraints shim.
  getUserMedia = function(c, onSuccess, onError) {
    var constraintsToChrome = function(c) {
      if (typeof c !== 'object' || c.mandatory || c.optional) {
        return c;
      }
      var cc = {};
      Object.keys(c).forEach(function(key) {
        if (key === 'require' || key === 'advanced') {
          return;
        }
        var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
        if (r.exact !== undefined && typeof r.exact === 'number') {
          r.min = r.max = r.exact;
        }
        var oldname = function(prefix, name) {
          if (prefix) {
            return prefix + name.charAt(0).toUpperCase() + name.slice(1);
          }
          return (name === 'deviceId') ? 'sourceId' : name;
        };
        if (r.ideal !== undefined) {
          cc.optional = cc.optional || [];
          var oc = {};
          if (typeof r.ideal === 'number') {
            oc[oldname('min', key)] = r.ideal;
            cc.optional.push(oc);
            oc = {};
            oc[oldname('max', key)] = r.ideal;
            cc.optional.push(oc);
          } else {
            oc[oldname('', key)] = r.ideal;
            cc.optional.push(oc);
          }
        }
        if (r.exact !== undefined && typeof r.exact !== 'number') {
          cc.mandatory = cc.mandatory || {};
          cc.mandatory[oldname('', key)] = r.exact;
        } else {
          ['min', 'max'].forEach(function(mix) {
            if (r[mix] !== undefined) {
              cc.mandatory = cc.mandatory || {};
              cc.mandatory[oldname(mix, key)] = r[mix];
            }
          });
        }
      });
      if (c.advanced) {
        cc.optional = (cc.optional || []).concat(c.advanced);
      }
      return cc;
    };
    console.log('spec:   ' + JSON.stringify(c)); // whitespace for alignment
    c.audio = constraintsToChrome(c.audio);
    c.video = constraintsToChrome(c.video);
    console.log('chrome: ' + JSON.stringify(c));
    return navigator.webkitGetUserMedia(c, onSuccess, onError);
  };
  navigator.getUserMedia = getUserMedia;

  // Attach a media stream to an element.
  attachMediaStream = function(element, stream) {
    if (typeof element.srcObject !== 'undefined') {
      element.srcObject = stream;
    } else if (typeof element.mozSrcObject !== 'undefined') {
      element.mozSrcObject = stream;
    } else if (typeof element.src !== 'undefined') {
      element.src = URL.createObjectURL(stream);
    } else {
      console.log('Error attaching stream to element.');
    }
  };

  reattachMediaStream = function(to, from) {
    to.src = from.src;
  };

  if (!navigator.mediaDevices) {
    navigator.mediaDevices = {getUserMedia: requestUserMedia,
                              enumerateDevices: function() {
      return new Promise(function(resolve) {
        var kinds = {audio: 'audioinput', video: 'videoinput'};
        return MediaStreamTrack.getSources(function(devices) {
          resolve(devices.map(function(device) {
            return {label: device.label,
                    kind: kinds[device.kind],
                    deviceId: device.id,
                    groupId: ''};
          }));
        });
      });
    }};
  }
} else if (navigator.mediaDevices && navigator.userAgent.match(
    /Edge\/(\d+).(\d+)$/)) {
  webrtcDetectedBrowser = 'edge';

  webrtcDetectedVersion =
    parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);

  // the minimum version still supported by adapter.
  webrtcMinimumVersion = 12;

  attachMediaStream = function(element, stream) {
    element.srcObject = stream;
  };
  reattachMediaStream = function(to, from) {
    to.srcObject = from.srcObject;
  };
} else {
  console.log('Browser does not appear to be WebRTC-capable');
}

// Returns the result of getUserMedia as a Promise.
function requestUserMedia(constraints) {
  return new Promise(function(resolve, reject) {
    getUserMedia(constraints, resolve, reject);
  });
}

if (typeof module !== 'undefined') {
  module.exports = {
    RTCPeerConnection: RTCPeerConnection,
    getUserMedia: getUserMedia,
    attachMediaStream: attachMediaStream,
    reattachMediaStream: reattachMediaStream,
    webrtcDetectedBrowser: webrtcDetectedBrowser,
    webrtcDetectedVersion: webrtcDetectedVersion,
    webrtcMinimumVersion: webrtcMinimumVersion
    //requestUserMedia: not exposed on purpose.
    //trace: not exposed on purpose.
  };
}
<commit_msg>move attachMediaStream definition<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

/* More information about these options at jshint.com/docs/options */
/* jshint browser: true, camelcase: true, curly: true, devel: true,
   eqeqeq: true, forin: false, globalstrict: true, node: true,
   quotmark: single, undef: true, unused: strict */
/* global mozRTCIceCandidate, mozRTCPeerConnection, Promise,
mozRTCSessionDescription, webkitRTCPeerConnection, MediaStreamTrack */
/* exported trace,requestUserMedia */

'use strict';

var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
var webrtcDetectedVersion = null;
var webrtcMinimumVersion = null;

function trace(text) {
  // This function is used for logging.
  if (text[text.length - 1] === '\n') {
    text = text.substring(0, text.length - 1);
  }
  if (window.performance) {
    var now = (window.performance.now() / 1000).toFixed(3);
    console.log(now + ': ' + text);
  } else {
    console.log(text);
  }
}

if (navigator.mozGetUserMedia) {
  console.log('This appears to be Firefox');

  webrtcDetectedBrowser = 'firefox';

  // the detected firefox version.
  webrtcDetectedVersion =
    parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);

  // the minimum firefox version still supported by adapter.
  webrtcMinimumVersion = 31;

  // The RTCPeerConnection object.
  window.RTCPeerConnection = function(pcConfig, pcConstraints) {
    if (webrtcDetectedVersion < 38) {
      // .urls is not supported in FF < 38.
      // create RTCIceServers with a single url.
      if (pcConfig && pcConfig.iceServers) {
        var newIceServers = [];
        for (var i = 0; i < pcConfig.iceServers.length; i++) {
          var server = pcConfig.iceServers[i];
          if (server.hasOwnProperty('urls')) {
            for (var j = 0; j < server.urls.length; j++) {
              var newServer = {
                url: server.urls[j]
              };
              if (server.urls[j].indexOf('turn') === 0) {
                newServer.username = server.username;
                newServer.credential = server.credential;
              }
              newIceServers.push(newServer);
            }
          } else {
            newIceServers.push(pcConfig.iceServers[i]);
          }
        }
        pcConfig.iceServers = newIceServers;
      }
    }
    return new mozRTCPeerConnection(pcConfig, pcConstraints);
  };

  // The RTCSessionDescription object.
  window.RTCSessionDescription = mozRTCSessionDescription;

  // The RTCIceCandidate object.
  window.RTCIceCandidate = mozRTCIceCandidate;

  // getUserMedia constraints shim.
  getUserMedia = (webrtcDetectedVersion < 38) ?
      function(c, onSuccess, onError) {
    var constraintsToFF37 = function(c) {
      if (typeof c !== 'object' || c.require) {
        return c;
      }
      var require = [];
      Object.keys(c).forEach(function(key) {
        var r = c[key] = (typeof c[key] === 'object') ?
            c[key] : {ideal: c[key]};
        if (r.exact !== undefined) {
          r.min = r.max = r.exact;
          delete r.exact;
        }
        if (r.min !== undefined || r.max !== undefined) {
          require.push(key);
        }
        if (r.ideal !== undefined) {
          c.advanced = c.advanced || [];
          var oc = {};
          oc[key] = {min: r.ideal, max: r.ideal};
          c.advanced.push(oc);
          delete r.ideal;
          if (!Object.keys(r).length) {
            delete c[key];
          }
        }
      });
      if (require.length) {
        c.require = require;
      }
      return c;
    };
    console.log('spec: ' + JSON.stringify(c));
    c.audio = constraintsToFF37(c.audio);
    c.video = constraintsToFF37(c.video);
    console.log('ff37: ' + JSON.stringify(c));
    return navigator.mozGetUserMedia(c, onSuccess, onError);
  } : navigator.mozGetUserMedia.bind(navigator);

  navigator.getUserMedia = getUserMedia;

  // Shim for mediaDevices on older versions.
  if (!navigator.mediaDevices) {
    navigator.mediaDevices = {getUserMedia: requestUserMedia};
  }
  navigator.mediaDevices.enumerateDevices =
      navigator.mediaDevices.enumerateDevices || function() {
    return new Promise(function(resolve) {
      var infos = [
        {kind: 'audioinput', deviceId: 'default', label:'', groupId:''},
        {kind: 'videoinput', deviceId: 'default', label:'', groupId:''}
      ];
      resolve(infos);
    });
  };
  if (webrtcDetectedVersion < 41) {
    // Work around http://bugzil.la/1169665
    var orgEnumerateDevices =
        navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
    navigator.mediaDevices.enumerateDevices = function() {
      return orgEnumerateDevices().catch(function(e) {
        if (e.name === 'NotFoundError') {
          return [];
        }
        throw e;
      });
    };
  }

  reattachMediaStream = function(to, from) {
    to.mozSrcObject = from.mozSrcObject;
  };

} else if (navigator.webkitGetUserMedia) {
  console.log('This appears to be Chrome');

  webrtcDetectedBrowser = 'chrome';

  // the detected chrome version.
  webrtcDetectedVersion =
    parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);

  // the minimum chrome version still supported by adapter.
  webrtcMinimumVersion = 38;

  // The RTCPeerConnection object.
  window.RTCPeerConnection = function(pcConfig, pcConstraints) {
    return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  };
  // add promise support
  ['createOffer', 'createAnswer'].forEach(function(method) {
    var nativeMethod = webkitRTCPeerConnection.prototype[method];
    webkitRTCPeerConnection.prototype[method] = function() {
      var self = this;
      if (arguments.length < 1 || (arguments.length === 1 &&
          typeof(arguments[0]) === 'object')) {
        var opts = arguments.length === 1 ? arguments[0] : undefined;
        return new Promise(function(resolve, reject) {
          nativeMethod.apply(self, [resolve, reject, opts]);
        });
      } else {
        return nativeMethod.apply(this, arguments);
      }
    };
  });

  ['setLocalDescription', 'setRemoteDescription',
      'addIceCandidate'].forEach(function(method) {
    var nativeMethod = webkitRTCPeerConnection.prototype[method];
    webkitRTCPeerConnection.prototype[method] = function() {
      var args = arguments;
      var self = this;
      return new Promise(function(resolve, reject) {
        nativeMethod.apply(self, [args[0],
            function() {
              resolve();
              if (args.length >= 2) {
                args[1].apply(null, []);
              }
            },
            function(err) {
              reject(err);
              if (args.length >= 3) {
                args[2].apply(null, [err]);
              }
            }]
          );
      });
    };
  });

  // getUserMedia constraints shim.
  getUserMedia = function(c, onSuccess, onError) {
    var constraintsToChrome = function(c) {
      if (typeof c !== 'object' || c.mandatory || c.optional) {
        return c;
      }
      var cc = {};
      Object.keys(c).forEach(function(key) {
        if (key === 'require' || key === 'advanced') {
          return;
        }
        var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
        if (r.exact !== undefined && typeof r.exact === 'number') {
          r.min = r.max = r.exact;
        }
        var oldname = function(prefix, name) {
          if (prefix) {
            return prefix + name.charAt(0).toUpperCase() + name.slice(1);
          }
          return (name === 'deviceId') ? 'sourceId' : name;
        };
        if (r.ideal !== undefined) {
          cc.optional = cc.optional || [];
          var oc = {};
          if (typeof r.ideal === 'number') {
            oc[oldname('min', key)] = r.ideal;
            cc.optional.push(oc);
            oc = {};
            oc[oldname('max', key)] = r.ideal;
            cc.optional.push(oc);
          } else {
            oc[oldname('', key)] = r.ideal;
            cc.optional.push(oc);
          }
        }
        if (r.exact !== undefined && typeof r.exact !== 'number') {
          cc.mandatory = cc.mandatory || {};
          cc.mandatory[oldname('', key)] = r.exact;
        } else {
          ['min', 'max'].forEach(function(mix) {
            if (r[mix] !== undefined) {
              cc.mandatory = cc.mandatory || {};
              cc.mandatory[oldname(mix, key)] = r[mix];
            }
          });
        }
      });
      if (c.advanced) {
        cc.optional = (cc.optional || []).concat(c.advanced);
      }
      return cc;
    };
    console.log('spec:   ' + JSON.stringify(c)); // whitespace for alignment
    c.audio = constraintsToChrome(c.audio);
    c.video = constraintsToChrome(c.video);
    console.log('chrome: ' + JSON.stringify(c));
    return navigator.webkitGetUserMedia(c, onSuccess, onError);
  };
  navigator.getUserMedia = getUserMedia;

  reattachMediaStream = function(to, from) {
    to.src = from.src;
  };

  if (!navigator.mediaDevices) {
    navigator.mediaDevices = {getUserMedia: requestUserMedia,
                              enumerateDevices: function() {
      return new Promise(function(resolve) {
        var kinds = {audio: 'audioinput', video: 'videoinput'};
        return MediaStreamTrack.getSources(function(devices) {
          resolve(devices.map(function(device) {
            return {label: device.label,
                    kind: kinds[device.kind],
                    deviceId: device.id,
                    groupId: ''};
          }));
        });
      });
    }};
  }
} else if (navigator.mediaDevices && navigator.userAgent.match(
    /Edge\/(\d+).(\d+)$/)) {
  webrtcDetectedBrowser = 'edge';

  webrtcDetectedVersion =
    parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);

  // the minimum version still supported by adapter.
  webrtcMinimumVersion = 12;

  reattachMediaStream = function(to, from) {
    to.srcObject = from.srcObject;
  };
} else {
  console.log('Browser does not appear to be WebRTC-capable');
}

// Attach a media stream to an element.
attachMediaStream = function(element, stream) {
  if (typeof element.srcObject !== 'undefined') {
    element.srcObject = stream;
  } else if (typeof element.mozSrcObject !== 'undefined') {
    element.mozSrcObject = stream;
  } else if (typeof element.src !== 'undefined') {
    element.src = URL.createObjectURL(stream);
  } else {
    console.log('Error attaching stream to element.');
  }
};

// Returns the result of getUserMedia as a Promise.
function requestUserMedia(constraints) {
  return new Promise(function(resolve, reject) {
    getUserMedia(constraints, resolve, reject);
  });
}

if (typeof module !== 'undefined') {
  module.exports = {
    RTCPeerConnection: RTCPeerConnection,
    getUserMedia: getUserMedia,
    attachMediaStream: attachMediaStream,
    reattachMediaStream: reattachMediaStream,
    webrtcDetectedBrowser: webrtcDetectedBrowser,
    webrtcDetectedVersion: webrtcDetectedVersion,
    webrtcMinimumVersion: webrtcMinimumVersion
    //requestUserMedia: not exposed on purpose.
    //trace: not exposed on purpose.
  };
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
//  AutobahnJS - http://autobahn.ws, http://wamp.ws
//
//  A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
//  Copyright (c) Crossbar.io Technologies GmbH and contributors
//
//  Licensed under the MIT License.
//  http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////

var debug = function () {};

if ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG && 'console' in global) {
   debug = function () {
      console.log.apply(console, arguments);
   }
}

var warn = console.warn;

exports.debug = debug;
exports.warn = warn;
<commit_msg>Make logging work on more environments (#499)<commit_after>///////////////////////////////////////////////////////////////////////////////
//
//  AutobahnJS - http://autobahn.ws, http://wamp.ws
//
//  A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
//  Copyright (c) Crossbar.io Technologies GmbH and contributors
//
//  Licensed under the MIT License.
//  http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////

let debug = function () {};

if ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG && 'console' in global) {
   debug = function () {
      console.log.apply(console, arguments);
   }
}

let warn = console.warn.bind(console);

exports.debug = debug;
exports.warn = warn;
<|endoftext|>


<commit_before>var geocoder = new google.maps.Geocoder(),
    map,
    marker,
    featureGroup,
    representativeTemplate = _.template( // @todo Replace this one underscore dependency.
      '
' +
        '<div class="avatar" style="background-image: url(<% if (photo_url) { %><%= photo_url %><% } else { %>/static/img/silhouette.png<% } %>)">
 ' +
        '
<% if (party_name) { %><%= party_name %><% } %> ' + '<%= elected_office %> ' +
        '<% if (url) { %><a href="<%= url %>"><%= name %><% } else { %><%= name %><% } %>
 ' +
        '
<%= district_name %> <button type="button" class="btn btn-default btn-xs shape" data-url="<%= related.boundary_url %>">' + gettext('Map') + '</button>
 ' +
        '
<% if (email) { %><a href="mailto:<%= email %>">' + gettext('Email') + ' <%= first_name %><% } %>
 ' +
      '
'
    );

/**
 * @see https://learn.jquery.com/code-organization/deferreds/examples/
 */
function createCache(url) {
  var cache = {};
  return function (arg) {
    var key = arg.toString();
    if (!cache[key]) {
      cache[key] = $.ajax({dataType: 'json', url: url(arg)});
    }
    return cache[key];
  };
}

/**
 * @param L.LatLng latlng
 */
var getRepresentativesByLatLng = createCache(function (latlng) {
  return 'https://represent.opennorth.ca/representatives/?limit=0&point=' + latlng.lat + ',' + latlng.lng;
});

/**
 * @param string path the boundary's path
 */
var getBoundaryShape = createCache(function (path) {
  return path + 'simple_shape';
});

/**
 * @param L.LatLng latlng
 */
function processLatLng(latlng) {
  featureGroup.clearLayers();
  $('#map').css('visibility', 'visible');

  marker.setLatLng(latlng);
  map.panTo(latlng);

  getRepresentativesByLatLng(latlng).then(function (response) {
    var representatives = response.objects.slice(),
        groups = {},
        order = 'MP|MHA|MLA|MNA|MPP|Chair|Maire|Mayor|Regional Chair|Warden|Deputy Mayor|Deputy Warden|Councillor at Large|Regional Councillor|Conseiller|Councillor|Commissioner';

    console.log(response.objects);
    representatives.sort(function (a, b) {
      var x = order.indexOf(a['elected_office']),
          y = order.indexOf(b['elected_office']);
      if (x < y) {
        return -1;
      }
      else if (x > y) {
        return 1;
      }
      else {
        return a['last_name'] > b['last_name'];
      }
    });

    var $representatives = $('

'), $row;

    $.each(representatives, function (i, object) {
      if (i % 6 == 0) {
        $row = $('

');
        $representatives.append($row);
      }
      else if (i % 3 == 0) {
        $row.append('

')
      }
      else if (i % 2 == 0) {
        $row.append('

')
      }
      $row.append($(representativeTemplate(object)));
    });

    $('#representatives').replaceWith($representatives);

    $('#representatives').imagesLoaded().progress(function (instance, image) {
      if (!image.isLoaded) {
        $(image.img).attr('src', '/static/img/silhouette.png');
      }
    });
  });
}

function processAddress() {
  $('.alert').hide();
  $('#addresses').empty();

  geocoder.geocode({address: $('#address').val(), region: 'ca', language: gettext('en')}, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results.length > 1) {
          $('#addresses').append('<option>' + gettext('Select your address') + '</option>');
        $.each(results, function (i, result) {
          $('#addresses').append('<option data-latitude="' + result.geometry.location.lat() + '" data-longitude="' + result.geometry.location.lng() + '">' + result.formatted_address + '</option>');
        });
        $('#many-results').fadeIn('slow');
      }
      else {
        processLatLng(L.latLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
      }
    }
    else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
      $('#no-results').fadeIn('slow');
    }
    else {
      $('#unknown-error').fadeIn('slow');
    }
  });
}

$(function ($) {
  var latlng = L.latLng(45.444369, -75.693832), // 24 Sussex Drive, Ottawa
      index = window.location.href.indexOf('#'),
      anchor;

  // Create the map, marker and feature group.
  map = L.map('map', {
    attributionControl: false,
    center: latlng,
    layers: [
      L.tileLayer('https://{s}.tiles.mapbox.com/v3/jpmckinney.hlcgg444/{z}/{x}/{y}.png')
    ],
    maxZoom: 17,
    zoom: 13,
    scrollWheelZoom: false,
    touchZoom: false
  });
  marker = L.marker(latlng, {draggable: true});
  featureGroup = L.featureGroup();
  map.addLayer(marker);
  map.addLayer(featureGroup);

  // Moving the marker calls the API.
  marker.on('dragend', function () {
    $('.alert').hide();
    processLatLng(marker.getLatLng());
  });

  // Geolocation calls the API.
  map.on('locationfound', function (event) {
    $('.alert').hide();
    processLatLng(event.latlng);
  });

  // Call the API if the user submits an address.
  $('#submit').click(function (event) {
    processAddress();
    event.preventDefault();
  });

  // Call the API if the user selects on an address.
  $('#addresses').change(function (event) {
    var $this = $(this).find(':selected');
    processLatLng(L.latLng($this.data('latitude'), $this.data('longitude')));
    event.preventDefault();
  });

  // Display a boundary if user clicks on a boundary name.
  $(document).on('click', '.shape', function (event) {
    featureGroup.clearLayers();
    $.scrollTo('#map', {axis: 'y', duration: 600, easing: 'easeOutQuart', offset: -40});

    getBoundaryShape($(this).data('url')).then(function (response) {
      featureGroup.addLayer(L.geoJson(response));
      map.fitBounds(featureGroup.getBounds());
    });

    event.preventDefault();
  });

  // Perform the first geolocation.
  if (index !== -1) { // Backwards-compatibility.
    anchor = window.location.href.substr(index + 1);
  }
  if (anchor) {
    $('#address').val(unescape(anchor));
    processAddress();
  }
  else {
    map.locate({setView: true, maxZoom: 13});
  }
});
<commit_msg>fix sorting on chrom<commit_after>var geocoder = new google.maps.Geocoder(),
    map,
    marker,
    featureGroup,
    representativeTemplate = _.template( // @todo Replace this one underscore dependency.
      '
' +
        '<div class="avatar" style="background-image: url(<% if (photo_url) { %><%= photo_url %><% } else { %>/static/img/silhouette.png<% } %>)">
 ' +
        '
<% if (party_name) { %><%= party_name %><% } %> ' + '<%= elected_office %> ' +
        '<% if (url) { %><a href="<%= url %>"><%= name %><% } else { %><%= name %><% } %>
 ' +
        '
<%= district_name %> <button type="button" class="btn btn-default btn-xs shape" data-url="<%= related.boundary_url %>">' + gettext('Map') + '</button>
 ' +
        '
<% if (email) { %><a href="mailto:<%= email %>">' + gettext('Email') + ' <%= first_name %><% } %>
 ' +
      '
'
    );

/**
 * @see https://learn.jquery.com/code-organization/deferreds/examples/
 */
function createCache(url) {
  var cache = {};
  return function (arg) {
    var key = arg.toString();
    if (!cache[key]) {
      cache[key] = $.ajax({dataType: 'json', url: url(arg)});
    }
    return cache[key];
  };
}

/**
 * @param L.LatLng latlng
 */
var getRepresentativesByLatLng = createCache(function (latlng) {
  return '/representatives/?limit=0&point=' + latlng.lat + ',' + latlng.lng;
});

/**
 * @param string path the boundary's path
 */
var getBoundaryShape = createCache(function (path) {
  return path + 'simple_shape';
});

/**
 * @param L.LatLng latlng
 */
function processLatLng(latlng) {
  featureGroup.clearLayers();
  $('#map').css('visibility', 'visible');

  marker.setLatLng(latlng);
  map.panTo(latlng);

  getRepresentativesByLatLng(latlng).then(function (response) {
    var representatives = response.objects.slice(),
        groups = {},
        order = 'MP|MHA|MLA|MNA|MPP|Chair|Maire|Mayor|Regional Chair|Warden|Deputy Mayor|Deputy Warden|Councillor at Large|Regional Councillor|Conseiller|Councillor|Commissioner';

    representatives.sort(function (a, b) {
      var x = order.indexOf(a['elected_office']),
          y = order.indexOf(b['elected_office']);
      if (x < y) {
        return -1;
      }
      else if (x > y) {
        return 1;
      }
      else if (a['last_name'] < b['last_name']) {
        return -1;
      }
      else {
        return 1;
      }
    });

    var $representatives = $('

'), $row;

    $.each(representatives, function (i, object) {
      if (i % 6 == 0) {
        $row = $('

');
        $representatives.append($row);
      }
      else if (i % 3 == 0) {
        $row.append('

')
      }
      else if (i % 2 == 0) {
        $row.append('

')
      }
      $row.append($(representativeTemplate(object)));
    });

    $('#representatives').replaceWith($representatives);

    $('#representatives').imagesLoaded().progress(function (instance, image) {
      if (!image.isLoaded) {
        $(image.img).attr('src', '/static/img/silhouette.png');
      }
    });
  });
}

function processAddress() {
  $('.alert').hide();
  $('#addresses').empty();

  geocoder.geocode({address: $('#address').val(), region: 'ca', language: gettext('en')}, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results.length > 1) {
          $('#addresses').append('<option>' + gettext('Select your address') + '</option>');
        $.each(results, function (i, result) {
          $('#addresses').append('<option data-latitude="' + result.geometry.location.lat() + '" data-longitude="' + result.geometry.location.lng() + '">' + result.formatted_address + '</option>');
        });
        $('#many-results').fadeIn('slow');
      }
      else {
        processLatLng(L.latLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
      }
    }
    else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
      $('#no-results').fadeIn('slow');
    }
    else {
      $('#unknown-error').fadeIn('slow');
    }
  });
}

$(function ($) {
  var latlng = L.latLng(45.444369, -75.693832), // 24 Sussex Drive, Ottawa
      index = window.location.href.indexOf('#'),
      anchor;

  // Create the map, marker and feature group.
  map = L.map('map', {
    attributionControl: false,
    center: latlng,
    layers: [
      L.tileLayer('https://{s}.tiles.mapbox.com/v3/jpmckinney.hlcgg444/{z}/{x}/{y}.png')
    ],
    maxZoom: 17,
    zoom: 13,
    scrollWheelZoom: false,
    touchZoom: false
  });
  marker = L.marker(latlng, {draggable: true});
  featureGroup = L.featureGroup();
  map.addLayer(marker);
  map.addLayer(featureGroup);

  // Moving the marker calls the API.
  marker.on('dragend', function () {
    $('.alert').hide();
    processLatLng(marker.getLatLng());
  });

  // Geolocation calls the API.
  map.on('locationfound', function (event) {
    $('.alert').hide();
    processLatLng(event.latlng);
  });

  // Call the API if the user submits an address.
  $('#submit').click(function (event) {
    processAddress();
    event.preventDefault();
  });

  // Call the API if the user selects on an address.
  $('#addresses').change(function (event) {
    var $this = $(this).find(':selected');
    processLatLng(L.latLng($this.data('latitude'), $this.data('longitude')));
    event.preventDefault();
  });

  // Display a boundary if user clicks on a boundary name.
  $(document).on('click', '.shape', function (event) {
    featureGroup.clearLayers();
    $.scrollTo('#map', {axis: 'y', duration: 600, easing: 'easeOutQuart', offset: -40});

    getBoundaryShape($(this).data('url')).then(function (response) {
      featureGroup.addLayer(L.geoJson(response));
      map.fitBounds(featureGroup.getBounds());
    });

    event.preventDefault();
  });

  // Perform the first geolocation.
  if (index !== -1) { // Backwards-compatibility.
    anchor = window.location.href.substr(index + 1);
  }
  if (anchor) {
    $('#address').val(unescape(anchor));
    processAddress();
  }
  else {
    map.locate({setView: true, maxZoom: 13});
  }
});
<|endoftext|>


<commit_before>//# require=d3,leaflet,es6-promise.min

const HOME_LAT = 34.601841;
const HOME_LNG = 133.765894;

const PICT_MARGIN = 20;
const MAIN_PICT_CONTAINER = 0.75;
const SUB_PICT_CONTAINER = 0.25;

const PREVIEW_MARGIN = 20;
const PREVIEW_MARGIN_TOP = 10;

d3.select(root)
  .append('div')
  .attr('id', 'map-container')

d3.select('#map-container')
  .style({
      'height': root.clientHeight + 'px',
      'width': root.clientWidth + 'px'
  })

// しぇあひるずを中心に表示  setView([緯度, 経度], ズーム)
var mapLayer = L.map('map-container').setView([HOME_LAT, HOME_LNG], 15);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors',
}).addTo(mapLayer);

function update(data) {
    const SPOT_NAME_LABEL = data[0][0];
    const LAT_LABEL = data[0][3];
    const LNG_LABEL = data[0][4];
    const ERA_LABEL = data[0][5];

    d3.selectAll('.leaflet-marker-icon')
      .remove()
    // d3.selectAll('.leaflet-marker-shadow')
    //   .remove()

    var listData = data.toList();

    listData.forEach(function(spot) {

        var marker = L.marker([spot[LAT_LABEL], spot[LNG_LABEL]])
          .addTo(mapLayer)
          // .bindPopup(spot[SPOT_NAME_LABEL] + '');
          // .bindPopup(spot[SPOT_NAME_LABEL]);
          .bindPopup(spot[SPOT_NAME_LABEL] + '\n 集音日時 :' + spot[ERA_LABEL]);

        marker.on('click', function() {
            d3.select('.leaflet-popup-content').on('click', function() {

                d3.select('.leaflet-control')
                  .style('display', 'none')

                createContents(spot, data, SPOT_NAME_LABEL);
            })
        });
    });
}

// function createContents(spot, data, spotName) {
//     const DESCRIPTION_LABEL = data[0][1];
//     const ERA_LABEL = data[0][5];
//     const ADDRESS_LABEL = data[0][2];
//     const PICT1_LABEL = data[0][6];
//     const PICT2_LABEL = data[0][7];
//     const PICT3_LABEL = data[0][8];
//     const PICT4_LABEL = data[0][9];
//
//     var modalPadding = root.clientHeight / 20;
//     var pictContainerWidth = root.clientWidth - (modalPadding * 2);
//
//     var modalContent = d3.select(root)
//       .append('div')
//       .attr('id', 'modal-content')
//       .style({
//           'padding': modalPadding + 'px',
//           'width': root.clientWidth - (modalPadding * 2) + 'px',
//           'height': root.clientHeight - (modalPadding * 2) + 'px'
//       })
//
//     modalContent
//       .append('div')
//       .attr('id', 'close-button')
//       .text('×')
//       .on('click', function() {
//           d3.select('#modal-content')
//             .remove()
//           d3.select('#modal-overlay')
//             .remove()
//
//           d3.select('.leaflet-control')
//             .style('display', 'block')
//       })
//
//     modalContent
//       .append('div')
//       .attr('id', 'spot')
//       .text(spot[spotName])
//       .style('width', pictContainerWidth - document.getElementById('close-button').clientWidth + 'px')
//       .append('span')
//       .attr('id', 'era')
//       .text(function() {
//           var eraText = '';
//           if (spot[ERA_LABEL] !== '') {
//               eraText = '（' + spot[ERA_LABEL] + '）';
//           }
//           return eraText;
//       })
//
//     modalContent
//       .append('div')
//       .attr('id', 'description')
//       .text(spot[DESCRIPTION_LABEL])
//
//     modalContent
//       .append('div')
//       .attr('id', 'address')
//       .text(spot[ADDRESS_LABEL])
//       .style({
//           'position': 'absolute',
//           'bottom': modalPadding + 'px'
//       })
//
//     var pictContainerHeight = root.clientHeight
//                               - document.getElementById('spot').clientHeight
//                               - document.getElementById('description').clientHeight
//                               - document.getElementById('address').clientHeight
//                               - (PICT_MARGIN * 2)
//                               - (modalPadding * 2);
//
//     var mainPictBox = modalContent
//       .append('div')
//       .attr('id', 'main-pict-box')
//
//     var p1 = function() {
//         return new Promise(function(resolve) {
//             mainPictBox
//               .append('img')
//               .attr('id', 'picture1')
//               .attr('src', spot[PICT1_LABEL])
//               .style({
//                   'max-width': (pictContainerWidth - PICT_MARGIN) / 2 + 'px',
//                   'max-height': pictContainerHeight + 'px',
//                   'margin-right': PICT_MARGIN + 'px',
//               })
//               .on('click', function() {
//                   createPictPreview(spot[PICT1_LABEL]);
//               })
//               .on('load', function() {
//                   if (spot[PICT3_LABEL] !== '' || spot[PICT4_LABEL] !== '') {
//                       resolve(getPictSize(this));
//                   }
//               })
//         })
//     }
//
//     var p2 = function() {
//         return new Promise(function(resolve) {
//             mainPictBox
//               .append('img')
//               .attr('id', 'picture2')
//               .attr('src', spot[PICT2_LABEL])
//               .style({
//                   'max-width': (pictContainerWidth - PICT_MARGIN) / 2  + 'px',
//                   'max-height': pictContainerHeight + 'px'
//               })
//               .on('click', function() {
//                   createPictPreview(spot[PICT2_LABEL]);
//               })
//               .on('load', function() {
//                   if (spot[PICT3_LABEL] !== '' || spot[PICT4_LABEL] !== '') {
//                       resolve(getPictSize(this));
//                   }
//               })
//         })
//     }
//
//     var tasks = [ p1(), p2() ];
//     Promise.all(tasks).then(function(results) {
//
//         var pictBox = modalContent
//           .append('div')
//           .attr('id', 'sub-pict-box')
//
//         pictBox
//           .append('img')
//           .attr('id', 'picture3')
//           .attr('src', spot[PICT3_LABEL])
//           .style({
//               'max-width': (pictContainerWidth - PICT_MARGIN) / 2 + 'px',
//               'max-height': pictContainerHeight + 'px',
//               'margin-right': PICT_MARGIN + 'px',
//               'margin-top': PICT_MARGIN + 'px'
//           })
//           .on('click', function() {
//               createPictPreview(spot[PICT3_LABEL]);
//           })
//
//         pictBox
//           .append('img')
//           .attr('id', 'picture4')
//           .attr('src', spot[PICT4_LABEL])
//           .style({
//               'max-width': (pictContainerWidth - PICT_MARGIN) / 2 + 'px',
//               'max-height': pictContainerHeight + 'px',
//               'margin-top': PICT_MARGIN + 'px'
//           })
//           .on('click', function() {
//               createPictPreview(spot[PICT4_LABEL]);
//           })
//
//         if (is2PictHeightsMax(results, pictContainerHeight)) {
//             d3.select('#main-pict-box')
//               .style({
//                   'margin-right': '20px',
//                   'display': 'inline-block'
//               })
//
//             d3.select('#picture1')
//               .style('max-width', (pictContainerWidth * MAIN_PICT_CONTAINER) / 2 - PICT_MARGIN + 'px')
//
//             d3.select('#picture2')
//               .style('max-width', (pictContainerWidth * MAIN_PICT_CONTAINER) / 2 - PICT_MARGIN + 'px')
//
//             d3.select('#sub-pict-box')
//               .style('display', 'inline-block')
//
//             d3.select('#picture3')
//               .style({
//                   'display': 'block',
//                   'max-width': pictContainerWidth * SUB_PICT_CONTAINER + 'px',
//                   'max-height': (pictContainerHeight - PICT_MARGIN) / 2 + 'px',
//                   'margin-top': 0,
//                   'margin-right': 0
//               })
//
//             d3.select('#picture4')
//               .style({
//                   'display': 'block',
//                   'max-width': pictContainerWidth * SUB_PICT_CONTAINER + 'px',
//                   'max-height': (pictContainerHeight - PICT_MARGIN) / 2 + 'px',
//                   'margin-right': 0
//               })
//
//         } else {
//             d3.select('#picture1')
//               .style('max-height', pictContainerHeight * MAIN_PICT_CONTAINER + 'px')
//
//             d3.select('#picture2')
//               .style('max-height', pictContainerHeight * MAIN_PICT_CONTAINER + 'px')
//
//             d3.select('#picture3')
//               .style('max-height', (pictContainerHeight - PICT_MARGIN) * SUB_PICT_CONTAINER + 'px')
//
//             d3.select('#picture4')
//               .style('max-height', (pictContainerHeight - PICT_MARGIN) * SUB_PICT_CONTAINER + 'px')
//         }
//     })
//
//     d3.select(root)
//       .append('div')
//       .attr('id', 'modal-overlay')
// }

var getPictSize = function(self) {
    var pictSize = { };
    pictSize.width = parseInt(d3.select(self).style('width'));
    pictSize.height = parseInt(d3.select(self).style('height'));
    return pictSize;
}

var is2PictHeightsMax = function(pictArray, pictContainerHeight) {
    return pictArray[0].height == parseInt(pictContainerHeight)
        && pictArray[1].height == parseInt(pictContainerHeight);
}

function createPictPreview(picture) {
    d3.select(root)
      .append('div')
      .attr('id', 'pict-overlay')

    d3.select(root)
      .append('div')
      .attr('id', 'preview-area')
      .text('click the picture to close')

    d3.select(root)
      .append('img')
      .attr('id', 'pict-preview')
      .attr('src', picture)
      .style({
          'max-width': root.clientWidth - PREVIEW_MARGIN * 2 + 'px',
          'max-height': root.clientHeight - PREVIEW_MARGIN * 2 - PREVIEW_MARGIN_TOP + 'px'
      })
      .on('load', function() {
          var width = parseInt(
              d3.select('#pict-preview')
                .style('width')
              )

          var height = parseInt(
              d3.select('#pict-preview')
                .style('height')
              )

          if (width == parseInt(root.clientWidth) - PREVIEW_MARGIN * 2) {
              setFullWidthPictPreview(height);

          } else {
              setFullHeightPictPreview(width);
          }
      })
      .on('click', function() {
          removePictPreview();
      })
}

var setFullWidthPictPreview = function(height) {
    d3.select('#preview-area')
      .style({
          'width': root.clientWidth - PREVIEW_MARGIN * 2 + 'px',
          'height': height + PREVIEW_MARGIN + PREVIEW_MARGIN_TOP + 'px',
          'top': (root.clientHeight - height - PREVIEW_MARGIN) / 2 + 'px'
      })

    d3.select('#pict-preview')
      .style({
          'top': (root.clientHeight - height) / 2 + PREVIEW_MARGIN_TOP + 'px'
      })
}

var setFullHeightPictPreview = function(width) {
    d3.select('#preview-area')
      .style({
          'width': width + 'px',
          'height': root.clientHeight - PREVIEW_MARGIN + 'px',
          'left': (root.clientWidth - width - PREVIEW_MARGIN) / 2 + 'px'
      })

    d3.select('#pict-preview')
      .style({
          'left': (root.clientWidth - width) / 2 + 'px'
      })
}

// var removePictPreview = function() {
//     d3.select('#preview-area')
//       .remove()
//     d3.select('#pict-preview')
//       .remove()
//     d3.select('#pict-overlay')
//       .remove()
// }
<commit_msg>音量の後に開業コードを追加<commit_after>//# require=d3,leaflet,es6-promise.min

const HOME_LAT = 34.601841;
const HOME_LNG = 133.765894;

const PICT_MARGIN = 20;
const MAIN_PICT_CONTAINER = 0.75;
const SUB_PICT_CONTAINER = 0.25;

const PREVIEW_MARGIN = 20;
const PREVIEW_MARGIN_TOP = 10;

d3.select(root)
  .append('div')
  .attr('id', 'map-container')

d3.select('#map-container')
  .style({
      'height': root.clientHeight + 'px',
      'width': root.clientWidth + 'px'
  })

// しぇあひるずを中心に表示  setView([緯度, 経度], ズーム)
var mapLayer = L.map('map-container').setView([HOME_LAT, HOME_LNG], 15);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors',
}).addTo(mapLayer);

function update(data) {
    const SPOT_NAME_LABEL = data[0][0];
    const LAT_LABEL = data[0][3];
    const LNG_LABEL = data[0][4];
    const ERA_LABEL = data[0][5];

    d3.selectAll('.leaflet-marker-icon')
      .remove()
    // d3.selectAll('.leaflet-marker-shadow')
    //   .remove()

    var listData = data.toList();

    listData.forEach(function(spot) {

        var marker = L.marker([spot[LAT_LABEL], spot[LNG_LABEL]])
          .addTo(mapLayer)
          // .bindPopup(spot[SPOT_NAME_LABEL] + '');
          // .bindPopup(spot[SPOT_NAME_LABEL]);
          .bindPopup(spot[SPOT_NAME_LABEL] + '
 集音日時 :' + spot[ERA_LABEL]);

        marker.on('click', function() {
            d3.select('.leaflet-popup-content').on('click', function() {

                d3.select('.leaflet-control')
                  .style('display', 'none')

                createContents(spot, data, SPOT_NAME_LABEL);
            })
        });
    });
}

// function createContents(spot, data, spotName) {
//     const DESCRIPTION_LABEL = data[0][1];
//     const ERA_LABEL = data[0][5];
//     const ADDRESS_LABEL = data[0][2];
//     const PICT1_LABEL = data[0][6];
//     const PICT2_LABEL = data[0][7];
//     const PICT3_LABEL = data[0][8];
//     const PICT4_LABEL = data[0][9];
//
//     var modalPadding = root.clientHeight / 20;
//     var pictContainerWidth = root.clientWidth - (modalPadding * 2);
//
//     var modalContent = d3.select(root)
//       .append('div')
//       .attr('id', 'modal-content')
//       .style({
//           'padding': modalPadding + 'px',
//           'width': root.clientWidth - (modalPadding * 2) + 'px',
//           'height': root.clientHeight - (modalPadding * 2) + 'px'
//       })
//
//     modalContent
//       .append('div')
//       .attr('id', 'close-button')
//       .text('×')
//       .on('click', function() {
//           d3.select('#modal-content')
//             .remove()
//           d3.select('#modal-overlay')
//             .remove()
//
//           d3.select('.leaflet-control')
//             .style('display', 'block')
//       })
//
//     modalContent
//       .append('div')
//       .attr('id', 'spot')
//       .text(spot[spotName])
//       .style('width', pictContainerWidth - document.getElementById('close-button').clientWidth + 'px')
//       .append('span')
//       .attr('id', 'era')
//       .text(function() {
//           var eraText = '';
//           if (spot[ERA_LABEL] !== '') {
//               eraText = '（' + spot[ERA_LABEL] + '）';
//           }
//           return eraText;
//       })
//
//     modalContent
//       .append('div')
//       .attr('id', 'description')
//       .text(spot[DESCRIPTION_LABEL])
//
//     modalContent
//       .append('div')
//       .attr('id', 'address')
//       .text(spot[ADDRESS_LABEL])
//       .style({
//           'position': 'absolute',
//           'bottom': modalPadding + 'px'
//       })
//
//     var pictContainerHeight = root.clientHeight
//                               - document.getElementById('spot').clientHeight
//                               - document.getElementById('description').clientHeight
//                               - document.getElementById('address').clientHeight
//                               - (PICT_MARGIN * 2)
//                               - (modalPadding * 2);
//
//     var mainPictBox = modalContent
//       .append('div')
//       .attr('id', 'main-pict-box')
//
//     var p1 = function() {
//         return new Promise(function(resolve) {
//             mainPictBox
//               .append('img')
//               .attr('id', 'picture1')
//               .attr('src', spot[PICT1_LABEL])
//               .style({
//                   'max-width': (pictContainerWidth - PICT_MARGIN) / 2 + 'px',
//                   'max-height': pictContainerHeight + 'px',
//                   'margin-right': PICT_MARGIN + 'px',
//               })
//               .on('click', function() {
//                   createPictPreview(spot[PICT1_LABEL]);
//               })
//               .on('load', function() {
//                   if (spot[PICT3_LABEL] !== '' || spot[PICT4_LABEL] !== '') {
//                       resolve(getPictSize(this));
//                   }
//               })
//         })
//     }
//
//     var p2 = function() {
//         return new Promise(function(resolve) {
//             mainPictBox
//               .append('img')
//               .attr('id', 'picture2')
//               .attr('src', spot[PICT2_LABEL])
//               .style({
//                   'max-width': (pictContainerWidth - PICT_MARGIN) / 2  + 'px',
//                   'max-height': pictContainerHeight + 'px'
//               })
//               .on('click', function() {
//                   createPictPreview(spot[PICT2_LABEL]);
//               })
//               .on('load', function() {
//                   if (spot[PICT3_LABEL] !== '' || spot[PICT4_LABEL] !== '') {
//                       resolve(getPictSize(this));
//                   }
//               })
//         })
//     }
//
//     var tasks = [ p1(), p2() ];
//     Promise.all(tasks).then(function(results) {
//
//         var pictBox = modalContent
//           .append('div')
//           .attr('id', 'sub-pict-box')
//
//         pictBox
//           .append('img')
//           .attr('id', 'picture3')
//           .attr('src', spot[PICT3_LABEL])
//           .style({
//               'max-width': (pictContainerWidth - PICT_MARGIN) / 2 + 'px',
//               'max-height': pictContainerHeight + 'px',
//               'margin-right': PICT_MARGIN + 'px',
//               'margin-top': PICT_MARGIN + 'px'
//           })
//           .on('click', function() {
//               createPictPreview(spot[PICT3_LABEL]);
//           })
//
//         pictBox
//           .append('img')
//           .attr('id', 'picture4')
//           .attr('src', spot[PICT4_LABEL])
//           .style({
//               'max-width': (pictContainerWidth - PICT_MARGIN) / 2 + 'px',
//               'max-height': pictContainerHeight + 'px',
//               'margin-top': PICT_MARGIN + 'px'
//           })
//           .on('click', function() {
//               createPictPreview(spot[PICT4_LABEL]);
//           })
//
//         if (is2PictHeightsMax(results, pictContainerHeight)) {
//             d3.select('#main-pict-box')
//               .style({
//                   'margin-right': '20px',
//                   'display': 'inline-block'
//               })
//
//             d3.select('#picture1')
//               .style('max-width', (pictContainerWidth * MAIN_PICT_CONTAINER) / 2 - PICT_MARGIN + 'px')
//
//             d3.select('#picture2')
//               .style('max-width', (pictContainerWidth * MAIN_PICT_CONTAINER) / 2 - PICT_MARGIN + 'px')
//
//             d3.select('#sub-pict-box')
//               .style('display', 'inline-block')
//
//             d3.select('#picture3')
//               .style({
//                   'display': 'block',
//                   'max-width': pictContainerWidth * SUB_PICT_CONTAINER + 'px',
//                   'max-height': (pictContainerHeight - PICT_MARGIN) / 2 + 'px',
//                   'margin-top': 0,
//                   'margin-right': 0
//               })
//
//             d3.select('#picture4')
//               .style({
//                   'display': 'block',
//                   'max-width': pictContainerWidth * SUB_PICT_CONTAINER + 'px',
//                   'max-height': (pictContainerHeight - PICT_MARGIN) / 2 + 'px',
//                   'margin-right': 0
//               })
//
//         } else {
//             d3.select('#picture1')
//               .style('max-height', pictContainerHeight * MAIN_PICT_CONTAINER + 'px')
//
//             d3.select('#picture2')
//               .style('max-height', pictContainerHeight * MAIN_PICT_CONTAINER + 'px')
//
//             d3.select('#picture3')
//               .style('max-height', (pictContainerHeight - PICT_MARGIN) * SUB_PICT_CONTAINER + 'px')
//
//             d3.select('#picture4')
//               .style('max-height', (pictContainerHeight - PICT_MARGIN) * SUB_PICT_CONTAINER + 'px')
//         }
//     })
//
//     d3.select(root)
//       .append('div')
//       .attr('id', 'modal-overlay')
// }

var getPictSize = function(self) {
    var pictSize = { };
    pictSize.width = parseInt(d3.select(self).style('width'));
    pictSize.height = parseInt(d3.select(self).style('height'));
    return pictSize;
}

var is2PictHeightsMax = function(pictArray, pictContainerHeight) {
    return pictArray[0].height == parseInt(pictContainerHeight)
        && pictArray[1].height == parseInt(pictContainerHeight);
}

function createPictPreview(picture) {
    d3.select(root)
      .append('div')
      .attr('id', 'pict-overlay')

    d3.select(root)
      .append('div')
      .attr('id', 'preview-area')
      .text('click the picture to close')

    d3.select(root)
      .append('img')
      .attr('id', 'pict-preview')
      .attr('src', picture)
      .style({
          'max-width': root.clientWidth - PREVIEW_MARGIN * 2 + 'px',
          'max-height': root.clientHeight - PREVIEW_MARGIN * 2 - PREVIEW_MARGIN_TOP + 'px'
      })
      .on('load', function() {
          var width = parseInt(
              d3.select('#pict-preview')
                .style('width')
              )

          var height = parseInt(
              d3.select('#pict-preview')
                .style('height')
              )

          if (width == parseInt(root.clientWidth) - PREVIEW_MARGIN * 2) {
              setFullWidthPictPreview(height);

          } else {
              setFullHeightPictPreview(width);
          }
      })
      .on('click', function() {
          removePictPreview();
      })
}

var setFullWidthPictPreview = function(height) {
    d3.select('#preview-area')
      .style({
          'width': root.clientWidth - PREVIEW_MARGIN * 2 + 'px',
          'height': height + PREVIEW_MARGIN + PREVIEW_MARGIN_TOP + 'px',
          'top': (root.clientHeight - height - PREVIEW_MARGIN) / 2 + 'px'
      })

    d3.select('#pict-preview')
      .style({
          'top': (root.clientHeight - height) / 2 + PREVIEW_MARGIN_TOP + 'px'
      })
}

var setFullHeightPictPreview = function(width) {
    d3.select('#preview-area')
      .style({
          'width': width + 'px',
          'height': root.clientHeight - PREVIEW_MARGIN + 'px',
          'left': (root.clientWidth - width - PREVIEW_MARGIN) / 2 + 'px'
      })

    d3.select('#pict-preview')
      .style({
          'left': (root.clientWidth - width) / 2 + 'px'
      })
}

// var removePictPreview = function() {
//     d3.select('#preview-area')
//       .remove()
//     d3.select('#pict-preview')
//       .remove()
//     d3.select('#pict-overlay')
//       .remove()
// }
<|endoftext|>


<commit_before>'use strict';
var config = require('./saucelabs.config');
var assert = require('assert');
var test = require('selenium-webdriver/testing');
var webdriver = require('selenium-webdriver');

var isSauceLabsTest = false;
var sauceLabsCaps = config.saucelabs.browserCaps;

var SAUCE_URL = 'http://ondemand.saucelabs.com:80/wd/hub';
var DBC_URLS = ['http://uxwin7-01:4444/wd/hub', 'http://uxwin81-01:4444/wd/hub', 'http://uxwin10-01:5432/wd/hub'];
var BASE_URL = isSauceLabsTest ? 'https://pg.demo.dbc.dk' : process.env.SELENIUM_URL || 'http://localhost:8080'; // eslint-disable-line

function runAllTests(driverCaps) {
  test.describe('Express endpoint', function () {
    test.it('/profile/login can be reached', function () {
      var endpoint = '/profile/login';
      var driver = driverCaps.build();
      driver.get(BASE_URL + endpoint);
      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'body'})), 12000);
      var body = driver.findElement({tagName: 'body'});
      var header = body.findElement({id: 'header'});

      header.getId()
        .then(function (id) {
          assert.notEqual(typeof id, 'undefined');
        });

      driver.quit();
    });

    test.it('/profile/signup can be reached', function () {
      var endpoint = '/profile/signup';
      var driver = driverCaps.build();
      driver.get(BASE_URL + endpoint);
      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'body'})), 12000);
      var body = driver.findElement({tagName: 'body'});
      var header = body.findElement({id: 'header'});

      header.getId()
        .then(function (id) {
          assert.notEqual(typeof id, 'undefined');
        });

      driver.quit();
    });
  });

  test.describe('Login page', function () {
    test.it('is rendered', function () {
      var endpoint = '/profile/login';
      var driver = driverCaps.build();
      driver.get(BASE_URL + endpoint);
      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'input', name: 'username'})), 5000);
      var emailInput = driver.findElement({tagName: 'input', name: 'username'});
      emailInput.sendKeys('rasmussen.matias@gmail.com');
      driver.quit();
    });
  });

  test.describe('Signup page', function () {
    test.it('is rendered', function () {
      var endpoint = '/profile/signup';
      var driver = driverCaps.build();
      driver.get(BASE_URL + endpoint);
      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'input', name: 'username'})), 5000);
      driver.quit();
    });
  });

  test.describe('Library Suggest - Autocomplete', function () {
    test.it('returns suggestions', function () {
      var driver = driverCaps.build();

      driver.get(BASE_URL + '/library/suggest');

      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'input'})), 5000);

      var searchField = driver.findElement({tagName: 'input'});

      searchField.sendKeys('køb');

      driver.wait(webdriver.until.elementLocated(webdriver.By.className('autocomplete--row-text')), 5000);

      var acRow = driver.findElement(webdriver.By.className('autocomplete--row-text'));

      acRow.getInnerHtml().then(function(html) {
        assert.notEqual(typeof html, 'undefined');
      });

      acRow.click();

      driver.quit();
    });
  });

  test.describe('Library', function () {
    test.it('SSR rendering of library', function () {
      var driver = driverCaps.build();
      var libraryId = '710100';
      var branchName = 'Hovedbiblioteket, Krystalgade';

      // ssrTimeout url param sets how many milliseconds to wait for data
      // Test times out before the ssrTimeout to ensure whats sent is rendered server side
      // If this test functions it SSR must work
      driver.get(BASE_URL + '/library?id=' + libraryId + '&ssrTimeout=900000');
      driver.wait(webdriver.until.elementLocated(webdriver.By.className('library--branch-name')), 5000);

      var libraryTitle = driver.findElement(webdriver.By.className('library--branch-name'));
      libraryTitle.getInnerHtml().then(function (html) {
        assert.equal(html, branchName);
      });

      driver.quit();
    });
  });
}

if (isSauceLabsTest) {
  for (var k in sauceLabsCaps) {
    if (sauceLabsCaps.hasOwnProperty(k)) {
      var caps = sauceLabsCaps[k];
      caps.username = config.saucelabs.username;
      caps.accessKey = config.saucelabs.accessKey;
      var sauceDriverCaps = new webdriver.Builder().
        usingServer(SAUCE_URL).
        withCapabilities(caps);

      runAllTests(sauceDriverCaps);
    }
  }
}
else if (process.env.JENKINS_TESTING || false) { // eslint-disable-line
  var driver = new webdriver.Builder()
    .forBrowser(process.env.SELENIUM_BROWSER_NAME || 'internet explorer') // eslint-disable-line
    .usingServer(process.env.SELENIUM_TEST_SERVER || DBC_URLS[1]); // eslint-disable-line

  runAllTests(driver);
}
else {
  var chromeCaps = new webdriver.Builder()
    .withCapabilities(webdriver.Capabilities.chrome());

  runAllTests(chromeCaps);
}
<commit_msg>Accumulated commit of the following from branch 'origin/ready/jph-us126':<commit_after>'use strict';
var config = require('./saucelabs.config');
var assert = require('assert');
var test = require('selenium-webdriver/testing');
var webdriver = require('selenium-webdriver');

var isSauceLabsTest = false;
var sauceLabsCaps = config.saucelabs.browserCaps;

var SAUCE_URL = 'http://ondemand.saucelabs.com:80/wd/hub';
var DBC_URLS = ['http://uxwin7-01:4444/wd/hub', 'http://uxwin81-01:4444/wd/hub', 'http://uxwin10-01:5432/wd/hub'];
var BASE_URL = isSauceLabsTest ? 'https://pg.demo.dbc.dk' : process.env.SELENIUM_URL || 'http://localhost:8080'; // eslint-disable-line
var driverTimeout = process.env.DRIVER_TIMEOUT || 10000; // eslint-disable-line no-process-env

function runAllTests(driverCaps) {
  test.describe('Express endpoint', function () {
    test.it('/profile/login can be reached', function () {
      var endpoint = '/profile/login';
      var driver = driverCaps.build();
      driver.get(BASE_URL + endpoint);
      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'body'})), driverTimeout);
      var body = driver.findElement({tagName: 'body'});
      var header = body.findElement({id: 'header'});

      header.getId()
        .then(function (id) {
          assert.notEqual(typeof id, 'undefined');
        });

      driver.quit();
    });

    test.it('/profile/signup can be reached', function () {
      var endpoint = '/profile/signup';
      var driver = driverCaps.build();
      driver.get(BASE_URL + endpoint);
      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'body'})), driverTimeout);
      var body = driver.findElement({tagName: 'body'});
      var header = body.findElement({id: 'header'});

      header.getId()
        .then(function (id) {
          assert.notEqual(typeof id, 'undefined');
        });

      driver.quit();
    });
  });

  test.describe('Login page', function () {
    test.it('is rendered', function () {
      var endpoint = '/profile/login';
      var driver = driverCaps.build();
      driver.get(BASE_URL + endpoint);
      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'input', name: 'username'})), driverTimeout);
      var emailInput = driver.findElement({tagName: 'input', name: 'username'});
      emailInput.sendKeys('rasmussen.matias@gmail.com');
      driver.quit();
    });
  });

  test.describe('Signup page', function () {
    test.it('is rendered', function () {
      var endpoint = '/profile/signup';
      var driver = driverCaps.build();
      driver.get(BASE_URL + endpoint);
      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'input', name: 'username'})), driverTimeout);
      driver.quit();
    });
  });

  test.describe('Library Suggest - Autocomplete', function () {
    test.it('returns suggestions', function () {
      var driver = driverCaps.build();

      driver.get(BASE_URL + '/library/suggest');

      driver.wait(webdriver.until.elementIsVisible(driver.findElement({tagName: 'input'})), driverTimeout);

      var searchField = driver.findElement({tagName: 'input'});

      searchField.sendKeys('køb');

      driver.wait(webdriver.until.elementLocated(webdriver.By.className('autocomplete--row-text')), driverTimeout);

      var acRow = driver.findElement(webdriver.By.className('autocomplete--row-text'));

      acRow.getInnerHtml().then(function(html) {
        assert.notEqual(typeof html, 'undefined');
      });

      acRow.click();

      driver.quit();
    });
  });

  test.describe('Library', function () {
    test.it('SSR rendering of library', function () {
      var driver = driverCaps.build();
      var libraryId = '710100';
      var branchName = 'Hovedbiblioteket, Krystalgade';

      // ssrTimeout url param sets how many milliseconds to wait for data
      // Test times out before the ssrTimeout to ensure whats sent is rendered server side
      // If this test functions it SSR must work
      driver.get(BASE_URL + '/library?id=' + libraryId + '&ssrTimeout=900000');
      driver.wait(webdriver.until.elementLocated(webdriver.By.className('library--branch-name')), driverTimeout);

      var libraryTitle = driver.findElement(webdriver.By.className('library--branch-name'));
      libraryTitle.getInnerHtml().then(function (html) {
        assert.equal(html, branchName);
      });

      driver.quit();
    });
  });
}

if (isSauceLabsTest) {
  for (var k in sauceLabsCaps) {
    if (sauceLabsCaps.hasOwnProperty(k)) {
      var caps = sauceLabsCaps[k];
      caps.username = config.saucelabs.username;
      caps.accessKey = config.saucelabs.accessKey;
      var sauceDriverCaps = new webdriver.Builder().
        usingServer(SAUCE_URL).
        withCapabilities(caps);

      runAllTests(sauceDriverCaps);
    }
  }
}
else if (process.env.JENKINS_TESTING || false) { // eslint-disable-line
  var driver = new webdriver.Builder()
    .forBrowser(process.env.SELENIUM_BROWSER_NAME || 'internet explorer') // eslint-disable-line
    .usingServer(process.env.SELENIUM_TEST_SERVER || DBC_URLS[1]); // eslint-disable-line

  runAllTests(driver);
}
else {
  var chromeCaps = new webdriver.Builder()
    .withCapabilities(webdriver.Capabilities.chrome());

  runAllTests(chromeCaps);
}
<|endoftext|>


<commit_before>import should from 'should';
import { transformString } from '../src/transform';

function test(input, output) {
  it(input, () => should(transformString(input)).equal(output));
}

describe('transform', () => {
  it('should turn a string into a string',
    () => transformString("()").should.be.a.String());

  describe('variables', () => {
    test('(let a 2)', 'var a = 2;');
    test('(let a 2 b 4 c 5)', 'var a = 2, b = 4, c = 5;');
    test('(let a (+ 1 2))', 'var a = (1 + 2);');
  });

  describe('math', () => {
    test('(+ 1 2)', '(1 + 2)');
    test('(- 9 6)', '(9 - 6)');
    test('(* 2 3)', '(2 * 3)');
    test('(/ 4 2)', '(4 / 2)');
    test('(* (+ 2 4) (- 5 3))', '((2 + 4) * (5 - 3))');
    test('(+ 2 3 4 5)', '(2 + 3 + 4 + 5)');

    test('(Math.pow 2 4)', 'Math.pow( 2, 4 )');
    test('(Math.abs -4)', 'Math.abs( -4 )');
    test('(Math.pow (* 2 3) (- 2 4))', 'Math.pow( (2 * 3), (2 - 4) )');
  });

  describe('control flow', () => {
    describe('if else', () => {});
    describe('for loops', () => {});
    describe('while loops', () => {});
  });

  describe('function literals', () => {
    test('(function ())', '(function () { return undefined;})');
    test('(function () 4)', '(function () { return 4;})');
    test('(function (x y) (+ x y))', '(function (x, y) { return (x + y);})');
    test('(function adder (x y) (+ x y))', '(function adder(x, y) { return (x + y);})');
    test('(function (x) (function (y) (+ x y)))', '(function (x) { return (function (y) { return (x + y);});})');
  });

  describe('function calls', () => {
    test('(some_func 1 2 3)', 'some_func( 1, 2, 3 )');
    test('(func 1 (nested 2 3))', 'func( 1, nested( 2, 3 ) )');
    test('(empty_func)', 'empty_func(  )');
  });

  describe('data structures', () => {
    describe('arrays', () => {});
    describe('objects', () => {});
  });

  describe('modules', () => {
    test(`
      (module testEm
        (+ 1 2))
      `,
      `module('testEm', function (require, export) {(1 + 2);})`);
    test(`
      (module testEm
        (export varA (+ 1 2)))
      `,
      `module('testEm', function (require, export) {export('varA', (1 + 2));})`);
    test(`
      (module testEmA
        (require testEmB (var-a)))
      `,
      `module('testEmA', function (require, export) {
         var testEmB = require('testEmB');
         var varA = testEmB['varA'];
       })`);
    test(`
      (module testEmA
        (require testEmB
          (varA
           varB
           varC)))
      `,
      `module('testEmA', function (require, export) {
         var testEmB = require('testEmB');
         var varA = testEmB['varA'];
         var varB = testEmB['varB'];
         var varC = testEmB['varC'];
       })`);
  });

  describe('calling methods on dynamic entities', () => {});
});
<commit_msg>fix an easy one<commit_after>import should from 'should';
import { transformString } from '../src/transform';

function test(input, output) {
  it(input, () => should(transformString(input)).equal(output));
}

describe('transform', () => {
  it('should turn a string into a string',
    () => transformString("()").should.be.a.String());

  describe('variables', () => {
    test('(let a 2)', 'var a = 2;');
    test('(let a 2 b 4 c 5)', 'var a = 2, b = 4, c = 5;');
    test('(let a (+ 1 2))', 'var a = (1 + 2);');
  });

  describe('math', () => {
    test('(+ 1 2)', '(1 + 2)');
    test('(- 9 6)', '(9 - 6)');
    test('(* 2 3)', '(2 * 3)');
    test('(/ 4 2)', '(4 / 2)');
    test('(* (+ 2 4) (- 5 3))', '((2 + 4) * (5 - 3))');
    test('(+ 2 3 4 5)', '(2 + 3 + 4 + 5)');

    test('(Math.pow 2 4)', 'Math.pow( 2, 4 )');
    test('(Math.abs -4)', 'Math.abs( -4 )');
    test('(Math.pow (* 2 3) (- 2 4))', 'Math.pow( (2 * 3), (2 - 4) )');
  });

  describe('control flow', () => {
    describe('if else', () => {});
    describe('for loops', () => {});
    describe('while loops', () => {});
  });

  describe('function literals', () => {
    test('(function ())', '(function () { return undefined;})');
    test('(function () 4)', '(function () { return 4;})');
    test('(function (x y) (+ x y))', '(function (x, y) { return (x + y);})');
    test('(function adder (x y) (+ x y))', '(function adder(x, y) { return (x + y);})');
    test('(function (x) (function (y) (+ x y)))', '(function (x) { return (function (y) { return (x + y);});})');
  });

  describe('function calls', () => {
    test('(some_func 1 2 3)', 'some_func( 1, 2, 3 )');
    test('(func 1 (nested 2 3))', 'func( 1, nested( 2, 3 ) )');
    test('(empty_func)', 'empty_func()');
  });

  describe('data structures', () => {
    describe('arrays', () => {});
    describe('objects', () => {});
  });

  describe('modules', () => {
    test(`
      (module testEm
        (+ 1 2))
      `,
      `module('testEm', function (require, export) {(1 + 2);})`);
    test(`
      (module testEm
        (export varA (+ 1 2)))
      `,
      `module('testEm', function (require, export) {export('varA', (1 + 2));})`);
    test(`
      (module testEmA
        (require testEmB (var-a)))
      `,
      `module('testEmA', function (require, export) {
         var testEmB = require('testEmB');
         var varA = testEmB['varA'];
       })`);
    test(`
      (module testEmA
        (require testEmB
          (varA
           varB
           varC)))
      `,
      `module('testEmA', function (require, export) {
         var testEmB = require('testEmB');
         var varA = testEmB['varA'];
         var varB = testEmB['varB'];
         var varC = testEmB['varC'];
       })`);
  });

  describe('calling methods on dynamic entities', () => {});
});
<|endoftext|>


<commit_before>
import React, {
    NetInfo
} from 'react-native';

import _ from 'lodash';
import Config from '../config';
import entities from 'entities';

export function getBloggerName(authorUri) {
    authorUri = _.trimEnd(authorUri, '\/');
    return authorUri.slice(authorUri.lastIndexOf("\/") + 1);
}

const seedColors = ['#ec898a', '#69bb97', '#55b9ce', '#cc936e', '#65be8d', '#6bb6cb', '#ae9cc3'];
export function getRandomColor(){
    return seedColors[_.random(0, seedColors.length -1)];
}

export function getBloggerAvatar(avatarUri){
    if (avatarUri && !_.endsWith(avatarUri, ".gif")) {
        avatarUri = avatarUri.replace(/face/, 'avatar');
        avatarUri = avatarUri.replace(/avatar\/u/, 'avatar\/a');
        return avatarUri;
    }
    return "http://www.sucaijishi.com/uploadfile/2016/0203/20160203022631602.png";
}

export function filterCodeSnippet(codeText) {
    if (codeText && codeText.length) {
        codeText = _.trim(codeText);
        codeText = _.trim(codeText, '
');
        if (codeText.startsWith(' ') || codeText.endsWith(' ') || codeText.startsWith('
') || codeText.endsWith('
')) {
            codeText = filterCodeSnippet(codeText);
        }
    }
    return codeText;
}

export function filterCommentData(commentText) {
    if (commentText && commentText.length) {
        commentText = commentText.replace(/<(script)[\S\s]*?\1>|<\/?(a|img)[^>]*>/gi, "");
        commentText = "<comment>" + commentText + "</comment>";
    }
    return commentText;
}

export function decodeHTML(htmlStr) {
    if (htmlStr && htmlStr.length) {
        htmlStr = entities.decodeHTML(htmlStr);
    }
    return htmlStr;
}

const imageSourcePath = Config.domain + "/public/img/metarial/";
export function getImageSource(key){
    let imageLen = 20;
    if (!key) {
        key = _.random(1, imageLen - 1);
    }
    return imageSourcePath + key + ".jpg?v=1.1";
}
<commit_msg>update author default avatar uri<commit_after>
import React, {
    NetInfo
} from 'react-native';

import _ from 'lodash';
import Config from '../config';
import entities from 'entities';

export function getBloggerName(authorUri) {
    authorUri = _.trimEnd(authorUri, '\/');
    return authorUri.slice(authorUri.lastIndexOf("\/") + 1);
}

const seedColors = ['#ec898a', '#69bb97', '#55b9ce', '#cc936e', '#65be8d', '#6bb6cb', '#ae9cc3'];
export function getRandomColor(){
    return seedColors[_.random(0, seedColors.length -1)];
}

export function getBloggerAvatar(avatarUri){
    if (avatarUri && !_.endsWith(avatarUri, ".gif")) {
        avatarUri = avatarUri.replace(/face/, 'avatar');
        avatarUri = avatarUri.replace(/avatar\/u/, 'avatar\/a');
        return avatarUri;
    }
    return Config.appInfo.avatar;
}

export function filterCodeSnippet(codeText) {
    if (codeText && codeText.length) {
        codeText = _.trim(codeText);
        codeText = _.trim(codeText, '
');
        if (codeText.startsWith(' ') || codeText.endsWith(' ') || codeText.startsWith('
') || codeText.endsWith('
')) {
            codeText = filterCodeSnippet(codeText);
        }
    }
    return codeText;
}

export function filterCommentData(commentText) {
    if (commentText && commentText.length) {
        commentText = commentText.replace(/<(script)[\S\s]*?\1>|<\/?(a|img)[^>]*>/gi, "");
        commentText = "<comment>" + commentText + "</comment>";
    }
    return commentText;
}

export function decodeHTML(htmlStr) {
    if (htmlStr && htmlStr.length) {
        htmlStr = entities.decodeHTML(htmlStr);
    }
    return htmlStr;
}

const imageSourcePath = Config.domain + "/public/img/metarial/";
export function getImageSource(key){
    let imageLen = 20;
    if (!key) {
        key = _.random(1, imageLen - 1);
    }
    return imageSourcePath + key + ".jpg?v=1.1";
}
<|endoftext|>


<commit_before>import * as core from '@candela/core';
import * as events from '@candela/events';
import * as geojs from '@candela/geojs';
import * as glo from '@candela/glo';
import * as lineup from '@candela/lineup';
import * as onset from '@candela/onset';
import * as sententree from '@candela/sententree';
import * as similaritygraph from '@candela/similaritygraph';
import * as size from '@candela/size';
import * as stats from '@candela/stats';
import * as treeheatmap from '@candela/treeheatmap';
import * as upset from '@candela/upset';
import * as vega from '@candela/vega';

function load (obj, target) {
  for (let prop in obj) {
    target[prop] = obj[prop];
  }
}

// Collect all candela components into a single object.
let components = {};
for (let bundle of [geojs, glo, lineup, onset, sententree, similaritygraph, stats, treeheatmap, upset]) {
  load(bundle, components);
}
for (let component in vega) {
  if (vega[component] !== vega.VegaView) {
    components[component] = vega[component]
  }
}

// Collect all candela mixings into a single object.
let mixins = {};
for (let bundle of [events, size]) {
  load(bundle, mixins);
}
mixins.VegaView = vega.VegaView;

let VisComponent = core.VisComponent;

// Export everything, both as default...
export default {
  VisComponent,
  components,
  mixins
};

// ...and non-default.
export {
  VisComponent,
  components,
  mixins
};
<commit_msg>style(all): add missing semicolon<commit_after>import * as core from '@candela/core';
import * as events from '@candela/events';
import * as geojs from '@candela/geojs';
import * as glo from '@candela/glo';
import * as lineup from '@candela/lineup';
import * as onset from '@candela/onset';
import * as sententree from '@candela/sententree';
import * as similaritygraph from '@candela/similaritygraph';
import * as size from '@candela/size';
import * as stats from '@candela/stats';
import * as treeheatmap from '@candela/treeheatmap';
import * as upset from '@candela/upset';
import * as vega from '@candela/vega';

function load (obj, target) {
  for (let prop in obj) {
    target[prop] = obj[prop];
  }
}

// Collect all candela components into a single object.
let components = {};
for (let bundle of [geojs, glo, lineup, onset, sententree, similaritygraph, stats, treeheatmap, upset]) {
  load(bundle, components);
}
for (let component in vega) {
  if (vega[component] !== vega.VegaView) {
    components[component] = vega[component];
  }
}

// Collect all candela mixings into a single object.
let mixins = {};
for (let bundle of [events, size]) {
  load(bundle, mixins);
}
mixins.VegaView = vega.VegaView;

let VisComponent = core.VisComponent;

// Export everything, both as default...
export default {
  VisComponent,
  components,
  mixins
};

// ...and non-default.
export {
  VisComponent,
  components,
  mixins
};
<|endoftext|>