<commit_before>/*
 * Handles all the client-side logic for the upload page.
 */

"use strict";  // Makes bad syntax into actual errors

// Ensure the DOM tree is loaded before we start executing
// if we want to wait for all images to load as well, use below line instead of $(document).ready
// window.onload = function () {
$(document).ready(function() {

	// Extract pic id.
	var id;
	var query = window.location.search;
	var idToEnd = query.substring(query.indexOf('id=')+3);
	var nextAnd = idToEnd.indexOf('&');
	if (nextAnd >= 0) {
		id = idToEnd.substring(0, nextAnd);
	} else {
		id = idToEnd;
	}

	// Find out privledge level
	$.ajax({
	    url: "/CMPUT391F/RestService",
	    data: 'function=singleImage&id=' + id,
	    type: 'GET',
	    success: function(response){
	    	var result = JSON.parse(response);
	        if (result.result == "success") {
				setupEdit(result.pic[0]);
			} else {
				setupDenied(result);
			}
	    },
	    //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
	});
});

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

function collapse($collapsible) {
	$collapsible.find('> *').hide();
	$collapsible.height('0px');
}

function expand($collapsible) {
	var totalHeight = 0;
    $collapsible.find('> *').each(function(){
        totalHeight += $(this).height();
    });

	$collapsible.height(totalHeight);
	setTimeout(function() {
		$collapsible.find('> *').show();
	}, 200);
}

function setupEdit(data) {
	// Sets date picker on all browsers
	$('#date-taken').datepicker();

	// Populates the group dropdown
	populateGroups(function() {
		// Populates the form data
		populateForm(data);

		// Handles submit for upload form
		$("#edit-form").on("submit", function(event) {
			handleSubmit(data.photo_id[0]);
		    return false;
		});
	});
}

function setupDenied(data) {
	$('.section').empty();
	$('.section').append('

' + data.reason[0] + '
');
}

// Populates the group dropdown
function populateGroups(callback) {
	$.ajax({
	    url: "/CMPUT391F/RestService",
	    data: 'function=groupOptions',
	    type: 'GET',

	    success: function(response){
	        if (response == "") {
	        	// No groups returned
	        	$('.permission-validation').append('* No groups found');
	        } else {
	        	$('select[name="group-id"]').empty();
	        	$('select[name="group-id"]').append(response);
	        	var $radGroup = $('input[type="radio"][value="group"]');
	        	$radGroup[0].disabled = false;

	        	// Hides and shows the group selector
				$('input[name="permitted"]').change(function(e) {
					$('input[name="permitted"]').each(function(index, value) {
						if ($(this).is(':checked')) {
							if (this.value == "group") {
								// Expand the group selector
								expand($('tr.collapsible.group-selector'));
							} else {
								// Hide the group selector
								collapse($('tr.collapsible.group-selector'));
							}
						}
					});
				});

				if (callback) {
					callback();
				}
	        }
	    },
	    //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
	});
}

function populateForm(pic) {
	// Show picture
	$('#picToDisplay')[0].src="GetOnePic?big"+pic.photo_id[0];

	// Permission
	var perm = pic.permitted[0];
	if (perm == 1) {
		$('input[type="radio"][name="permitted"][value="1"]').click();
	} else if (perm == 2) {
		$('input[type="radio"][name="permitted"][value="2"]').click();
	} else {
		$('input[type="radio"][name="permitted"][value="group"]').click();
		$('select option[value="' + perm + '"]').prop({selected: true});

	}

	// Subject
	$('input[name="subject"]').val(pic.subject[0]);

	// Date Taken
	if (pic.timing[0] != null) {
		$('#date-taken').datepicker("setDate", new Date(pic.timing[0]));
	}

	// Location
	$('input[name="location"]').val(pic.place[0]);

	// Description
	$('textarea[name="description"]').val(pic.description[0]);
}

function handleSubmit(picId) {

	// Validate!
	var passed = true;
	$('.validation').empty();

	// Check for valid permission
	var permission_id = 0;
	$('input[name="permitted"]').each(function(index, entry) {
		if ($(entry).is(':checked')) {
			permission_id = entry.value;
		}
	});
	if (permission_id == 'group') {
		permission_id = $('select[name="group-id"]').val();
	} else if (permission_id == 0) {
		$('.permission.validation').append('* Please select a permission level.');
		passed = false;
	}

	// Get all our data in a FormData object
	var data = new FormData();
	$('input').each(function(index, element) {
		var type = this.type;
		if (type == "group" || type == "radio") {
			// Don't add anything, just continue
		} else if (type == "file") {
			data.append(this.name, this.files[0]);
		} else if (this.name == "date") {
			if (this.value == "") {
				// Empty / null date
				data.append(this.name, this.value);
			} else {
				// There is input on date, check for validity
				var d = new Date(this.value);
				if (d == "Invalid Date") {
					$('.date.validation').append('* Invalid date.');
					passed = false;
				} else {
					// Transform date to correct format
					var month = (d.getMonth()+1);
					if ((month+"").length < 2) {
						month = "0" + month;
					}
					var date = d.getDate();
					if ((date+"").length < 2) {
						date = "0" + date;
					}
					var val = d.getFullYear() + "-" + month + "-" + date;
					data.append(this.name, val);
				}
			}
		} else {
			data.append(this.name, this.value);
		}
	});

	// Did we pass validation?
	if (!passed) {
		return false;
	}

	// Add the group id and description
	data.append("photo-id", picId);
	data.append("group-id", permission_id);
	data.append('description', $('textarea').val());
	// Add function so the RESTController knows what to do with the data
	data.append("function", "editPic");

	// Start upload
	$("#edit-results").empty().append('Saving...
');

    $.ajax({
	    url: "/CMPUT391F/RestService",
	    data: data,
	    type: 'POST',
	    success: function(response){
	        $("#edit-results").append(response);
	    },
	    //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
	});
}<commit_msg>fix edit bug<commit_after>/*
 * Handles all the client-side logic for the upload page.
 */

"use strict";  // Makes bad syntax into actual errors

// Ensure the DOM tree is loaded before we start executing
// if we want to wait for all images to load as well, use below line instead of $(document).ready
// window.onload = function () {
$(document).ready(function() {

	// Extract pic id.
	var id;
	var query = window.location.search;
	var idToEnd = query.substring(query.indexOf('id=')+3);
	var nextAnd = idToEnd.indexOf('&');
	if (nextAnd >= 0) {
		id = idToEnd.substring(0, nextAnd);
	} else {
		id = idToEnd;
	}

	// Find out privledge level
	$.ajax({
	    url: "/CMPUT391F/RestService",
	    data: 'function=singleImage&id=' + id,
	    type: 'GET',
	    success: function(response){
	    	var result = JSON.parse(response);
	        if (result.result == "success") {
				setupEdit(result.pic[0]);
			} else {
				setupDenied(result);
			}
	    },
	    //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
	});
});

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

function collapse($collapsible) {
	$collapsible.find('> *').hide();
	$collapsible.height('0px');
}

function expand($collapsible) {
	var totalHeight = 0;
    $collapsible.find('> *').each(function(){
        totalHeight += $(this).height();
    });

	$collapsible.height(totalHeight);
	setTimeout(function() {
		$collapsible.find('> *').show();
	}, 200);
}

function setupEdit(data) {
	// Sets date picker on all browsers
	$('#date-taken').datepicker();

	// Populates the group dropdown
	populateGroups(function() {
		// Populates the form data
		populateForm(data);

		// Handles submit for upload form
		$("#edit-form").on("submit", function(event) {
			handleSubmit(data.photo_id[0]);
		    return false;
		});
	});
}

function setupDenied(data) {
	$('.section').empty();
	$('.section').append('

' + data.reason[0] + '
');
}

// Populates the group dropdown
function populateGroups(callback) {
	$.ajax({
	    url: "/CMPUT391F/RestService",
	    data: 'function=groupOptions',
	    type: 'GET',

	    success: function(response){
	        if (response == "") {
	        	// No groups returned
	        	$('.permission-validation').append('* No groups found');
	        } else {
	        	$('select[name="group-id"]').empty();
	        	$('select[name="group-id"]').append(response);
	        	var $radGroup = $('input[type="radio"][value="group"]');
	        	$radGroup[0].disabled = false;

	        	// Hides and shows the group selector
				$('input[name="permitted"]').change(function(e) {
					$('input[name="permitted"]').each(function(index, value) {
						if ($(this).is(':checked')) {
							if (this.value == "group") {
								// Expand the group selector
								expand($('tr.collapsible.group-selector'));
							} else {
								// Hide the group selector
								collapse($('tr.collapsible.group-selector'));
							}
						}
					});
				});
	        }
	        if (callback) {
				callback();
			}
	    },
	    //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
	});
}

function populateForm(pic) {
	// Show picture
	$('#picToDisplay')[0].src="GetOnePic?big"+pic.photo_id[0];

	// Permission
	var perm = pic.permitted[0];
	if (perm == 1) {
		$('input[type="radio"][name="permitted"][value="1"]').click();
	} else if (perm == 2) {
		$('input[type="radio"][name="permitted"][value="2"]').click();
	} else {
		$('input[type="radio"][name="permitted"][value="group"]').click();
		$('select option[value="' + perm + '"]').prop({selected: true});

	}

	// Subject
	$('input[name="subject"]').val(pic.subject[0]);

	// Date Taken
	if (pic.timing[0] != null) {
		$('#date-taken').datepicker("setDate", new Date(pic.timing[0]));
	}

	// Location
	$('input[name="location"]').val(pic.place[0]);

	// Description
	$('textarea[name="description"]').val(pic.description[0]);
}

function handleSubmit(picId) {

	// Validate!
	var passed = true;
	$('.validation').empty();

	// Check for valid permission
	var permission_id = 0;
	$('input[name="permitted"]').each(function(index, entry) {
		if ($(entry).is(':checked')) {
			permission_id = entry.value;
		}
	});
	if (permission_id == 'group') {
		permission_id = $('select[name="group-id"]').val();
	} else if (permission_id == 0) {
		$('.permission.validation').append('* Please select a permission level.');
		passed = false;
	}

	// Get all our data in a FormData object
	var data = new FormData();
	$('input').each(function(index, element) {
		var type = this.type;
		if (type == "group" || type == "radio") {
			// Don't add anything, just continue
		} else if (type == "file") {
			data.append(this.name, this.files[0]);
		} else if (this.name == "date") {
			if (this.value == "") {
				// Empty / null date
				data.append(this.name, this.value);
			} else {
				// There is input on date, check for validity
				var d = new Date(this.value);
				if (d == "Invalid Date") {
					$('.date.validation').append('* Invalid date.');
					passed = false;
				} else {
					// Transform date to correct format
					var month = (d.getMonth()+1);
					if ((month+"").length < 2) {
						month = "0" + month;
					}
					var date = d.getDate();
					if ((date+"").length < 2) {
						date = "0" + date;
					}
					var val = d.getFullYear() + "-" + month + "-" + date;
					data.append(this.name, val);
				}
			}
		} else {
			data.append(this.name, this.value);
		}
	});

	// Did we pass validation?
	if (!passed) {
		return false;
	}

	// Add the group id and description
	data.append("photo-id", picId);
	data.append("group-id", permission_id);
	data.append('description', $('textarea').val());
	// Add function so the RESTController knows what to do with the data
	data.append("function", "editPic");

	// Start upload
	$("#edit-results").empty().append('Saving...
');

    $.ajax({
	    url: "/CMPUT391F/RestService",
	    data: data,
	    type: 'POST',
	    success: function(response){
	        $("#edit-results").append(response);
	    },
	    //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
	});
}<|endoftext|>


<commit_before>'use strict';

describe('uiLayout', function () {

  // declare these up here to be global to all tests
  var scope, $compile, element;

  /**
   * UTILS
   */

  function appendTemplate(tpl) {
    element = angular.element(tpl);
    angular.element(document.body).append(element);
    $compile(element)(scope);
    scope.$digest();
  }

  /**
   * TESTS
   */

  beforeEach(module('ui.layout'));

  // inject in angular constructs. Injector knows about leading/trailing underscores and does the right thing
  // otherwise, you would need to inject these into each test
  beforeEach(inject(function (_$rootScope_, _$compile_) {
    scope = _$rootScope_.$new();
    $compile = _$compile_;
  }));

  // jasmine matcher for expecting an element to have a css class
  // https://github.com/angular/angular.js/blob/master/test/matchers.js
  beforeEach(function () {
    this.addMatchers({
      toHaveClass: function (cls) {
        this.message = function () {
          return 'Expected "' + angular.mock.dump(this.actual) + '" to have class "' + cls + '".';
        };

        return this.actual.hasClass(cls);
      }
    });
  });

  describe('require', function () {
    it('requestAnimationFrame', function () {
      expect(window.requestAnimationFrame).toBeDefined();
    });
    it('cancelAnimationFrame', function () {
      expect(window.cancelAnimationFrame).toBeDefined();
    });
  });

  afterEach(function () {
    if (element) element.remove();
  });

  describe('directive', function () {

    it('should have a "stretch" class', function () {
      appendTemplate('

');
      expect(element).toHaveClass('stretch');
    });

    it('should work as an element', function () {
      appendTemplate('<ui-layout></ui-layout>');
      expect(element).toHaveClass('stretch');
    });

    it('should work as an attribute', function () {
      appendTemplate('

');
      expect(element).toHaveClass('stretch');
    });

    it('should have a "ui-layout-row" class by default', function () {
      appendTemplate('

');
      expect(element).toHaveClass('ui-layout-row');
    });

    it('should not add split bar when empty', function () {
      appendTemplate('

');
      expect(element.children().length).toEqual(0);
    });

    it('should not add split bar when only one area', function () {
      appendTemplate('

');
      expect(element.children().length).toEqual(1);
    });

    it('should add n-1 split bar pour n area', function () {
      var children, splitBarElm;

      // Try with 2 elements
      appendTemplate('

');
      children = element.children();
      expect(children.length).toEqual(2 + 1); // add one slide
      expect(children[0].tagName).toEqual('ARTICLE');

      splitBarElm = children.eq(1);
      expect(splitBarElm[0].tagName).toEqual('DIV');
      expect(splitBarElm).toHaveClass('ui-splitbar');

      expect(children[2].tagName).toEqual('SECTION');

      // Try with 4 elements
      element.remove();
      appendTemplate('

');
      children = element.children();
      expect(children.length).toEqual(4 + 3); // add three slide

      // Raw pluck
      function _pluck(col, prop) {
        var _r = [];
        for (var i = 0; i < col.length; i++) {
          _r[i] = col[i][prop];
        }
        return _r;
      }

      expect(_pluck(children, 'tagName')).toEqual(['HEADER', 'DIV', 'ARTICLE', 'DIV', 'SECTION', 'DIV', 'FOOTER']);

    });

    describe('in column flow', function () {

      beforeEach(function () {
        appendTemplate('

');
      });

      it('should have a "ui-layout-column" class by default', function () {
        expect(element).toHaveClass('ui-layout-column');
      });

      it('should initialise with equal width', function () {
        var firstElemWidth = element.children()[0].getBoundingClientRect().width;
        for (var i = 0; i < element.children().length; i++) {
          expect(element.children()[i].getBoundingClientRect().width, 'tagName').toEqual(firstElemWidth);
        }
      });

      it('should have a split bar at the middle', function () {
        expect(element.children().eq(1).css('left')).toEqual('50%');
      });
    });

    describe('in row flow', function () {

      beforeEach(function () {
        appendTemplate('

');
      });

      it('should have a "ui-layout-row" class by default', function () {
        expect(element).toHaveClass('ui-layout-row');
      });

      it('should initialise with equal height', function () {
        var firstElemHeight = element.children()[0].getBoundingClientRect().height;
        for (var i = 0; i < element.children().length; i++) {
          expect(element.children()[i].getBoundingClientRect().height, 'tagName').toEqual(firstElemHeight);
        }
      });

      it('should have a split bar at the middle', function () {
        expect(element.children().eq(1).css('top')).toEqual('50%');
      });
    });

  });

  describe('controller', function () {
    var ctrl;

    beforeEach(inject(function (_$controller_) {
      appendTemplate('

');
      ctrl = _$controller_('uiLayoutCtrl', { $scope: scope, $element: element, $attrs: element[0].attributes });
    }));

    it('should expose the options and the element', function () {
      expect(ctrl).toEqual({ opts: jasmine.any(Object), element: element });
    });
  });

});
<commit_msg>fix(test): mesure odd elements only<commit_after>'use strict';

describe('uiLayout', function () {

  // declare these up here to be global to all tests
  var scope, $compile, element;

  /**
   * UTILS
   */

  function appendTemplate(tpl) {
    element = angular.element(tpl);
    angular.element(document.body).append(element);
    $compile(element)(scope);
    scope.$digest();
  }

  /**
   * TESTS
   */

  beforeEach(module('ui.layout'));

  // inject in angular constructs. Injector knows about leading/trailing underscores and does the right thing
  // otherwise, you would need to inject these into each test
  beforeEach(inject(function (_$rootScope_, _$compile_) {
    scope = _$rootScope_.$new();
    $compile = _$compile_;
  }));

  // jasmine matcher for expecting an element to have a css class
  // https://github.com/angular/angular.js/blob/master/test/matchers.js
  beforeEach(function () {
    this.addMatchers({
      toHaveClass: function (cls) {
        this.message = function () {
          return 'Expected "' + angular.mock.dump(this.actual) + '" to have class "' + cls + '".';
        };

        return this.actual.hasClass(cls);
      }
    });
  });

  describe('require', function () {
    it('requestAnimationFrame', function () {
      expect(window.requestAnimationFrame).toBeDefined();
    });
    it('cancelAnimationFrame', function () {
      expect(window.cancelAnimationFrame).toBeDefined();
    });
  });

  afterEach(function () {
    if (element) element.remove();
  });

  describe('directive', function () {

    it('should have a "stretch" class', function () {
      appendTemplate('

');
      expect(element).toHaveClass('stretch');
    });

    it('should work as an element', function () {
      appendTemplate('<ui-layout></ui-layout>');
      expect(element).toHaveClass('stretch');
    });

    it('should work as an attribute', function () {
      appendTemplate('

');
      expect(element).toHaveClass('stretch');
    });

    it('should have a "ui-layout-row" class by default', function () {
      appendTemplate('

');
      expect(element).toHaveClass('ui-layout-row');
    });

    it('should not add split bar when empty', function () {
      appendTemplate('

');
      expect(element.children().length).toEqual(0);
    });

    it('should not add split bar when only one area', function () {
      appendTemplate('

');
      expect(element.children().length).toEqual(1);
    });

    it('should add n-1 split bar pour n area', function () {
      var children, splitBarElm;

      // Try with 2 elements
      appendTemplate('

');
      children = element.children();
      expect(children.length).toEqual(2 + 1); // add one slide
      expect(children[0].tagName).toEqual('ARTICLE');

      splitBarElm = children.eq(1);
      expect(splitBarElm[0].tagName).toEqual('DIV');
      expect(splitBarElm).toHaveClass('ui-splitbar');

      expect(children[2].tagName).toEqual('SECTION');

      // Try with 4 elements
      element.remove();
      appendTemplate('

');
      children = element.children();
      expect(children.length).toEqual(4 + 3); // add three slide

      // Raw pluck
      function _pluck(col, prop) {
        var _r = [];
        for (var i = 0; i < col.length; i++) {
          _r[i] = col[i][prop];
        }
        return _r;
      }

      expect(_pluck(children, 'tagName')).toEqual(['HEADER', 'DIV', 'ARTICLE', 'DIV', 'SECTION', 'DIV', 'FOOTER']);

    });

    describe('in column flow', function () {

      beforeEach(function () {
        appendTemplate('

');
      });

      it('should have a "ui-layout-column" class by default', function () {
        expect(element).toHaveClass('ui-layout-column');
      });

      it('should initialise with equal width', function () {
        var firstElemWidth = element.children()[0].getBoundingClientRect().width;
        for (var i = 0; i < element.children().length; i+=2) {
          expect(element.children()[i].getBoundingClientRect().width, 'tagName').toEqual(firstElemWidth);
        }
      });

      it('should have a split bar at the middle', function () {
        expect(element.children().eq(1).css('left')).toEqual('50%');
      });
    });

    describe('in row flow', function () {

      beforeEach(function () {
        appendTemplate('

');
      });

      it('should have a "ui-layout-row" class by default', function () {
        expect(element).toHaveClass('ui-layout-row');
      });

      it('should initialise with equal height', function () {
        var firstElemHeight = element.children()[0].getBoundingClientRect().height;
        for (var i = 0; i < element.children().length; i+=2) {
          expect(element.children()[i].getBoundingClientRect().height, 'tagName').toEqual(firstElemHeight);
        }
      });

      it('should have a split bar at the middle', function () {
        expect(element.children().eq(1).css('top')).toEqual('50%');
      });
    });

  });

  describe('controller', function () {
    var ctrl;

    beforeEach(inject(function (_$controller_) {
      appendTemplate('

');
      ctrl = _$controller_('uiLayoutCtrl', { $scope: scope, $element: element, $attrs: element[0].attributes });
    }));

    it('should expose the options and the element', function () {
      expect(ctrl).toEqual({ opts: jasmine.any(Object), element: element });
    });
  });

});
<|endoftext|>


<commit_before>'use strict'
/* eslint-env mocha */

const expect = require('chai').expect
const libp2p = require('../src')
const PeerInfo = require('peer-info')
const multiaddr = require('multiaddr')
const parallel = require('async/parallel')
const map = require('async/map')
const spawn = require('child_process').spawn
const path = require('path')
const pull = require('pull-stream')

describe('libp2p-ipfs', () => {
  let nodeA // TCP
  let nodeB // TCP
  let nodeC // TCP
  let nodeD // TCP
  let nodeE // TCP + WebSockets
  let nodeF // WebSockets

  let nodeAMultiaddrTCP
  let nodeBMultiaddrTCP
  let nodeCMultiaddrTCP
  let nodeDMultiaddrTCP
  let nodeEMultiaddrTCP
  let nodeEMultiaddrWebSockets
  let nodeFMultiaddrWebSockets

  let spawnedNode

  it('create 6 nodes', (done) => {
    map([0, 1, 2, 3, 4, 5], (i, cb) => {
      PeerInfo.create(cb)
    }, (err, infos) => {
      if (err) {
        return done(err)
      }

      infos.forEach((info, i) => {
        if (i === 5) {
          return
        }
        info.multiaddr.add(multiaddr('/ip4/0.0.0.0/tcp/0'))
      })

      nodeA = new libp2p.Node(infos[0])
      nodeB = new libp2p.Node(infos[1])
      nodeC = new libp2p.Node(infos[2])
      nodeD = new libp2p.Node(infos[3])
      nodeE = new libp2p.Node(infos[4])
      const maddrWS1 = multiaddr('/ip4/127.0.0.1/tcp/25001/ws')
      nodeE.peerInfo.multiaddr.add(maddrWS1)

      nodeEMultiaddrWebSockets = multiaddr(
        nodeE.peerInfo.multiaddrs[1].toString() +
        '/ipfs/' + nodeE.peerInfo.id.toB58String()
      )

      const pInfo = infos[5]
      const maddrWS2 = multiaddr('/ip4/127.0.0.1/tcp/25002/ws')
      pInfo.multiaddr.add(maddrWS2)

      nodeF = new libp2p.Node(pInfo)

      nodeFMultiaddrWebSockets = multiaddr(
        nodeF.peerInfo.multiaddrs[0].toString() +
        '/ipfs/' + nodeF.peerInfo.id.toB58String()
      )

      done()
    })
  })

  it('start 6 nodes', (done) => {
    parallel([
      nodeA.start,
      nodeB.start,
      nodeC.start,
      nodeD.start,
      nodeE.start,
      nodeF.start
    ], (err) => {
      expect(err).to.not.exist
      expect(nodeA.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeB.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeC.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeD.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeE.peerInfo.multiaddrs.length > 2).to.equal(true)
      expect(nodeF.peerInfo.multiaddrs.length).to.equal(1)
      done()
    })
  })

  it('extract TCP multiaddr', () => {
    nodeAMultiaddrTCP = multiaddr((
      nodeA.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeA.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )
    nodeBMultiaddrTCP = multiaddr((
      nodeB.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeB.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')

    )
    nodeCMultiaddrTCP = multiaddr((
      nodeC.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeC.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')

    )
    nodeDMultiaddrTCP = multiaddr((
      nodeD.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeD.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )

    // Note: Here is the multiaddrs[1] again because
    // the .replace in swarm switches the order of
    // the TCP and WS addr
    nodeEMultiaddrTCP = multiaddr((
      nodeE.peerInfo.multiaddrs[1].toString() +
      '/ipfs/' + nodeE.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )

    // console.log(nodeAMultiaddrTCP.toString())
    // console.log(nodeBMultiaddrTCP.toString())
    // console.log(nodeCMultiaddrTCP.toString())
    // console.log(nodeDMultiaddrTCP.toString())
    // console.log(nodeEMultiaddrTCP.toString())
  })

  it('handle echo proto in 6 nodes', () => {
    function echo (protocol, conn) {
      pull(conn, conn)
    }

    nodeA.handle('/echo/1.0.0', echo)
    nodeB.handle('/echo/1.0.0', echo)
    nodeC.handle('/echo/1.0.0', echo)
    nodeD.handle('/echo/1.0.0', echo)
    nodeE.handle('/echo/1.0.0', echo)
    nodeF.handle('/echo/1.0.0', echo)
  })

  // General connectivity tests

  it('libp2p.dialByMultiaddr nodeA to nodeB', (done) => {
    nodeA.dialByMultiaddr(nodeBMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      // Some time for Identify to finish
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          }
        ], done)
      }
      // TODO confirm that we got the pubkey through identify
    })
  })

  it('libp2p.dialByMultiaddr on Protocol nodeA to nodeB', (done) => {
    nodeA.dialByMultiaddr(nodeBMultiaddrTCP, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      parallel([
        (cb) => {
          const peers = nodeA.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        },
        (cb) => {
          const peers = nodeB.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        }
      ], () => {
        pull(
          pull.values([Buffer('hey')]),
          conn,
          pull.collect((err, data) => {
            expect(err).to.not.exist
            expect(data).to.be.eql([Buffer('hey')])
            done()
          })
        )
      })
    })
  })

  it('libp2p.hangupByMultiaddr nodeA to nodeB', (done) => {
    nodeA.hangUpByMultiaddr(nodeBMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeA.swarm.muxedConns)).to.have.length(0)

            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeB.swarm.muxedConns)).to.have.length(0)
            cb()
          }
        ], done)
      }
    })
  })

  it('libp2p.dialByPeerInfo nodeA to nodeB', (done) => {
    nodeA.dialByPeerInfo(nodeB.peerInfo, (err) => {
      expect(err).to.not.exist
      // Some time for Identify to finish
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          }
        ], done)
      }
      // TODO confirm that we got the pubkey through identify
    })
  })

  it('libp2p.dialByPeerInfo on Protocol nodeA to nodeB', (done) => {
    nodeA.dialByPeerInfo(nodeB.peerInfo, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      parallel([
        (cb) => {
          const peers = nodeA.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        },
        (cb) => {
          const peers = nodeB.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        }
      ], () => {
        pull(
          pull.values([Buffer('hey')]),
          conn,
          pull.collect((err, data) => {
            expect(err).to.not.exist
            expect(data).to.be.eql([Buffer('hey')])
            done()
          })
        )
      })
    })
  })

  it('libp2p.hangupByPeerInfo nodeA to nodeB', (done) => {
    nodeA.hangUpByPeerInfo(nodeB.peerInfo, (err) => {
      expect(err).to.not.exist
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeA.swarm.muxedConns)).to.have.length(0)

            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeB.swarm.muxedConns)).to.have.length(0)
            cb()
          }
        ], done)
      }
    })
  })

  // NOTE, these dialById only works if a previous dial was made
  // until we have PeerRouting
  it.skip('libp2p.dialById nodeA to nodeB', (done) => {})
  it.skip('libp2p.dialById on Protocol nodeA to nodeB', (done) => {})
  it.skip('libp2p.hangupById nodeA to nodeB', (done) => {})

  it('nodeA dial to nodeC and nodeD', (done) => {
    let count = 0
    const next = () => ++count === 2 ? check() : null

    nodeA.dialByMultiaddr(nodeCMultiaddrTCP, next)
    nodeA.dialByMultiaddr(nodeDMultiaddrTCP, next)

    function check () {
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(2)
      done()
    }
  })

  // Multiple transport tests

  it('nodeA dial to nodeE', (done) => {
    nodeA.dialByMultiaddr(nodeEMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    })
  })

  it('nodeA fails to dial to nodeF', (done) => {
    nodeA.dialByMultiaddr(nodeFMultiaddrWebSockets, (err) => {
      expect(err).to.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    })
  })

  it('nodeF fails to dial to nodeA', (done) => {
    nodeF.dialByMultiaddr(nodeAMultiaddrTCP, (err) => {
      expect(err).to.exist
      done()
    })
  })

  it('nodeF dial to nodeE', (done) => {
    nodeF.dialByMultiaddr(nodeEMultiaddrWebSockets, (err) => {
      expect(err).to.not.exist
      done()
    })
  })

  // Turbolence tests

  it('spawn a node in a different process', (done) => {
    const filePath = path.join(__dirname, './spawn-libp2p-node.js')
    spawnedNode = spawn(filePath)

    let spawned = false
    spawnedNode.stdout.on('data', (data) => {
      if (!spawned) {
        spawned = true
        done()
      }
    })
  })

  it('connect nodeA to that node', (done) => {
    const spawnedId = require('./test-data/test-id.json')
    const maddr = multiaddr('/ip4/127.0.0.1/tcp/12345/ipfs/' + spawnedId.id)
    nodeA.dialByMultiaddr(maddr, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(4)

      pull(
        pull.values([Buffer('hey')]),
        conn,
        pull.collect((err, data) => {
          expect(err).to.not.exist
          expect(data).to.be.eql([Buffer('hey')])
          done()
        })
      )
    })
  })

  it('crash that node, make sure nodeA continues going steady', (done) => {
    spawnedNode.kill('SIGKILL')

    setTimeout(check, 5000)

    function check () {
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    }
  })

  it('stop', (done) => {
    parallel([
      nodeA.stop,
      nodeB.stop,
      nodeC.stop,
      nodeD.stop,
      nodeE.stop,
      nodeF.stop
    ], done)
  })
})
<commit_msg>fix: mad tests missing with the `this value`<commit_after>'use strict'
/* eslint-env mocha */

const expect = require('chai').expect
const libp2p = require('../src')
const PeerInfo = require('peer-info')
const multiaddr = require('multiaddr')
const parallel = require('async/parallel')
const map = require('async/map')
const spawn = require('child_process').spawn
const path = require('path')
const pull = require('pull-stream')

describe('libp2p-ipfs', () => {
  let nodeA // TCP
  let nodeB // TCP
  let nodeC // TCP
  let nodeD // TCP
  let nodeE // TCP + WebSockets
  let nodeF // WebSockets

  let nodeAMultiaddrTCP
  let nodeBMultiaddrTCP
  let nodeCMultiaddrTCP
  let nodeDMultiaddrTCP
  let nodeEMultiaddrTCP
  let nodeEMultiaddrWebSockets
  let nodeFMultiaddrWebSockets

  let spawnedNode

  it('create 6 nodes', (done) => {
    map([0, 1, 2, 3, 4, 5], (i, cb) => {
      PeerInfo.create(cb)
    }, (err, infos) => {
      if (err) {
        return done(err)
      }

      infos.forEach((info, i) => {
        if (i === 5) {
          return
        }
        info.multiaddr.add(multiaddr('/ip4/0.0.0.0/tcp/0'))
      })

      nodeA = new libp2p.Node(infos[0])
      nodeB = new libp2p.Node(infos[1])
      nodeC = new libp2p.Node(infos[2])
      nodeD = new libp2p.Node(infos[3])
      nodeE = new libp2p.Node(infos[4])
      const maddrWS1 = multiaddr('/ip4/127.0.0.1/tcp/25001/ws')
      nodeE.peerInfo.multiaddr.add(maddrWS1)

      nodeEMultiaddrWebSockets = multiaddr(
        nodeE.peerInfo.multiaddrs[1].toString() +
        '/ipfs/' + nodeE.peerInfo.id.toB58String()
      )

      const pInfo = infos[5]
      const maddrWS2 = multiaddr('/ip4/127.0.0.1/tcp/25002/ws')
      pInfo.multiaddr.add(maddrWS2)

      nodeF = new libp2p.Node(pInfo)

      nodeFMultiaddrWebSockets = multiaddr(
        nodeF.peerInfo.multiaddrs[0].toString() +
        '/ipfs/' + nodeF.peerInfo.id.toB58String()
      )

      done()
    })
  })

  it('start 6 nodes', (done) => {
    parallel([
      (cb) => nodeA.start(cb),
      (cb) => nodeB.start(cb),
      (cb) => nodeC.start(cb),
      (cb) => nodeD.start(cb),
      (cb) => nodeE.start(cb),
      (cb) => nodeF.start(cb)
    ], (err) => {
      expect(err).to.not.exist
      expect(nodeA.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeB.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeC.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeD.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeE.peerInfo.multiaddrs.length > 2).to.equal(true)
      expect(nodeF.peerInfo.multiaddrs.length).to.equal(1)
      done()
    })
  })

  it('extract TCP multiaddr', () => {
    nodeAMultiaddrTCP = multiaddr((
      nodeA.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeA.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )
    nodeBMultiaddrTCP = multiaddr((
      nodeB.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeB.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')

    )
    nodeCMultiaddrTCP = multiaddr((
      nodeC.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeC.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')

    )
    nodeDMultiaddrTCP = multiaddr((
      nodeD.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeD.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )

    // Note: Here is the multiaddrs[1] again because
    // the .replace in swarm switches the order of
    // the TCP and WS addr
    nodeEMultiaddrTCP = multiaddr((
      nodeE.peerInfo.multiaddrs[1].toString() +
      '/ipfs/' + nodeE.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )

    // console.log(nodeAMultiaddrTCP.toString())
    // console.log(nodeBMultiaddrTCP.toString())
    // console.log(nodeCMultiaddrTCP.toString())
    // console.log(nodeDMultiaddrTCP.toString())
    // console.log(nodeEMultiaddrTCP.toString())
  })

  it('handle echo proto in 6 nodes', () => {
    function echo (protocol, conn) {
      pull(conn, conn)
    }

    nodeA.handle('/echo/1.0.0', echo)
    nodeB.handle('/echo/1.0.0', echo)
    nodeC.handle('/echo/1.0.0', echo)
    nodeD.handle('/echo/1.0.0', echo)
    nodeE.handle('/echo/1.0.0', echo)
    nodeF.handle('/echo/1.0.0', echo)
  })

  // General connectivity tests

  it('libp2p.dialByMultiaddr nodeA to nodeB', (done) => {
    nodeA.dialByMultiaddr(nodeBMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      // Some time for Identify to finish
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          }
        ], done)
      }
      // TODO confirm that we got the pubkey through identify
    })
  })

  it('libp2p.dialByMultiaddr on Protocol nodeA to nodeB', (done) => {
    nodeA.dialByMultiaddr(nodeBMultiaddrTCP, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      parallel([
        (cb) => {
          const peers = nodeA.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        },
        (cb) => {
          const peers = nodeB.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        }
      ], () => {
        pull(
          pull.values([Buffer('hey')]),
          conn,
          pull.collect((err, data) => {
            expect(err).to.not.exist
            expect(data).to.be.eql([Buffer('hey')])
            done()
          })
        )
      })
    })
  })

  it('libp2p.hangupByMultiaddr nodeA to nodeB', (done) => {
    nodeA.hangUpByMultiaddr(nodeBMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeA.swarm.muxedConns)).to.have.length(0)

            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeB.swarm.muxedConns)).to.have.length(0)
            cb()
          }
        ], done)
      }
    })
  })

  it('libp2p.dialByPeerInfo nodeA to nodeB', (done) => {
    nodeA.dialByPeerInfo(nodeB.peerInfo, (err) => {
      expect(err).to.not.exist
      // Some time for Identify to finish
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          }
        ], done)
      }
      // TODO confirm that we got the pubkey through identify
    })
  })

  it('libp2p.dialByPeerInfo on Protocol nodeA to nodeB', (done) => {
    nodeA.dialByPeerInfo(nodeB.peerInfo, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      parallel([
        (cb) => {
          const peers = nodeA.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        },
        (cb) => {
          const peers = nodeB.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        }
      ], () => {
        pull(
          pull.values([Buffer('hey')]),
          conn,
          pull.collect((err, data) => {
            expect(err).to.not.exist
            expect(data).to.be.eql([Buffer('hey')])
            done()
          })
        )
      })
    })
  })

  it('libp2p.hangupByPeerInfo nodeA to nodeB', (done) => {
    nodeA.hangUpByPeerInfo(nodeB.peerInfo, (err) => {
      expect(err).to.not.exist
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeA.swarm.muxedConns)).to.have.length(0)

            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeB.swarm.muxedConns)).to.have.length(0)
            cb()
          }
        ], done)
      }
    })
  })

  // NOTE, these dialById only works if a previous dial was made
  // until we have PeerRouting
  it.skip('libp2p.dialById nodeA to nodeB', (done) => {})
  it.skip('libp2p.dialById on Protocol nodeA to nodeB', (done) => {})
  it.skip('libp2p.hangupById nodeA to nodeB', (done) => {})

  it('nodeA dial to nodeC and nodeD', (done) => {
    let count = 0
    const next = () => ++count === 2 ? check() : null

    nodeA.dialByMultiaddr(nodeCMultiaddrTCP, next)
    nodeA.dialByMultiaddr(nodeDMultiaddrTCP, next)

    function check () {
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(2)
      done()
    }
  })

  // Multiple transport tests

  it('nodeA dial to nodeE', (done) => {
    nodeA.dialByMultiaddr(nodeEMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    })
  })

  it('nodeA fails to dial to nodeF', (done) => {
    nodeA.dialByMultiaddr(nodeFMultiaddrWebSockets, (err) => {
      expect(err).to.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    })
  })

  it('nodeF fails to dial to nodeA', (done) => {
    nodeF.dialByMultiaddr(nodeAMultiaddrTCP, (err) => {
      expect(err).to.exist
      done()
    })
  })

  it('nodeF dial to nodeE', (done) => {
    nodeF.dialByMultiaddr(nodeEMultiaddrWebSockets, (err) => {
      expect(err).to.not.exist
      done()
    })
  })

  // Turbolence tests

  it('spawn a node in a different process', (done) => {
    const filePath = path.join(__dirname, './spawn-libp2p-node.js')
    spawnedNode = spawn(filePath)

    let spawned = false
    spawnedNode.stdout.on('data', (data) => {
      if (!spawned) {
        spawned = true
        done()
      }
    })
  })

  it('connect nodeA to that node', (done) => {
    const spawnedId = require('./test-data/test-id.json')
    const maddr = multiaddr('/ip4/127.0.0.1/tcp/12345/ipfs/' + spawnedId.id)
    nodeA.dialByMultiaddr(maddr, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(4)

      pull(
        pull.values([Buffer('hey')]),
        conn,
        pull.collect((err, data) => {
          expect(err).to.not.exist
          expect(data).to.be.eql([Buffer('hey')])
          done()
        })
      )
    })
  })

  it('crash that node, make sure nodeA continues going steady', (done) => {
    spawnedNode.kill('SIGKILL')

    setTimeout(check, 5000)

    function check () {
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    }
  })

  it('stop', (done) => {
    parallel([
      (cb) => nodeA.stop(cb),
      (cb) => nodeB.stop(cb),
      (cb) => nodeC.stop(cb),
      (cb) => nodeD.stop(cb),
      (cb) => nodeE.stop(cb),
      (cb) => nodeF.stop(cb)
    ], done)
  })
})
<|endoftext|>


<commit_before>'use strict'

const test = require('tap').test
const Fastify = require('..')

test('listen accepts a port and a callback', t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.listen(0, (err) => {
    fastify.server.unref()
    t.error(err)
    t.pass()
    fastify.close()
  })
})

test('listen accepts a port, address, and callback', t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.listen(0, '127.0.0.1', (err) => {
    fastify.server.unref()
    t.error(err)
    t.pass()
    fastify.close()
  })
})

test('listen after Promise.resolve()', t => {
  t.plan(2)
  const f = Fastify()
  Promise.resolve()
    .then(() => {
      f.listen(0, (err) => {
        f.server.unref()
        t.error(err)
        t.pass()
        f.close()
      })
    })
})

test('register after listen using Promise.resolve()', t => {
  t.plan(2)
  const f = Fastify()

  const handler = (req, res) => res.send({})
  Promise.resolve()
    .then(() => {
      f.get('/', handler)
      f.register((f2, options, done) => {
        f2.get('/plugin', handler)
        done()
      })
    })
    .then(() => {
      f.listen(0, '127.0.0.1', (err) => {
        t.error(err)
        t.pass()
        f.close()
      })
    })
})

test('double listen errors', t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.listen(0, (err) => {
    t.error(err)
    fastify.listen(fastify.server.address().port, (err) => {
      t.ok(err)
      fastify.close()
    })
  })
})

test('listen twice on the same port', t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.listen(0, (err) => {
    t.error(err)
    const s2 = Fastify()
    s2.listen(fastify.server.address().port, (err) => {
      fastify.close()
      t.ok(err)
    })
  })
})
<commit_msg>Add test for sock support<commit_after>'use strict'

const os = require('os')
const path = require('path')
const fs = require('fs')
const test = require('tap').test
const Fastify = require('..')

test('listen accepts a port and a callback', t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.listen(0, (err) => {
    fastify.server.unref()
    t.error(err)
    t.pass()
    fastify.close()
  })
})

test('listen accepts a port, address, and callback', t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.listen(0, '127.0.0.1', (err) => {
    fastify.server.unref()
    t.error(err)
    t.pass()
    fastify.close()
  })
})

test('listen after Promise.resolve()', t => {
  t.plan(2)
  const f = Fastify()
  Promise.resolve()
    .then(() => {
      f.listen(0, (err) => {
        f.server.unref()
        t.error(err)
        t.pass()
        f.close()
      })
    })
})

test('register after listen using Promise.resolve()', t => {
  t.plan(2)
  const f = Fastify()

  const handler = (req, res) => res.send({})
  Promise.resolve()
    .then(() => {
      f.get('/', handler)
      f.register((f2, options, done) => {
        f2.get('/plugin', handler)
        done()
      })
    })
    .then(() => {
      f.listen(0, '127.0.0.1', (err) => {
        t.error(err)
        t.pass()
        f.close()
      })
    })
})

test('double listen errors', t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.listen(0, (err) => {
    t.error(err)
    fastify.listen(fastify.server.address().port, (err) => {
      t.ok(err)
      fastify.close()
    })
  })
})

test('listen twice on the same port', t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.listen(0, (err) => {
    t.error(err)
    const s2 = Fastify()
    s2.listen(fastify.server.address().port, (err) => {
      fastify.close()
      t.ok(err)
    })
  })
})

test('listen on socket', t => {
  t.plan(2)
  const fastify = Fastify()
  const sockFile = path.join(os.tmpdir(), 'server.sock')
  try {
    fs.unlinkSync(sockFile)
  } catch (e) { }
  fastify.listen(sockFile, (err) => {
    t.error(err)
    t.equal(sockFile, fastify.server.address())
    fastify.close()
  })
})
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var assign = require('object-assign');
var expect = require('expect.js');
var webpack = require('webpack');

var ASYNC_TEST_TIMEOUT = 10000;

describe('svg-url-loader', function() {
    'use strict';

    var outputDir = path.resolve(__dirname, './output'),
        bundleFileName = 'bundle.js',
        getBundleFile = function() {
            return path.join(outputDir, bundleFileName);
        };
    var svgUrlLoader = path.resolve(__dirname, '../');
    var globalConfig = {
        context: path.resolve(__dirname, '../'),
        output: {
            path: outputDir,
            filename: bundleFileName
        },
        module: {
            rules: [
                {
                    test: /\.svg/,
                    exclude: /node_modules/,
                    use: [
                        {
							loader: svgUrlLoader,
							options: {}
                        }
                    ]
                }
            ]
        }
    };

    // Clean generated cache files before each test so that we can call each test with an empty state.
    afterEach(function(done) {
        fs.unlink(getBundleFile(), done);
        globalConfig.module.rules[0].use[0].options = {};
    });

    describe('"noquotes" option', function () {
        it('should convert SVG file to utf-8 encoded data-uri string, enclosed in quotes', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/icon.js'
            });
            config.module.rules[0].use[0].options.noquotes = false;

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString());
                    expect(encoded.indexOf('"')).to.be(0);
                    expect(encoded.lastIndexOf('"')).to.be(encoded.length - 1);
                    expect(encoded.indexOf('data:image/svg+xml;charset=utf8,%3Csvg')).to.be(1);
                    return done();
                });
            });
        }, ASYNC_TEST_TIMEOUT);

        it('should not enclose output in quotes if \'noquotes\' option is specified', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/icon.js'
            });
            config.module.rules[0].use[0].options.noquotes = true;

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString());
                    expect(encoded.indexOf('data:image/svg+xml;charset=utf8,%3Csvg')).to.be(0);
                    expect(encoded.lastIndexOf('svg%3E')).to.be(encoded.length - 'svg%3E'.length);
                    return done();
                });
            });
        }, ASYNC_TEST_TIMEOUT);
    });

    describe('"limit" option and "url.dataUrlLimit" configuration', function () {
        it('should fall back to file-loader if the content of SVG file is longer than "limit" query parameter', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/icon.js'
            });
            config.module.rules[0].use[0].options.limit = 10;
            config.module.rules[0].use[0].options.name = 'foo.svg';

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString());
                    expect(encoded).to.be('foo.svg');
                    return done();
                });
            });
        }, ASYNC_TEST_TIMEOUT);
    });

    describe('combining with other loaders', function () {
        it('should convert SVG file to utf-8 encoded data-uri string, when embedded in LESS file', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/less.js'
            });
            config.module.rules[0].use[0].options.noquotes = false;
            config.module.rules.push({
                test: /\.less$/,
                use: [
                    'css-loader',
                    'less-loader'
	             ]
            });

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString()),
                        found = false;
                    for(var i=0; i<encoded[0].length; ++i) {
                        var v = encoded[0][i];
                        if (typeof v === 'string' && v.indexOf('background-image: url("data:image/svg+xml;charset=utf8,%3Csvg') !== -1) {
                            found = true;
                        }
                    }
                    expect(found).to.be(true);
                    return done();
                });
            });
        }, ASYNC_TEST_TIMEOUT);

        it('should convert SVG file to utf-8 encoded data-uri string, when embedded in SCSS file', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/scss.js'
            });
            config.module.rules[0].use[0].options.noquotes = false;
            config.module.rules.push({
                test: /\.scss$/,
                use: [
                    'css-loader',
                    'sass-loader'
                ]
            });

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString()),
                        found = false;
                    for(var i=0; i<encoded[0].length; ++i) {
                        var v = encoded[0][i];
                        if (typeof v === 'string' && v.indexOf('background-image: url("data:image/svg+xml;charset=utf8,%3Csvg') !== -1) {
                            found = true;
                        }
                    }
                    expect(found).to.be(true);
                    return done();
                });
            });
        }, ASYNC_TEST_TIMEOUT);

        it('should convert SVG file to utf-8 encoded data-uri string, when embedded in CSS file', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/css.js'
            });
            config.module.rules[0].use[0].options.noquotes = false;
            config.module.rules.push({
                test: /\.css$/,
                use: [
                    'css-loader'
                ]
            });

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString()),
                        found = false;
                    for(var i=0; i<encoded[0].length; ++i) {
                        var v = encoded[0][i];
                        if (typeof v === 'string' && v.indexOf('background-image: url("data:image/svg+xml;charset=utf8,%3Csvg') !== -1) {
                            found = true;
                        }
                    }
                    expect(found).to.be(true);
                    return done();
                });
            });
        }, ASYNC_TEST_TIMEOUT);
    });
});
<commit_msg>chore: fixed timeout for async tests<commit_after>var fs = require('fs');
var path = require('path');
var assign = require('object-assign');
var expect = require('expect.js');
var webpack = require('webpack');

describe('svg-url-loader', function() {
    'use strict';

    this.timeout(10000);

    var outputDir = path.resolve(__dirname, './output'),
        bundleFileName = 'bundle.js',
        getBundleFile = function() {
            return path.join(outputDir, bundleFileName);
        };
    var svgUrlLoader = path.resolve(__dirname, '../');
    var globalConfig = {
        context: path.resolve(__dirname, '../'),
        output: {
            path: outputDir,
            filename: bundleFileName
        },
        module: {
            rules: [
                {
                    test: /\.svg/,
                    exclude: /node_modules/,
                    use: [
                        {
							loader: svgUrlLoader,
							options: {}
                        }
                    ]
                }
            ]
        }
    };

    // Clean generated cache files before each test so that we can call each test with an empty state.
    afterEach(function(done) {
        fs.unlink(getBundleFile(), done);
        globalConfig.module.rules[0].use[0].options = {};
    });

    describe('"noquotes" option', function () {
        it('should convert SVG file to utf-8 encoded data-uri string, enclosed in quotes', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/icon.js'
            });
            config.module.rules[0].use[0].options.noquotes = false;

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString());
                    expect(encoded.indexOf('"')).to.be(0);
                    expect(encoded.lastIndexOf('"')).to.be(encoded.length - 1);
                    expect(encoded.indexOf('data:image/svg+xml;charset=utf8,%3Csvg')).to.be(1);
                    return done();
                });
            });
        });

        it('should not enclose output in quotes if \'noquotes\' option is specified', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/icon.js'
            });
            config.module.rules[0].use[0].options.noquotes = true;

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString());
                    expect(encoded.indexOf('data:image/svg+xml;charset=utf8,%3Csvg')).to.be(0);
                    expect(encoded.lastIndexOf('svg%3E')).to.be(encoded.length - 'svg%3E'.length);
                    return done();
                });
            });
        });
    });

    describe('"limit" option and "url.dataUrlLimit" configuration', function () {
        it('should fall back to file-loader if the content of SVG file is longer than "limit" query parameter', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/icon.js'
            });
            config.module.rules[0].use[0].options.limit = 10;
            config.module.rules[0].use[0].options.name = 'foo.svg';

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString());
                    expect(encoded).to.be('foo.svg');
                    return done();
                });
            });
        });
    });

    describe('combining with other loaders', function () {
        it('should convert SVG file to utf-8 encoded data-uri string, when embedded in LESS file', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/less.js'
            });
            config.module.rules[0].use[0].options.noquotes = false;
            config.module.rules.push({
                test: /\.less$/,
                use: [
                    'css-loader',
                    'less-loader'
	             ]
            });

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString()),
                        found = false;
                    for(var i=0; i<encoded[0].length; ++i) {
                        var v = encoded[0][i];
                        if (typeof v === 'string' && v.indexOf('background-image: url("data:image/svg+xml;charset=utf8,%3Csvg') !== -1) {
                            found = true;
                        }
                    }
                    expect(found).to.be(true);
                    return done();
                });
            });
        });

        it('should convert SVG file to utf-8 encoded data-uri string, when embedded in SCSS file', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/scss.js'
            });
            config.module.rules[0].use[0].options.noquotes = false;
            config.module.rules.push({
                test: /\.scss$/,
                use: [
                    'css-loader',
                    'sass-loader'
                ]
            });

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString()),
                        found = false;
                    for(var i=0; i<encoded[0].length; ++i) {
                        var v = encoded[0][i];
                        if (typeof v === 'string' && v.indexOf('background-image: url("data:image/svg+xml;charset=utf8,%3Csvg') !== -1) {
                            found = true;
                        }
                    }
                    expect(found).to.be(true);
                    return done();
                });
            });
        });

        it('should convert SVG file to utf-8 encoded data-uri string, when embedded in CSS file', function(done) {
            var config = assign({}, globalConfig, {
                entry: './test/input/css.js'
            });
            config.module.rules[0].use[0].options.noquotes = false;
            config.module.rules.push({
                test: /\.css$/,
                use: [
                    'css-loader'
                ]
            });

            webpack(config, function(err) {
                expect(err).to.be(null);
                fs.readFile(getBundleFile(), function(err, data) {
                    expect(err).to.be(null);
                    var encoded = (0,eval)(data.toString()),
                        found = false;
                    for(var i=0; i<encoded[0].length; ++i) {
                        var v = encoded[0][i];
                        if (typeof v === 'string' && v.indexOf('background-image: url("data:image/svg+xml;charset=utf8,%3Csvg') !== -1) {
                            found = true;
                        }
                    }
                    expect(found).to.be(true);
                    return done();
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>/*
 * L.esri.WebMap
 *
 *
 */

L.esri.WebMap = L.Class.extend({
	options: {
		map: {}
	},

	initialize: function(webmapId, options) {
		L.setOptions(this, options);

		this._map = this.options.map;
		this._webmapId = webmapId;
		this._mapOptions = {};
		this._baseMap = {};
		this._operationalLayers = {};
		this._exportOptions = {};
		this._layoutOptions = {};

        this.layers = [];

		this._loadWebMapMetaData(webmapId);
		this._loadWebMap(webmapId);
	},

	_loadWebMapMetaData: function(id) {
        console.log(this);
		var map = this._map;
		var leafletLatlng = this.leafletLatlng;
		var webmapMetaDataRequestUrl = 'https://www.arcgis.com/sharing/rest/content/items/' + id;
		L.esri.request(webmapMetaDataRequestUrl, {}, function(error, response){
		  if(error){
		    console.log(error);
		  } else {
		    console.log(response);
				console.log('extent: ', response.extent);

				map.fitBounds([leafletLatlng(response.extent[0]), leafletLatlng(response.extent[1])]);
		  }
		});
	},

	_loadWebMap: function(id) {
		var map = this._map;
		var generateEsriLayer = this._generateEsriLayer;
		//var basemapKey = this.getBasemapKey;
		var webmapRequestUrl = 'https://www.arcgis.com/sharing/rest/content/items/' + id + '/data?f=json';
		L.esri.request(webmapRequestUrl, {}, function(error, response){
		  if(error){
		    console.log(error);
		  } else {
		    console.log(response);
				console.log('baseMap: ', response.baseMap);
				console.log('operationalLayers: ', response.operationalLayers);

				// Add Basemap
				response.baseMap.baseMapLayers.map(function(baseMapLayer) {
					generateEsriLayer(baseMapLayer).addTo(map);
				});

				// Add Operational Layers
				response.operationalLayers.map(function(layer) {
                    var lyr = generateEsriLayer(layer);
                    this.webmap.layers.push(lyr);
                    lyr.addTo(map);
				});
		  }
		});
	},

	leafletLatlng: function(latlng) {
		var changedLatlng = [latlng[1], latlng[0]];
		return changedLatlng;
	},

    _createPopupContent: function(popupInfo, properties) {
        //console.log(popupInfo, properties);
        var content = '
' + popupInfo.title + '
';
        if(popupInfo.fieldInfos.length > 0) {
            popupInfo.fieldInfos.map(function(info) {
                content += '
' + info.label + '
 ' + properties[info.fieldName] + '
';
            });
        }
        if(popupInfo.mediaInfos.length > 0) {

        }
        return content;
    },

    _pointSymbol: function(symbol) {
        var icon;
        if(symbol.type === 'esriPMS') {
            icon = L.icon({
                iconUrl: symbol.url,
                shadowUrl: '',
                iconSize:     [symbol.height, symbol.width],
                shadowSize:   [0, 0],
                iconAnchor:   [symbol.height-16, symbol.width-1],
                shadowAnchor: [0, 0],
                popupAnchor:  [symbol.width/3, symbol.height*-1]
            });
        }
        if(symbol.type === 'esriSMS') {
            if(symbol.style === 'esriSMSCircle') {
                if(symbol.outline.style === 'esriSLSNull') {
                    icon = L.vectorIcon({
                        //className: 'my-vector-icon',
                        svgHeight: (symbol.size + symbol.outline.width) * 2,
                        svgWidth: (symbol.size + symbol.outline.width) * 2,
                        type: 'circle',
                        shape: {
                            r: symbol.size + '',
                            cx: symbol.size + symbol.outline.width,
                            cy: symbol.size + symbol.outline.width
                        },
                        style: {
                            fill: 'rgba(' + symbol.color[0] + ',' + symbol.color[1] + ',' + symbol.color[2] + ',' + symbol.color[3]/255 + ')',
                            //stroke: '',
                            strokeWidth: 0
                        }
                    });
                }
                else {
                    icon = L.vectorIcon({
                        //className: 'my-vector-icon',
                        svgHeight: (symbol.size + symbol.outline.width) * 2,
                        svgWidth: (symbol.size + symbol.outline.width) * 2,
                        type: 'circle',
                        shape: {
                            r: symbol.size + '',
                            cx: symbol.size + symbol.outline.width,
                            cy: symbol.size + symbol.outline.width
                        },
                        style: {
                            fill: 'rgba(' + symbol.color[0] + ',' + symbol.color[1] + ',' + symbol.color[2] + ',' + symbol.color[3]/255 + ')',
                            stroke: 'rgba(' + symbol.outline.color[0] + ',' + symbol.outline.color[1] + ',' + symbol.outline.color[2] + ',' + symbol.outline.color[3]/255 + ')',
                            strokeWidth: symbol.outline.width
                        }
                    });
                }
            }
            if(symbol.style === '') {

            }
            if(symbol.style === '') {

            }
        }
        return icon;
    },

    _generateIcon: function(renderer, properties) {
        //console.log(renderer);
        var icon;
        if(renderer.type === 'simple') {
            icon = this._pointSymbol(renderer.symbol);
        }
        if(renderer.type === 'uniqueValue') {
            renderer.uniqueValueInfos.map(function(info) {
                if(info.value === properties[renderer.field1]) { // field2, field3は後で考えよう
                    icon = this.webmap._pointSymbol(info.symbol);
                }
            });
        }
        if(renderer.type === 'classBreaks') {
            renderer.classBreakInfos.map(function(info) {
                if(info.classMinValue !== undefined) {
                    if(info.classMinValue <= properties[renderer.field] && info.classMaxValue > properties[renderer.field]) {
                        icon = this.webmap._pointSymbol(info.symbol);
                    }
                }
                else {
                    if(info.classMaxValue > properties[renderer.field]) {
                        icon = this.webmap._pointSymbol(info.symbol);
                    }
                }
            });
        }
        return icon;
    },

    _generateLabel: function(properties, labelingInfo) {
        //console.log('generateLabels: ', properties, labelingInfo);
        var r = /\[([^\]]*)\]/g;
        var labelText = labelingInfo[0].labelExpression;
        labelText = labelText.replace(r, function(s) {
            var m = r.exec(s);
            //console.log(m[1]);
            //console.log(properties[m[1]]);
            return properties[m[1]];
        });
        return labelText;
    },

	_generateEsriLayer: function(layer) {
		console.log('generateEsriLayer: ', layer.title, layer);

		console.log(this.webmap);

		if(layer.featureCollection !== undefined) {
            // Supporting only point geometry
            console.log('create FeatureCollection');
            var renderer = layer.featureCollection.layers[0].layerDefinition.drawingInfo.renderer;
            console.log(renderer);
            var features = [];
            layer.featureCollection.layers[0].featureSet.features.map(function(feature) {

                var popupContent = this.webmap._createPopupContent(layer.featureCollection.layers[0].popupInfo, feature.attributes);
                var icon = this.webmap._generateIcon(renderer, feature.attributes);
                var mercatorToLatlng = L.Projection.SphericalMercator.unproject(L.point(feature.geometry.x, feature.geometry.y));

                var f = L.marker(mercatorToLatlng, { icon: icon, opacity: layer.opacity }).bindPopup(popupContent);

                if(layer.featureCollection.layers[0].layerDefinition.drawingInfo.labelingInfo !== undefined) {
                    var labelingInfo = layer.featureCollection.layers[0].layerDefinition.drawingInfo.labelingInfo;
                    var labelText = this.webmap._generateLabel(feature.attributes, labelingInfo);
                    //f.bindLabel(labelText, { noHide: true }).showLabel();
                }

                features.push(f);
            });

            var lyr = L.featureGroup(features);
            return lyr;
        }
        if(layer.layerType === 'ArcGISFeatureLayer' && layer.layerDefinition !== undefined) {
            if(layer.layerDefinition.drawingInfo.renderer.type === 'heatmap'){
                console.log('create HeatmapLayer');
                var gradient = {};
                layer.layerDefinition.drawingInfo.renderer.colorStops.map(function(stop) {
                    //gradient[stop.ratio] = 'rgba(' + stop.color[0] + ',' + stop.color[1] + ',' + stop.color[2] + ',' + (stop.color[3]/255) + ')';
                    gradient[Math.round(stop.ratio*100)/100] = 'rgb(' + stop.color[0] + ',' + stop.color[1] + ',' + stop.color[2] + ')';
                });
                //console.log(gradient);

                var lyr = L.esri.Heat.heatmapFeatureLayer({ // Esri Leaflet 2.0
                //var lyr = L.esri.heatmapFeatureLayer({ // Esri Leaflet 1.0
                    url: layer.url,
                    //blur: layer.layerDefinition.drawingInfo.renderer.blurRadius,
                    //max: layer.layerDefinition.drawingInfo.renderer.maxPixelIntensity,
                    gradient: gradient
                })
                return lyr;
            }
		}
		if(layer.layerType === 'ArcGISFeatureLayer' && layer.layerDefinition !== undefined) {
            if(layer.layerDefinition.drawingInfo !== undefined){
                console.log('create ArcGISFeatureLayer (with layerDefinition)');
                var renderer = layer.layerDefinition.drawingInfo.renderer;

                var lyr = L.esri.featureLayer({
                    url: layer.url,
                    pointToLayer: function (geojson, latlng) {

                        var popupContent = this.webmap._createPopupContent(layer.popupInfo, geojson.properties);
                        var icon = this.webmap._generateIcon(renderer, geojson.properties);

                        var f = L.marker(latlng, {
                            icon: icon,
                            opacity: layer.opacity
                        }).bindPopup(popupContent);

                        if(layer.layerDefinition.drawingInfo.labelingInfo !== undefined) {
                            var labelingInfo = layer.layerDefinition.drawingInfo.labelingInfo;
                            var labelText = this.webmap._generateLabel(geojson.properties, labelingInfo);
                            //f.bindLabel(labelText, { noHide: true }).showLabel();
                        }

                        return f;
                    }
                });
                return lyr;
            }
		}
		if(layer.layerType === 'ArcGISFeatureLayer') {
			console.log('create ArcGISFeatureLayer');
            var lyr = L.esri.featureLayer({
                url: layer.url,
                pointToLayer: function (geojson, latlng) {

                    var popupContent = this.webmap._createPopupContent(layer.popupInfo, geojson.properties);
                    //var icon = this.webmap._generateIcon(renderer, geojson.properties);

                    var f = L.marker(latlng, {
                        //icon: icon,
                        opacity: layer.opacity
                    }).bindPopup(popupContent);

                    return f;
                }
            });
			return lyr;
		}
		if(layer.layerType === 'ArcGISImageServiceLayer') {
			console.log('create ArcGISImageServiceLayer');
			var lyr = L.esri.imageMapLayer({
				url: layer.url
			});
			return lyr;
		}
		if(layer.layerType === 'ArcGISMapServiceLayer') {
			var lyr = L.esri.dynamicMapLayer({
				url: layer.url
			});
			return lyr;
		}
		if(layer.layerType === 'ArcGISTiledMapServiceLayer') {
			var lyr = L.esri.tiledMapLayer({
				url: layer.url
			});
			return lyr;
		}
		if(layer.layerType === '') {
			return false;
		}
		if(layer.layerType === '') {
			return false;
		}
	}

});

L.esri.webMap = function (webmapId, options) {
	return new L.esri.WebMap(webmapId, options);
};<commit_msg>FeatureLayer: definitionExpression (where)<commit_after>/*
 * L.esri.WebMap
 *
 *
 */

L.esri.WebMap = L.Class.extend({
	options: {
		map: {}
	},

	initialize: function(webmapId, options) {
		L.setOptions(this, options);

		this._map = this.options.map;
		this._webmapId = webmapId;
		this._mapOptions = {};
		this._baseMap = {};
		this._operationalLayers = {};
		this._exportOptions = {};
		this._layoutOptions = {};

        this.layers = [];

		this._loadWebMapMetaData(webmapId);
		this._loadWebMap(webmapId);
	},

	_loadWebMapMetaData: function(id) {
        console.log(this);
		var map = this._map;
		var leafletLatlng = this.leafletLatlng;
		var webmapMetaDataRequestUrl = 'https://www.arcgis.com/sharing/rest/content/items/' + id;
		L.esri.request(webmapMetaDataRequestUrl, {}, function(error, response){
		  if(error){
		    console.log(error);
		  } else {
		    console.log(response);
				console.log('extent: ', response.extent);

				map.fitBounds([leafletLatlng(response.extent[0]), leafletLatlng(response.extent[1])]);
		  }
		});
	},

	_loadWebMap: function(id) {
		var map = this._map;
		var generateEsriLayer = this._generateEsriLayer;
		//var basemapKey = this.getBasemapKey;
		var webmapRequestUrl = 'https://www.arcgis.com/sharing/rest/content/items/' + id + '/data';
		L.esri.request(webmapRequestUrl, {}, function(error, response){
		  if(error){
		    console.log(error);
		  } else {
		    console.log(response);
				console.log('baseMap: ', response.baseMap);
				console.log('operationalLayers: ', response.operationalLayers);

				// Add Basemap
				response.baseMap.baseMapLayers.map(function(baseMapLayer) {
					generateEsriLayer(baseMapLayer).addTo(map);
				});

				// Add Operational Layers
				response.operationalLayers.map(function(layer) {
                    var lyr = generateEsriLayer(layer);
                    this.webmap.layers.push(lyr);
                    lyr.addTo(map);
				});
		  }
		});
	},

	leafletLatlng: function(latlng) {
		var changedLatlng = [latlng[1], latlng[0]];
		return changedLatlng;
	},

    _createPopupContent: function(popupInfo, properties) {
        //console.log(popupInfo, properties);
        var content = '
' + popupInfo.title + '
';
        if(popupInfo.fieldInfos.length > 0) {
            popupInfo.fieldInfos.map(function(info) {
                content += '
' + info.label + '
 ' + properties[info.fieldName] + '
';
            });
        }
        if(popupInfo.mediaInfos.length > 0) {

        }
        return content;
    },

    _pointSymbol: function(symbol) {
        var icon;
        if(symbol.type === 'esriPMS') {
            icon = L.icon({
                iconUrl: symbol.url,
                shadowUrl: '',
                iconSize:     [symbol.height, symbol.width],
                shadowSize:   [0, 0],
                iconAnchor:   [symbol.height-16, symbol.width-1],
                shadowAnchor: [0, 0],
                popupAnchor:  [symbol.width/3, symbol.height*-1]
            });
        }
        if(symbol.type === 'esriSMS') {
            if(symbol.style === 'esriSMSCircle') {
                if(symbol.outline.style === 'esriSLSNull') {
                    icon = L.vectorIcon({
                        //className: 'my-vector-icon',
                        svgHeight: (symbol.size + symbol.outline.width) * 2,
                        svgWidth: (symbol.size + symbol.outline.width) * 2,
                        type: 'circle',
                        shape: {
                            r: symbol.size + '',
                            cx: symbol.size + symbol.outline.width,
                            cy: symbol.size + symbol.outline.width
                        },
                        style: {
                            fill: 'rgba(' + symbol.color[0] + ',' + symbol.color[1] + ',' + symbol.color[2] + ',' + symbol.color[3]/255 + ')',
                            //stroke: '',
                            strokeWidth: 0
                        }
                    });
                }
                else {
                    icon = L.vectorIcon({
                        //className: 'my-vector-icon',
                        svgHeight: (symbol.size + symbol.outline.width) * 2,
                        svgWidth: (symbol.size + symbol.outline.width) * 2,
                        type: 'circle',
                        shape: {
                            r: symbol.size + '',
                            cx: symbol.size + symbol.outline.width,
                            cy: symbol.size + symbol.outline.width
                        },
                        style: {
                            fill: 'rgba(' + symbol.color[0] + ',' + symbol.color[1] + ',' + symbol.color[2] + ',' + symbol.color[3]/255 + ')',
                            stroke: 'rgba(' + symbol.outline.color[0] + ',' + symbol.outline.color[1] + ',' + symbol.outline.color[2] + ',' + symbol.outline.color[3]/255 + ')',
                            strokeWidth: symbol.outline.width
                        }
                    });
                }
            }
            if(symbol.style === '') {

            }
            if(symbol.style === '') {

            }
        }
        return icon;
    },

    _generateIcon: function(renderer, properties) {
        //console.log(renderer);
        var icon;
        if(renderer.type === 'simple') {
            icon = this._pointSymbol(renderer.symbol);
        }
        if(renderer.type === 'uniqueValue') {
            renderer.uniqueValueInfos.map(function(info) {
                if(info.value === properties[renderer.field1]) { // field2, field3は後で考えよう
                    icon = this.webmap._pointSymbol(info.symbol);
                }
            });
        }
        if(renderer.type === 'classBreaks') {
            renderer.classBreakInfos.map(function(info) {
                if(info.classMinValue !== undefined) {
                    if(info.classMinValue <= properties[renderer.field] && info.classMaxValue > properties[renderer.field]) {
                        icon = this.webmap._pointSymbol(info.symbol);
                    }
                }
                else {
                    if(info.classMaxValue > properties[renderer.field]) {
                        icon = this.webmap._pointSymbol(info.symbol);
                    }
                }
            });
        }
        return icon;
    },

    _generateLabel: function(properties, labelingInfo) {
        //console.log('generateLabels: ', properties, labelingInfo);
        var r = /\[([^\]]*)\]/g;
        var labelText = labelingInfo[0].labelExpression;
        labelText = labelText.replace(r, function(s) {
            var m = r.exec(s);
            //console.log(m[1]);
            //console.log(properties[m[1]]);
            return properties[m[1]];
        });
        return labelText;
    },

	_generateEsriLayer: function(layer) {
		console.log('generateEsriLayer: ', layer.title, layer);

		console.log(this.webmap);

		if(layer.featureCollection !== undefined) {
            // Supporting only point geometry
            console.log('create FeatureCollection');
            var renderer = layer.featureCollection.layers[0].layerDefinition.drawingInfo.renderer;
            console.log(renderer);
            var features = [];
            layer.featureCollection.layers[0].featureSet.features.map(function(feature) {

                var popupContent = this.webmap._createPopupContent(layer.featureCollection.layers[0].popupInfo, feature.attributes);
                var icon = this.webmap._generateIcon(renderer, feature.attributes);
                var mercatorToLatlng = L.Projection.SphericalMercator.unproject(L.point(feature.geometry.x, feature.geometry.y));

                var f = L.marker(mercatorToLatlng, { icon: icon, opacity: layer.opacity }).bindPopup(popupContent);

                if(layer.featureCollection.layers[0].layerDefinition.drawingInfo.labelingInfo !== undefined) {
                    var labelingInfo = layer.featureCollection.layers[0].layerDefinition.drawingInfo.labelingInfo;
                    var labelText = this.webmap._generateLabel(feature.attributes, labelingInfo);
                    //f.bindLabel(labelText, { noHide: true }).showLabel();
                }

                features.push(f);
            });

            var lyr = L.featureGroup(features);
            return lyr;
        }
        if(layer.layerType === 'ArcGISFeatureLayer' && layer.layerDefinition.drawingInfo !== undefined) {
            if(layer.layerDefinition.drawingInfo.renderer.type === 'heatmap'){
                console.log('create HeatmapLayer');
                var gradient = {};
                layer.layerDefinition.drawingInfo.renderer.colorStops.map(function(stop) {
                    //gradient[stop.ratio] = 'rgba(' + stop.color[0] + ',' + stop.color[1] + ',' + stop.color[2] + ',' + (stop.color[3]/255) + ')';
                    gradient[Math.round(stop.ratio*100)/100] = 'rgb(' + stop.color[0] + ',' + stop.color[1] + ',' + stop.color[2] + ')';
                });
                //console.log(gradient);

                var lyr = L.esri.Heat.heatmapFeatureLayer({ // Esri Leaflet 2.0
                //var lyr = L.esri.heatmapFeatureLayer({ // Esri Leaflet 1.0
                    url: layer.url,
                    //blur: layer.layerDefinition.drawingInfo.renderer.blurRadius,
                    //max: layer.layerDefinition.drawingInfo.renderer.maxPixelIntensity,
                    gradient: gradient
                })
                return lyr;
            }
		}
		if(layer.layerType === 'ArcGISFeatureLayer' && layer.layerDefinition !== undefined) {
            if(layer.layerDefinition.drawingInfo !== undefined){
                console.log('create ArcGISFeatureLayer (with layerDefinition.drawingInfo)');
                var renderer = layer.layerDefinition.drawingInfo.renderer;
                var where = '1=1';
                if(layer.layerDefinition.definitionExpression !== undefined) {
                    where = layer.layerDefinition.definitionExpression;
                }

                var lyr = L.esri.featureLayer({
                    url: layer.url,
                    where: where,
                    pointToLayer: function (geojson, latlng) {

                        var popupContent = this.webmap._createPopupContent(layer.popupInfo, geojson.properties);
                        var icon = this.webmap._generateIcon(renderer, geojson.properties);

                        var f = L.marker(latlng, {
                            icon: icon,
                            opacity: layer.opacity
                        }).bindPopup(popupContent);

                        if(layer.layerDefinition.drawingInfo.labelingInfo !== undefined) {
                            var labelingInfo = layer.layerDefinition.drawingInfo.labelingInfo;
                            var labelText = this.webmap._generateLabel(geojson.properties, labelingInfo);
                            //f.bindLabel(labelText, { noHide: true }).showLabel();
                        }

                        return f;
                    }
                });
                return lyr;
            }
            else {
                console.log('create ArcGISFeatureLayer (without layerDefinition.drawingInfo)');
                var where = '1=1';
                if(layer.layerDefinition.definitionExpression !== undefined) {
                    where = layer.layerDefinition.definitionExpression;
                }

                var lyr = L.esri.featureLayer({
                    url: layer.url,
                    where: where,
                    pointToLayer: function (geojson, latlng) {

                        var popupContent = this.webmap._createPopupContent(layer.popupInfo, geojson.properties);
                        //var icon = this.webmap._generateIcon(renderer, geojson.properties);

                        var f = L.marker(latlng, {
                            //icon: icon,
                            opacity: layer.opacity
                        }).bindPopup(popupContent);

                        return f;
                    }
                });
                return lyr;
            }
		}
		if(layer.layerType === 'ArcGISFeatureLayer') {
			console.log('create ArcGISFeatureLayer');
            var lyr = L.esri.featureLayer({
                url: layer.url,
                pointToLayer: function (geojson, latlng) {

                    var popupContent = this.webmap._createPopupContent(layer.popupInfo, geojson.properties);
                    //var icon = this.webmap._generateIcon(renderer, geojson.properties);

                    var f = L.marker(latlng, {
                        //icon: icon,
                        opacity: layer.opacity
                    }).bindPopup(popupContent);

                    return f;
                }
            });
			return lyr;
		}
		if(layer.layerType === 'ArcGISImageServiceLayer') {
			console.log('create ArcGISImageServiceLayer');
			var lyr = L.esri.imageMapLayer({
				url: layer.url
			});
			return lyr;
		}
		if(layer.layerType === 'ArcGISMapServiceLayer') {
			var lyr = L.esri.dynamicMapLayer({
				url: layer.url
			});
			return lyr;
		}
		if(layer.layerType === 'ArcGISTiledMapServiceLayer') {
			var lyr = L.esri.tiledMapLayer({
				url: layer.url
			});
			return lyr;
		}
		if(layer.layerType === '') {
			return false;
		}
		if(layer.layerType === '') {
			return false;
		}
	}

});

L.esri.webMap = function (webmapId, options) {
	return new L.esri.WebMap(webmapId, options);
};<|endoftext|>


<commit_before>/*
 * loggly-test.js: Tests for instances of the Loggly transport
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENSE
 *
 */

var path = require('path'),
    vows = require('vows'),
    assert = require('assert'),
    winston = require('../../lib/winston'),
    helpers = require('../helpers');

var config = helpers.loadConfig(),
    tokenTransport = new (winston.transports.Loggly)({
      subdomain: config.transports.loggly.subdomain,
      inputToken: config.transports.loggly.inputToken
    }),
    nameTransport = new (winston.transports.Loggly)({
      subdomain: config.transports.loggly.subdomain,
      inputName: config.transports.loggly.inputName,
      auth: config.transports.loggly.auth
    });

vows.describe('winston/transports/loggly').addBatch({
  "An instance of the Loggly Transport": {
    "when passed an input token": {
      "should have the proper methods defined": function () {
        helpers.assertLoggly(tokenTransport);
      },
      "the log() method": helpers.testNpmLevels(tokenTransport, "should log messages to loggly", function (ign, err, logged) {
        assert.isNull(err);
        assert.isTrue(logged);
      })
    },
    "when passed an input name": {
      "should have the proper methods defined": function () {
        helpers.assertLoggly(nameTransport);
      },
      "the log() method": helpers.testNpmLevels(nameTransport, "should log messages to loggly", function (ign, err, result) {
        assert.isNull(err);
        assert.isTrue(result === true || result.response === 'ok');
      })
    }
  }
}).export(module);<commit_msg>[dist] Remove old test code<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Table, Icon } from 'semantic-ui-react';
import data from './data/food.json';

class List extends Component {
  render() {
    let list = [];

    let categories = data.categories;
    let status = data.status;

    data.foods.forEach((item, index) => {
      if (item.name.toLowerCase().includes(this.props.term) || this.props.term === "") {
        list.push(
          <Table.Row positive={ !item.status } negative={ item.status } key={ index } >
            <Table.Cell>
              { !item.status ? (
                <Icon name='checkmark' />
              ) : (
                <Icon name='close' />
              )}
            </Table.Cell>
            <Table.Cell>{ item.name }</Table.Cell>
            <Table.Cell>{ categories[item.category] }</Table.Cell>
            <Table.Cell warning={ item.hasOwnProperty('note') }>{ item.note }</Table.Cell>
          </Table.Row>
        );
      }
    });

    return (
      <Table celled striped compact unstackable>
        <Table.Header>
          <Table.Row>
            <Table.HeaderCell></Table.HeaderCell>
            <Table.HeaderCell>Name</Table.HeaderCell>
            <Table.HeaderCell>Category</Table.HeaderCell>
            <Table.HeaderCell>Note</Table.HeaderCell>
          </Table.Row>
        </Table.Header>

        <Table.Body>
          { list }
        </Table.Body>
      </Table>
    );
  }
}

export default List;
<commit_msg>Make table basic and no longer striped<commit_after>import React, { Component } from 'react';
import { Table, Icon } from 'semantic-ui-react';
import data from './data/food.json';

class List extends Component {
  render() {
    let list = [];

    let categories = data.categories;
    let status = data.status;

    data.foods.forEach((item, index) => {
      if (item.name.toLowerCase().includes(this.props.term) || this.props.term === "") {
        list.push(
          <Table.Row positive={ !item.status } negative={ item.status } key={ index } >
            <Table.Cell>
              { !item.status ? (
                <Icon name='checkmark' />
              ) : (
                <Icon name='close' />
              )}
            </Table.Cell>
            <Table.Cell>{ item.name }</Table.Cell>
            <Table.Cell>{ categories[item.category] }</Table.Cell>
            <Table.Cell warning={ item.hasOwnProperty('note') }>{ item.note }</Table.Cell>
          </Table.Row>
        );
      }
    });

    return (
      <Table celled basic compact unstackable>
        <Table.Header>
          <Table.Row>
            <Table.HeaderCell></Table.HeaderCell>
            <Table.HeaderCell>Name</Table.HeaderCell>
            <Table.HeaderCell>Category</Table.HeaderCell>
            <Table.HeaderCell>Note</Table.HeaderCell>
          </Table.Row>
        </Table.Header>

        <Table.Body>
          { list }
        </Table.Body>
      </Table>
    );
  }
}

export default List;
<|endoftext|>


<commit_before>import { expect } from 'chai';

import { launchNewNotebook } from '../../build/main/launch';
import {ipcMain as ipc} from 'electron';

describe('launch', () => {
  describe('launchNewNotebook', () => {
    it('launches a window', function(done) {
      this.timeout(7000);

      const win = launchNewNotebook('python3');
      win.hide();
      ipc.on('nteract:ping:kernel', (event, kernel) => {
        win.close();
        expect(kernel).to.equal('python3');
        done();
      });

      setTimeout(() => {
        expect.fail('nteract:ping:kernel', null, 'Expected nteract:ping:kernel to be sent from frontend');
        done();
      }, 6000)
    });
  });
});
<commit_msg>comment on hiding<commit_after>import { expect } from 'chai';

import { launchNewNotebook } from '../../build/main/launch';
import {ipcMain as ipc} from 'electron';

describe('launch', () => {
  describe('launchNewNotebook', () => {
    it('launches a window', function(done) {
      this.timeout(7000);

      const win = launchNewNotebook('python3');
      win.hide(); // To make it nicer to run locally
      ipc.on('nteract:ping:kernel', (event, kernel) => {
        win.close();
        expect(kernel).to.equal('python3');
        done();
      });

      setTimeout(() => {
        expect.fail('nteract:ping:kernel', null, 'Expected nteract:ping:kernel to be sent from frontend');
        done();
      }, 6000)
    });
  });
});
<|endoftext|>