<commit_before>// Reference to my Firebase
var myFirebaseRef = new Firebase('https://torrid-inferno-1243.firebaseio.com/');

// Grobal
var index = 4;
var maps = [];

console.log('%c⚛ Projection Mapping Tool: Hello geohacker! ⚛', 'font-family:monospace;font-size:16px;color:darkblue;');

// Create menu icon
$.fatNav();

// Menu event listner
$('.fat-nav__wrapper').on('click', function(e) {
  console.log(e.target.text);
  createMapContainer(e.target.text);
});

// Create container before map
function createMapContainer(type) {
  var mapCont = $('
', {
    id: 'l-map' + index,
    css: { top: '50px', left: '50px' },
    addClass: 'l-map'
  });
  $('body').append(mapCont);
  Maptastic('l-map' + index);
  createMap(index, type);
  index += 1;
}

// Create map and add tile layer
function createMap(index, type) {
  var center = [35.8, 139];
  var zoom = 4;
  var map = L.map('l-map' + index, { zoomControl: false, attributionControl: false }).setView(center, zoom);
  maps.push(map);

  switch (type) {
    case 'OpenStreetMap':
      L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: 'Map data © OpenStreetMap contributors, ' +
        'CC-BY-SA',
        id: 'osm' + index
      }).addTo(map);
      break;
    case 'Esri Satellite':
      L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        maxZoom: 18,
        attribution: '© Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
        id: 'esri-satellite' + index
      }).addTo(map);
      break;
    case 'Stamen Tonar':
      L.tileLayer('//stamen-tiles-a.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA. | Video from Mazwai.',
        id: 'stamen-toner' + index
      }).addTo(map);
      break;
  }
}

// Create GeoJSON layer and add into maps
function createGeoJSONLayer(url) {
  var markerIcon = L.divIcon({
    className: 'svg-marker-icon',
    html: '<svg width="64px" height="64px" viewBox="-20 -20 64 64"><g><circle class="circles" opacity="0.4" r="6" transform="translate(0,0)"></circle></g></svg>'
  });
  var pathStyle = {
    color: '#ff6500',
    weight: 1,
    opacity: 0.8,
    fillOpacity: 0.35,
    fillColor: '#ff6500'
  };
  $.getJSON(url, function(data) {
    $.each(maps, function(i, map) {
      var geojson = L.geoJson(data, {
        onEachFeature: function(feature, layer) {
          console.log(layer.feature.geometry.type);
          if(layer.feature.geometry.type === 'Polygon' || layer.feature.geometry.type === 'MultiPolygon' || layer.feature.geometry.type === 'Polyline') {
            layer.setStyle(pathStyle);
          }
          else if(layer.feature.geometry.type === 'Point' || layer.feature.geometry.type === 'MultiPoint') {
            layer.setIcon(markerIcon);
          }
          else {
            return false;
          }
        }
      });
      geojson.addTo(map);
    });
  });
}

// Init
function initMap() {
  var center = [35.8, 139];
  var zoom = 4;
  var map1 = L.map('l-map1', { zoomControl: false, attributionControl: false }).setView(center, zoom);
  var map2 = L.map('l-map2', { zoomControl: false, attributionControl: false }).setView(center, zoom);
  var map3 = L.map('l-map3', { zoomControl: false, attributionControl: false }).setView(center, zoom);
  maps = [map1, map2, map3];

  // The elements will be available to transform
  Maptastic('l-map1');
  Maptastic('l-map2');
  Maptastic('l-map3');

  L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'Map data © OpenStreetMap contributors, ' +
    'CC-BY-SA',
    id: 'osm'
  }).addTo(map1);
  L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
    maxZoom: 18,
    attribution: '© Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
    id: 'esri-satellite'
  }).addTo(map2);
  L.tileLayer('//stamen-tiles-a.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA. | Video from Mazwai.',
    id: 'stamen-toner'
  }).addTo(map3);

  // Firebase event listners
  myFirebaseRef.child('map/center').on('value', function(snapshot) {
    center = snapshot.val();
    console.log(maps);
    $.each(maps, function(i, map) {
      map.setView(center, zoom);
    });
  });
  myFirebaseRef.child('map/zoom').on('value', function(snapshot) {
    zoom = snapshot.val();
    $.each(maps, function(i, map) {
      map.setView(center, zoom);
    });
  });
  myFirebaseRef.child('flash1').on('value', function(snapshot) {
    var flag = snapshot.val();
    console.log(flag);
    if(flag === true) {
      console.log('flash1!');
      $.each(maps, function(i, map) {
        map.eachLayer(function (layer) {
          layer.setOpacity(0);
          setTimeout(function() {
            layer.setOpacity(1);
          }, 100);
        });
      });
    }
  });
  myFirebaseRef.child('flash2').on('value', function(snapshot) {
    var flag = snapshot.val();
    console.log(flag);
    if(flag === true) {
      console.log('flash2!');
      $.each(maps, function(i, map) {
        map.eachLayer(function (layer) {
          setTimeout(function() {
            layer.setOpacity(0);
            setTimeout(function() {
              layer.setOpacity(1);
            }, 100);
          }, 100 * i);
        });
      });
    }
  });
  myFirebaseRef.child('dataUrl').on('value', function(snapshot) {
    var url = snapshot.val();
    console.log(url);
    createGeoJSONLayer(url);
  });
}
initMap();
<commit_msg>updates<commit_after>// Reference to my Firebase
var myFirebaseRef = new Firebase('https://<YOUR-APP>.firebaseio.com/');

// Grobal
var index = 4;
var maps = [];

console.log('%c⚛ Projection Mapping Tool: Hello geohacker! ⚛', 'font-family:monospace;font-size:16px;color:darkblue;');

// Create menu icon
$.fatNav();

// Menu event listner
$('.fat-nav__wrapper').on('click', function(e) {
  console.log(e.target.text);
  createMapContainer(e.target.text);
});

// Create container before map
function createMapContainer(type) {
  var mapCont = $('
', {
    id: 'l-map' + index,
    css: { top: '50px', left: '50px' },
    addClass: 'l-map'
  });
  $('body').append(mapCont);
  Maptastic('l-map' + index);
  createMap(index, type);
  index += 1;
}

// Create map and add tile layer
function createMap(index, type) {
  var center = [35.8, 139];
  var zoom = 4;
  var map = L.map('l-map' + index, { zoomControl: false, attributionControl: false }).setView(center, zoom);
  maps.push(map);

  switch (type) {
    case 'OpenStreetMap':
      L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: 'Map data © OpenStreetMap contributors, ' +
        'CC-BY-SA',
        id: 'osm' + index
      }).addTo(map);
      break;
    case 'Esri Satellite':
      L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        maxZoom: 18,
        attribution: '© Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
        id: 'esri-satellite' + index
      }).addTo(map);
      break;
    case 'Stamen Tonar':
      L.tileLayer('//stamen-tiles-a.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA. | Video from Mazwai.',
        id: 'stamen-toner' + index
      }).addTo(map);
      break;
  }
}

// Create GeoJSON layer and add into maps
function createGeoJSONLayer(url) {
  var markerIcon = L.divIcon({
    className: 'svg-marker-icon',
    html: '<svg width="64px" height="64px" viewBox="-20 -20 64 64"><g><circle class="circles" opacity="0.4" r="6" transform="translate(0,0)"></circle></g></svg>'
  });
  var pathStyle = {
    color: '#ff6500',
    weight: 1,
    opacity: 0.8,
    fillOpacity: 0.35,
    fillColor: '#ff6500'
  };
  $.getJSON(url, function(data) {
    $.each(maps, function(i, map) {
      var geojson = L.geoJson(data, {
        onEachFeature: function(feature, layer) {
          console.log(layer.feature.geometry.type);
          if(layer.feature.geometry.type === 'Polygon' || layer.feature.geometry.type === 'MultiPolygon' || layer.feature.geometry.type === 'Polyline') {
            layer.setStyle(pathStyle);
          }
          else if(layer.feature.geometry.type === 'Point' || layer.feature.geometry.type === 'MultiPoint') {
            layer.setIcon(markerIcon);
          }
          else {
            return false;
          }
        }
      });
      geojson.addTo(map);
    });
  });
}

// Init
function initMap() {
  var center = [35.8, 139];
  var zoom = 4;
  var map1 = L.map('l-map1', { zoomControl: false, attributionControl: false }).setView(center, zoom);
  var map2 = L.map('l-map2', { zoomControl: false, attributionControl: false }).setView(center, zoom);
  var map3 = L.map('l-map3', { zoomControl: false, attributionControl: false }).setView(center, zoom);
  maps = [map1, map2, map3];

  // The elements will be available to transform
  Maptastic('l-map1');
  Maptastic('l-map2');
  Maptastic('l-map3');

  L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'Map data © OpenStreetMap contributors, ' +
    'CC-BY-SA',
    id: 'osm'
  }).addTo(map1);
  L.tileLayer('//server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
    maxZoom: 18,
    attribution: '© Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
    id: 'esri-satellite'
  }).addTo(map2);
  L.tileLayer('//stamen-tiles-a.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA. | Video from Mazwai.',
    id: 'stamen-toner'
  }).addTo(map3);

  // Firebase event listners
  myFirebaseRef.child('map/center').on('value', function(snapshot) {
    center = snapshot.val();
    console.log(maps);
    $.each(maps, function(i, map) {
      map.setView(center, zoom);
    });
  });
  myFirebaseRef.child('map/zoom').on('value', function(snapshot) {
    zoom = snapshot.val();
    $.each(maps, function(i, map) {
      map.setView(center, zoom);
    });
  });
  myFirebaseRef.child('flash1').on('value', function(snapshot) {
    var flag = snapshot.val();
    console.log(flag);
    if(flag === true) {
      console.log('flash1!');
      $.each(maps, function(i, map) {
        map.eachLayer(function (layer) {
          layer.setOpacity(0);
          setTimeout(function() {
            layer.setOpacity(1);
          }, 100);
        });
      });
    }
  });
  myFirebaseRef.child('flash2').on('value', function(snapshot) {
    var flag = snapshot.val();
    console.log(flag);
    if(flag === true) {
      console.log('flash2!');
      $.each(maps, function(i, map) {
        map.eachLayer(function (layer) {
          setTimeout(function() {
            layer.setOpacity(0);
            setTimeout(function() {
              layer.setOpacity(1);
            }, 100);
          }, 100 * i);
        });
      });
    }
  });
  myFirebaseRef.child('dataUrl').on('value', function(snapshot) {
    var url = snapshot.val();
    console.log(url);
    createGeoJSONLayer(url);
  });
}
initMap();
<|endoftext|>


<commit_before>/**
*	Chef and Cake solution
*
*	@author : Lakha Singh
*/

// Read Input from console
var readInput = function( callback ){
	process.stdin.setEncoding('utf8');
	callback = callback || function(){};

	// Start Listening to user input
	process.stdin.addListener('data', function( data ){
		callback( data );
	});
};

// Process input as per problem statement
function processInput( callback ){
	var i = 3, input = [], helper;

	callback = callback || function(){};

	readInput(function( data ){
		helper = data.split(' ');
		if ( i == 3 ){
			input.push({
				N: parseInt( helper[0], 10),
				K: parseInt( helper[1], 10),
				Q: parseInt( helper[2], 10)
			});
		}

		elseif ( i == 2 ){
			input.push({
				a: parseInt( helper[0], 10),
				b: parseInt( helper[1], 10),
				c: parseInt( helper[2], 10),
				d: parseInt( helper[3], 10),
				e: parseInt( helper[4], 10),
				f: parseInt( helper[5], 10),
				r: parseInt( helper[6], 10),
				s: parseInt( helper[7], 10),
				t: parseInt( helper[8], 10),
				m: parseInt( helper[9], 10),
				A: parseInt( helper[10], 10)
			});
		}

		elseif ( i == 1 ){
			input.push({
				L1: parseInt( helper[0], 10),
				La: parseInt( helper[1], 10),
				Lc: parseInt( helper[2], 10),
				Lm: parseInt( helper[3], 10),
				D1: parseInt( helper[4], 10),
				Da: parseInt( helper[5], 10),
				Dc: parseInt( helper[6], 10),
				Dm: parseInt( helper[7], 10)
			});
		}
		i--;

		if ( i == 0 ){
			callback( input );
		}
	});
}

var createIngridients = function( input ){
	var N = input[0].N;
	var a = input[1].a;
	var b = input[1].b;
	var c = input[1].c;
	var d = input[1].d;
	var e = input[1].e;
	var f = input[1].f;
	var r = input[1].r;
	var s = input[1].s;
	var t = input[1].t;
	var m = input[1].m;
	var A = [], x;

	A[1] = input[1].A;

	for ( x = 2; x <= N; i++ ){
		if(t^x % s  <= r) {
			 A[x] = (a*A[x-1]^2 + b*A[x-1] + c) % m
		}
	    else{
	        A[x] = (d*A[x-1]^2 + e*A[x-1] + f) % m
	    }
	}

	return A;
}

var min = function(a, b){
	return a < b ? a : b;
}

var createDishes = function( input ){
	var Q = input[0].Q;
	var L1 = input[2].L1;
	var La = input[2].La;
	var Lc = input[2].Lc;
	var Lm = input[2].Lm;
	var D1 = input[2].D1;
	var Da = input[2].Da;
	var Dc = input[2].Dc;
	var Dm = input[2].Dm;

	var dish = [], i, L, R;

	for (i = 1; i <= Q; i++){
	    L1 = (La * L1 + Lc) % Lm;
	    D1 = (Da * D1 + Dc) % Dm;
	    L = L1 + 1;
	    R = min(L + K - 1 + D1, N);
	    dish.push({
	    	L: L,
	    	R: R
	    });
	}

	return dish;
}

var findDishQualities = function( dishes, ingridients ){

}

var calcSumAndProduct = function( dishQualities ){

}

// start
processInput(function(input){
	// Ingridients
	var A = [];

	// dishes
	var Q = [];

	// Dish Qualities
	var DQ = [];

	A = createIngridients( input );

	Q = createDishes( input );

	DQ = findDishQualities( Q, A );

	console.log( calcSumAndProduct( DQ ) );
});<commit_msg>completed solution (untested)<commit_after>/**
*	Chef and Cake solution
*
*	@author : Lakha Singh
*/

var MOD = 1000000007;

// Read Input from console
var readInput = function( callback ){
	process.stdin.setEncoding('utf8');
	callback = callback || function(){};

	// Start Listening to user input
	process.stdin.addListener('data', function( data ){
		callback( data );
	});
};

// Process input as per problem statement
function processInput( callback ){
	var i = 3, input = [], helper;

	callback = callback || function(){};

	readInput(function( data ){
		helper = data.split(' ');
		if ( i == 3 ){
			input.push({
				N: parseInt( helper[0], 10),
				K: parseInt( helper[1], 10),
				Q: parseInt( helper[2], 10)
			});
		}

		elseif ( i == 2 ){
			input.push({
				a: parseInt( helper[0], 10),
				b: parseInt( helper[1], 10),
				c: parseInt( helper[2], 10),
				d: parseInt( helper[3], 10),
				e: parseInt( helper[4], 10),
				f: parseInt( helper[5], 10),
				r: parseInt( helper[6], 10),
				s: parseInt( helper[7], 10),
				t: parseInt( helper[8], 10),
				m: parseInt( helper[9], 10),
				A: parseInt( helper[10], 10)
			});
		}

		elseif ( i == 1 ){
			input.push({
				L1: parseInt( helper[0], 10),
				La: parseInt( helper[1], 10),
				Lc: parseInt( helper[2], 10),
				Lm: parseInt( helper[3], 10),
				D1: parseInt( helper[4], 10),
				Da: parseInt( helper[5], 10),
				Dc: parseInt( helper[6], 10),
				Dm: parseInt( helper[7], 10)
			});
		}
		i--;

		if ( i == 0 ){
			callback( input );
		}
	});
}

var createIngridients = function( input ){
	var N = input[0].N;
	var a = input[1].a;
	var b = input[1].b;
	var c = input[1].c;
	var d = input[1].d;
	var e = input[1].e;
	var f = input[1].f;
	var r = input[1].r;
	var s = input[1].s;
	var t = input[1].t;
	var m = input[1].m;
	var A = [], x;

	A[1] = input[1].A;

	for ( x = 2; x <= N; i++ ){
		if(t^x % s  <= r) {
			 A[x] = (a*A[x-1]^2 + b*A[x-1] + c) % m
		}
	    else{
	        A[x] = (d*A[x-1]^2 + e*A[x-1] + f) % m
	    }
	}

	return A;
}

var min = function(a, b){
	return a < b ? a : b;
}

var minValue = function( arr, s, e ){
	var minVal = arr[s++], i;

	for ( ; s <= e; s++ ){
		if ( minVal > arr[s]){
			minVal = arr[s];
		}
	}

	return minVal;
}

var createDishes = function( input ){
	var Q = input[0].Q;
	var L1 = input[2].L1;
	var La = input[2].La;
	var Lc = input[2].Lc;
	var Lm = input[2].Lm;
	var D1 = input[2].D1;
	var Da = input[2].Da;
	var Dc = input[2].Dc;
	var Dm = input[2].Dm;

	var dish = [], i, L, R;

	for (i = 1; i <= Q; i++){
	    L1 = (La * L1 + Lc) % Lm;
	    D1 = (Da * D1 + Dc) % Dm;
	    L = L1 + 1;
	    R = min(L + K - 1 + D1, N);
	    dish.push({
	    	L: L,
	    	R: R
	    });
	}

	return dish;
}

var findDishQualities = function( dishes, ingridients ){

	var i = 0, dq = [];

	for (; i < dishes.length; i++ ){
		dq.push( minValue( ingridients, dishes[ i ].L, dishes[ i ].R ) );
	}

	return dq;
}

var calcSumAndProduct = function( dishQualities ){
	var i, sum = 0, product = 1;

	for (; i < dishQualities.length; i++ ){
		sum += dishQualities[ i ];
		product *= dishQualities[ i ];

		if ( sum >= MOD ){
			sum -= MOD;
		}

		if ( product >= MOD ){
			product %= MOD;
		}
	}

	return sum + ' ' + product;
}

// start
processInput(function(input){
	// Ingridients
	var A = [];

	// dishes
	var Q = [];

	// Dish Qualities
	var DQ = [];

	A = createIngridients( input );

	Q = createDishes( input );

	DQ = findDishQualities( Q, A );

	console.log( calcSumAndProduct( DQ ) );
});<|endoftext|>


<commit_before>var ContributionsDAO = require("../data/contributions-dao").ContributionsDAO;

/* The ContributionsHandler must be constructed with a connected db */
function ContributionsHandler(db) {
    "use strict";

    var contributionsDAO = new ContributionsDAO(db);

    this.displayContributions = function(req, res, next) {
        var userId = req.session.userId;

        contributionsDAO.getByUserId(userId, function(error, contrib) {
            if (error) return next(error);

            contrib.userId = userId; //set for nav menu items
            return res.render("contributions", contrib);
        });
    };

    this.handleContributionsUpdate = function(req, res, next) {
        /*************** SECURITY ISSUE ****************
         ** What is bad about using eval() to parse   **
         ** user input here?                          **
         ***********************************************/
        var preTax = parseInt(req.body.preTax);
        var afterTax = parseInt(req.body.afterTax);
        var roth = parseInt(req.body.roth);

        var userId = req.session.userId;

        //validate contributions
        if (isNaN(preTax) || isNaN(afterTax) || isNaN(roth) || preTax < 0 || afterTax < 0 || roth < 0) {
            return res.render("contributions", {
                updateError: "Invalid contribution percentages",
                userId: userId
            });
        }
        // Prevent more than 30% contributions
        if (preTax + afterTax + roth > 30) {
            return res.render("contributions", {
                updateError: "Contribution percentages cannot exceed 30 %",
                userId: userId
            });
        }

        contributionsDAO.update(userId, preTax, afterTax, roth, function(err, contributions) {

            if (err) return next(err);

            contributions.updateSuccess = true;
            return res.render("contributions", contributions);
        });

    };

}

module.exports = ContributionsHandler;
<commit_msg>Update contributions.js<commit_after>var ContributionsDAO = require("../data/contributions-dao").ContributionsDAO;

/* The ContributionsHandler must be constructed with a connected db */
function ContributionsHandler(db) {
    "use strict";

    var contributionsDAO = new ContributionsDAO(db);

    this.displayContributions = function(req, res, next) {
        var userId = req.session.userId;

        contributionsDAO.getByUserId(userId, function(error, contrib) {
            if (error) return next(error);

            contrib.userId = userId; //set for nav menu items
            return res.render("contributions", contrib);
        });
    };

    this.handleContributionsUpdate = function(req, res, next) {
        /*************** SECURITY ISSUE ****************
         ** What is bad about using eval() to parse   **
         ** user input here?                          **
         ***********************************************/
         //This makes application vulnerable to SSJS attack. It can fixed simply by using parseInt()instead.
        var preTax = parseInt(req.body.preTax);
        var afterTax = parseInt(req.body.afterTax);
        var roth = parseInt(req.body.roth);

        var userId = req.session.userId;

        //validate contributions
        if (isNaN(preTax) || isNaN(afterTax) || isNaN(roth) || preTax < 0 || afterTax < 0 || roth < 0) {
            return res.render("contributions", {
                updateError: "Invalid contribution percentages",
                userId: userId
            });
        }
        // Prevent more than 30% contributions
        if (preTax + afterTax + roth > 30) {
            return res.render("contributions", {
                updateError: "Contribution percentages cannot exceed 30 %",
                userId: userId
            });
        }

        contributionsDAO.update(userId, preTax, afterTax, roth, function(err, contributions) {

            if (err) return next(err);

            contributions.updateSuccess = true;
            return res.render("contributions", contributions);
        });

    };

}

module.exports = ContributionsHandler;
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/firebug",
    "firebug/lib/domplate",
    "firebug/lib/events",
    "firebug/lib/dom",
    "firebug/lib/css",
    "firebug/console/autoCompleter",    // Firebug.JSEditor
],
function(Firebug, Domplate, Events, Dom, Css) {
with (Domplate) {

// ********************************************************************************************* //
// DOM Inline Editor

function DOMEditor(doc)
{
    this.box = this.tag.replace({}, doc, this);
    this.input = this.box.childNodes[1];

    var completionBox = this.box.childNodes[0];
    var options = {
        includeCurrentScope: true
    };

    this.setupCompleter(completionBox, options);
}

DOMEditor.prototype = domplate(Firebug.JSEditor.prototype,
{
    tag:
        DIV({style: "position: absolute;"},
            INPUT({"class": "fixedWidthEditor completionBox", type: "text",
                tabindex: "-1"}),
            INPUT({"class": "fixedWidthEditor completionInput", type: "text",
                oninput: "$onInput", onkeypress: "$onKeyPress"})),

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    endEditing: function(target, value, cancel)
    {
        // XXXjoe Kind of hackish - fix me
        delete this.panel.context.thisValue;

        if (cancel || value === "")
            return;

        var row = Dom.getAncestorByClass(target, "memberRow");

        Events.dispatch(this.panel.fbListeners, "onWatchEndEditing", [this.panel]);

        if (!row)
            this.panel.addWatch(value);
        else if (Css.hasClass(row, "watchRow"))
            this.panel.setWatchValue(row, value);
        else
            this.panel.setPropertyValue(row, value);
    }
});

// ********************************************************************************************* //
// Registration

return DOMEditor;

// ********************************************************************************************* //
}});
<commit_msg>Remove with Domplate + use strict<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/firebug",
    "firebug/lib/domplate",
    "firebug/lib/events",
    "firebug/lib/dom",
    "firebug/lib/css",
    "firebug/console/autoCompleter",    // Firebug.JSEditor
],
function(Firebug, Domplate, Events, Dom, Css) {

"use strict";

// ********************************************************************************************* //
// Constants

var {domplate, DIV, INPUT} = Domplate;

// ********************************************************************************************* //
// DOM Inline Editor

function DOMEditor(doc)
{
    this.box = this.tag.replace({}, doc, this);
    this.input = this.box.childNodes[1];

    var completionBox = this.box.childNodes[0];
    var options = {
        includeCurrentScope: true
    };

    this.setupCompleter(completionBox, options);
}

DOMEditor.prototype = domplate(Firebug.JSEditor.prototype,
{
    tag:
        DIV({style: "position: absolute;"},
            INPUT({"class": "fixedWidthEditor completionBox", type: "text",
                tabindex: "-1"}),
            INPUT({"class": "fixedWidthEditor completionInput", type: "text",
                oninput: "$onInput", onkeypress: "$onKeyPress"})),

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    endEditing: function(target, value, cancel)
    {
        // XXXjoe Kind of hackish - fix me
        delete this.panel.context.thisValue;

        if (cancel || value === "")
            return;

        var row = Dom.getAncestorByClass(target, "memberRow");

        Events.dispatch(this.panel.fbListeners, "onWatchEndEditing", [this.panel]);

        if (!row)
            this.panel.addWatch(value);
        else if (Css.hasClass(row, "watchRow"))
            this.panel.setWatchValue(row, value);
        else
            this.panel.setPropertyValue(row, value);
    }
});

// ********************************************************************************************* //
// Registration

return DOMEditor;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>import {extent} from "d3-array";
import {nest} from "d3-collection";
import {interpolatePath} from "d3-interpolate-path";
import {select} from "d3-selection";
import * as paths from "d3-shape";
import {transition} from "d3-transition";

import {accessor, constant} from "d3plus-common";
import {strip} from "d3plus-text";

import {default as Shape} from "./Shape";

/**
    @class Area
    @extends Shape
    @desc Creates SVG areas based on an array of data.
*/
export default class Area extends Shape {

  constructor() {

    super();

    this._curve = "linear";
    this._x = accessor("x");
    this._x0 = accessor("x");
    this._x1 = constant(null);
    this._y = constant(0);
    this._y0 = constant(0);
    this._y1 = accessor("y");

    this._path = paths.area()
      .defined(d => d)
      .x(this._x)
      .y0(this._y0)
      .y1(this._y1);

    this._pathExit = paths.area()
      .defined(d => d)
      .x(this._x)
      .y0(this._y0)
      .y1(this._y0);

  }

  /**
      Draws the lines.
      @param {Function} [*callback* = undefined]
      @private
  */
  render(callback) {

    super.render(callback);

    const that = this;

    const areas = nest().key(this._id).entries(this._data).map(d => {
      const x = extent(d.values.map(this._x)
        .concat(d.values.map(this._x0))
        .concat(d.values.map(this._x1))
      );
      d.xR = x;
      d.width = x[1] - x[0];
      d.x = x[0] + d.width / 2;
      const y = extent(d.values.map(this._y)
        .concat(d.values.map(this._y0))
        .concat(d.values.map(this._y1))
      );
      d.yR = y;
      d.height = y[1] - y[0];
      d.y = y[0] + d.height / 2;
      d.nested = true;
      return d;
    });

    this._path.curve(paths[`curve${this._curve.charAt(0).toUpperCase()}${this._curve.slice(1)}`]);

    const groups = this._select.selectAll(".d3plus-Area").data(areas, d => d.key);

    groups.transition(this._transition)
      .attr("transform", d => `translate(${d.x}, ${d.y})`);

    groups.select("path").transition(this._transition)
      .attr("transform", d => `translate(${-d.xR[0] - d.width / 2}, ${-d.yR[0] - d.height / 2})`)
      .attrTween("d", function(d) {
        return interpolatePath(select(this).attr("d"), that._path(d.values));
      })
      .call(this._applyStyle.bind(this));

    groups.exit().select("path").transition(this._transition)
      .attrTween("d", function(d) {
        return interpolatePath(select(this).attr("d"), that._pathExit(d.values));
      });

    groups.exit().transition().delay(this._duration).remove();

    groups.exit().call(this._applyLabels.bind(this), false);

    const enter = groups.enter().append("g")
        .attr("class", d => `d3plus-Shape d3plus-Area d3plus-id-${strip(d.key)}`)
        .attr("transform", d => `translate(${d.x}, ${d.y})`)
        .attr("opacity", 0);

    enter.append("path")
      .attr("transform", d => `translate(${-d.xR[0] - d.width / 2}, ${-d.yR[0] - d.height / 2})`)
      .attr("d", d => this._path(d.values))
      .call(this._applyStyle.bind(this));

    const update = enter.merge(groups);

    update.call(this._applyLabels.bind(this))
        .attr("pointer-events", "none")
      .transition(this._transition)
        .attr("opacity", this._opacity)
      .transition()
        .attr("pointer-events", "all");

    this._applyEvents(update);

    return this;

  }

  /**
      @memberof Area
      @desc Given a specific data point and index, returns the aesthetic properties of the shape.
      @param {Object} *data point*
      @param {Number} *index*
      @private
  */
  _aes(d, i) {
    return {points: d.values.map(p => [this._x(p, i), this._y(p, i)])};
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the line curve to the specified string and returns the current class instance. If *value* is not specified, returns the current line curve. The number returned should correspond to the horizontal center of the rectangle.
      @param {String} [*value* = "linear"]
  */
  curve(_) {
    return arguments.length ? (this._curve = _, this) : this._curve;
  }

  /**
      @memberof Area
      @desc Updates the style and positioning of the elements matching *selector* and returns the current class instance. This is helpful when not wanting to loop through all shapes just to change the style of a few.
      @param {String|HTMLElement} *selector*
  */
  update(_) {

    const groups = this._select.selectAll(_),
          t = transition().duration(this._duration);

    groups
        .call(this._applyLabels.bind(this))
      .transition(t)
        .attr("opacity", this._opacity);

    groups.select("path").transition(t)
      .attr("d", d => this._path(d.values));

    return this;

  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x accessor.
      @param {Function|Number} [*value*]
      @example
function(d) {
  return d.x;
}
  */
  x(_) {
    if (arguments.length) {
      this._x = typeof _ === "function" ? _ : constant(_);
      this._path.x(this._x);
      this._pathExit.x(this._x);
      return this;
    }
    return this._x;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x0 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x0 accessor.
      @param {Function|Number} [*value*]
  */
  x0(_) {
    if (arguments.length) {
      this._x0 = typeof _ === "function" ? _ : constant(_);
      this._path.x0(this._x0);
      this._pathExit.x0(this._x0);
      this._pathExit.x1(this._x0);
      return this;
    }
    return this._x0;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x1 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x1 accessor.
      @param {Function|Number} [*value*]
  */
  x1(_) {
    if (arguments.length) {
      this._x1 = typeof _ === "function" ? _ : constant(_);
      this._path.x1(this._x1);
      return this;
    }
    return this._x1;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y accessor.
      @param {Function|Number} [*value*]
      @example
function(d) {
  return d.y;
}
  */
  y(_) {
    if (arguments.length) {
      this._y = typeof _ === "function" ? _ : constant(_);
      this._path.y(this._y);
      this._pathExit.y(this._y);
      return this;
    }
    return this._y;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y0 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y0 accessor.
      @param {Function|Number} [*value*]
  */
  y0(_) {
    if (arguments.length) {
      this._y0 = typeof _ === "function" ? _ : constant(_);
      this._path.y0(this._y0);
      this._pathExit.y0(this._y0);
      this._pathExit.y1(this._y0);
      return this;
    }
    return this._y0;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y1 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y1 accessor.
      @param {Function|Number} [*value*]
  */
  y1(_) {
    if (arguments.length) {
      this._y1 = typeof _ === "function" ? _ : constant(_);
      this._path.y1(this._y1);
      return this;
    }
    return this._y1;
  }

}
<commit_msg>cleans up Area path x/y setting behavior<commit_after>import {extent} from "d3-array";
import {nest} from "d3-collection";
import {interpolatePath} from "d3-interpolate-path";
import {select} from "d3-selection";
import * as paths from "d3-shape";
import {transition} from "d3-transition";

import {accessor, constant} from "d3plus-common";
import {strip} from "d3plus-text";

import {default as Shape} from "./Shape";

/**
    @class Area
    @extends Shape
    @desc Creates SVG areas based on an array of data.
*/
export default class Area extends Shape {

  constructor() {

    super();

    this._curve = "linear";
    this._x = accessor("x");
    this._x0 = accessor("x");
    this._x1 = null;
    this._y = constant(0);
    this._y0 = constant(0);
    this._y1 = accessor("y");

  }

  /**
      Draws the lines.
      @param {Function} [*callback* = undefined]
      @private
  */
  render(callback) {

    super.render(callback);

    const path = this._path = paths.area()
      .defined(d => d)
      .curve(paths[`curve${this._curve.charAt(0).toUpperCase()}${this._curve.slice(1)}`])
      .x(this._x)
      .x0(this._x0)
      .x1(this._x1)
      .y(this._y)
      .y0(this._y0)
      .y1(this._y1);

    const exitPath = paths.area()
      .defined(d => d)
      .curve(paths[`curve${this._curve.charAt(0).toUpperCase()}${this._curve.slice(1)}`])
      .x(this._x)
      .x0(this._x0)
      .x1(this._x1)
      .y(this._y)
      .y0(this._y0)
      .y1(this._y1);

    const areas = nest().key(this._id).entries(this._data).map(d => {
      const x = extent(d.values.map(this._x)
        .concat(d.values.map(this._x0))
        .concat(this._x1 ? d.values.map(this._x1) : [])
      );
      d.xR = x;
      d.width = x[1] - x[0];
      d.x = x[0] + d.width / 2;
      const y = extent(d.values.map(this._y)
        .concat(d.values.map(this._y0))
        .concat(this._y1 ? d.values.map(this._y1) : [])
      );
      d.yR = y;
      d.height = y[1] - y[0];
      d.y = y[0] + d.height / 2;
      d.nested = true;
      return d;
    });

    const groups = this._select.selectAll(".d3plus-Area").data(areas, d => d.key);

    groups.transition(this._transition)
      .attr("transform", d => `translate(${d.x}, ${d.y})`);

    groups.select("path").transition(this._transition)
      .attr("transform", d => `translate(${-d.xR[0] - d.width / 2}, ${-d.yR[0] - d.height / 2})`)
      .attrTween("d", function(d) {
        return interpolatePath(select(this).attr("d"), path(d.values));
      })
      .call(this._applyStyle.bind(this));

    groups.exit().select("path").transition(this._transition)
      .attrTween("d", function(d) {
        return interpolatePath(select(this).attr("d"), exitPath(d.values));
      });

    groups.exit().transition().delay(this._duration).remove();

    groups.exit().call(this._applyLabels.bind(this), false);

    const enter = groups.enter().append("g")
        .attr("class", d => `d3plus-Shape d3plus-Area d3plus-id-${strip(d.key)}`)
        .attr("transform", d => `translate(${d.x}, ${d.y})`)
        .attr("opacity", 0);

    enter.append("path")
      .attr("transform", d => `translate(${-d.xR[0] - d.width / 2}, ${-d.yR[0] - d.height / 2})`)
      .attr("d", d => path(d.values))
      .call(this._applyStyle.bind(this));

    const update = enter.merge(groups);

    update.call(this._applyLabels.bind(this))
        .attr("pointer-events", "none")
      .transition(this._transition)
        .attr("opacity", this._opacity)
      .transition()
        .attr("pointer-events", "all");

    this._applyEvents(update);

    return this;

  }

  /**
      @memberof Area
      @desc Given a specific data point and index, returns the aesthetic properties of the shape.
      @param {Object} *data point*
      @param {Number} *index*
      @private
  */
  _aes(d, i) {
    return {points: d.values.map(p => [this._x(p, i), this._y(p, i)])};
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the line curve to the specified string and returns the current class instance. If *value* is not specified, returns the current line curve. The number returned should correspond to the horizontal center of the rectangle.
      @param {String} [*value* = "linear"]
  */
  curve(_) {
    return arguments.length ? (this._curve = _, this) : this._curve;
  }

  /**
      @memberof Area
      @desc Updates the style and positioning of the elements matching *selector* and returns the current class instance. This is helpful when not wanting to loop through all shapes just to change the style of a few.
      @param {String|HTMLElement} *selector*
  */
  update(_) {

    const groups = this._select.selectAll(_),
          t = transition().duration(this._duration);

    groups
        .call(this._applyLabels.bind(this))
      .transition(t)
        .attr("opacity", this._opacity);

    groups.select("path").transition(t)
      .attr("d", d => this._path(d.values));

    return this;

  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x accessor.
      @param {Function|Number} [*value*]
      @example
function(d) {
  return d.x;
}
  */
  x(_) {
    return arguments.length ? (this._x = _, this) : this._x;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x0 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x0 accessor.
      @param {Function|Number} [*value*]
  */
  x0(_) {
    return arguments.length ? (this._x0 = _, this) : this._x0;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the x1 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current x1 accessor.
      @param {Function|Number} [*value*]
  */
  x1(_) {
    return arguments.length ? (this._x1 = _, this) : this._x1;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y accessor.
      @param {Function|Number} [*value*]
      @example
function(d) {
  return d.y;
}
  */
  y(_) {
    return arguments.length ? (this._y = _, this) : this._y;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y0 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y0 accessor.
      @param {Function|Number} [*value*]
  */
  y0(_) {
    return arguments.length ? (this._y0 = _, this) : this._y0;
  }

  /**
      @memberof Area
      @desc If *value* is specified, sets the y1 accessor to the specified function or number and returns the current class instance. If *value* is not specified, returns the current y1 accessor.
      @param {Function|Number} [*value*]
  */
  y1(_) {
    return arguments.length ? (this._y1 = _, this) : this._y1;
  }

}
<|endoftext|>


<commit_before>import React from "react";
import Helmet from "react-helmet";
import Link from "gatsby-link";
import css from "./index.module.css";

const H1 = ({children}) =>
{children}
;

const H2 = ({children}) =>
{children}
;

const Defn = ({children}) =>
{children}
;

const Term = ({children}) =>
{children}
;

const mlWebapp = (

    machine learning webapp

);

const cvPosterSim = (

    computer vision poster simulator

);

const frontendDev = (
  frontend development
);

const InfoA = ({children, href, print}) => (

      {children}

);

const InfoLink = ({children, to, print}) => (

    <Link className={css.Print} data-print={print} to={to}>
      {children}
    </Link>

);

export default ({data: {site}}) => (

    <Helmet title={`Resume - ${site.siteMetadata.title}`} />

Ariel Davis

      <InfoA
        href="mailto:ariel.z.davis@icloud.com"
        print="ariel.z.davis@icloud.com"
      >
        Email
      </InfoA>
      <InfoA print="1-908-514-1006" href="tel:1-908-514-1006">
        Phone
      </InfoA>
      <InfoLink print="azdavis.xyz" to="/">
        Website
      </InfoLink>
      <InfoA print="github.com/azdavis" href="https://github.com/azdavis">
        GitHub
      </InfoA>

Education

    <Term>May 2020</Term>
    <Defn>

Carnegie Mellon University - Pittsburgh, PA

B.S in Computer Science, Minor in Japanese Studies

GPA ~3.9

    </Defn>
    <Term>June 2016</Term>
    <Defn>

Summit High School - Summit, NJ

Summa Cum Laude

    </Defn>

Selected Coursework

    <Term>Spring 2018</Term>
    <Defn>

15-210: Parallel and Sequential Data Structures and Algorithms

15-418: Parallel Computer Architecture and Programming

82-272: Intermediate Japanese II

    </Defn>
    <Term>Fall 2017</Term>
    <Defn>

15-213: Introduction to Computer Systems

82-271: Intermediate Japanese I

82-273: Introduction to Japanese Language and Culture

    </Defn>
    <Term>Summer 2017</Term>
    <Defn>82-172: Elementary Japanese II</Defn>
    <Term>Spring 2017</Term>
    <Defn>

15-251: Great Theoretical Ideas in Computer Science

82-171: Elementary Japanese I

    </Defn>
    <Term>Fall 2016</Term>
    <Defn>

15-131: Great Practical Ideas in Computer Science

15-150: Principles of Functional Programming

    </Defn>
    <Term>Summer 2015</Term>
    <Defn>

15-122: Principles of Imperative Computation

21-127: Concepts of Mathematics

    </Defn>

Activities

    <Term>Summer 2018</Term>
    <Defn>Internship: Stripe</Defn>
    <Term>Spring 2018</Term>
    <Defn>TA: 15-150</Defn>
    <Term>Fall 2017</Term>
    <Defn>TA: 15-131, 15-150</Defn>
    <Term>Summer 2017</Term>
    <Defn>TA: 15-150</Defn>
    <Term>Spring 2017</Term>
    <Defn>TartanHacks: helped to create a {mlWebapp}</Defn>
    <Term>Fall 2016</Term>
    <Defn>

HackCMU: helped to create a {cvPosterSim}

ScottyLabs: gave a talk on basic {frontendDev}

    </Defn>
    <Term>Summer 2015</Term>
    <Defn>
      Carnegie Mellon University Pre-College: took compressed-form CMU classes
    </Defn>
    <Term>Summer 2014</Term>
    <Defn>
      Northwestern University Center for Talent Development: learned HTML, CSS
    </Defn>

Skills

    <Term>Languages</Term>
    <Defn>JavaScript, Standard ML, Rust, Ruby, C</Defn>
    <Term>Markup</Term>
    <Defn>HTML, CSS, LaTeX, Markdown</Defn>
    <Term>Tools</Term>
    <Defn>Git, GitHub, Make, Shell, POSIX</Defn>

);

export const pageQuery = graphql`
  query Resume {
    site {
      siteMetadata {
        title
      }
    }
  }
`;
<commit_msg>Update courses<commit_after>import React from "react";
import Helmet from "react-helmet";
import Link from "gatsby-link";
import css from "./index.module.css";

const H1 = ({children}) =>
{children}
;

const H2 = ({children}) =>
{children}
;

const Defn = ({children}) =>
{children}
;

const Term = ({children}) =>
{children}
;

const mlWebapp = (

    machine learning webapp

);

const cvPosterSim = (

    computer vision poster simulator

);

const frontendDev = (
  frontend development
);

const InfoA = ({children, href, print}) => (

      {children}

);

const InfoLink = ({children, to, print}) => (

    <Link className={css.Print} data-print={print} to={to}>
      {children}
    </Link>

);

export default ({data: {site}}) => (

    <Helmet title={`Resume - ${site.siteMetadata.title}`} />

Ariel Davis

      <InfoA
        href="mailto:ariel.z.davis@icloud.com"
        print="ariel.z.davis@icloud.com"
      >
        Email
      </InfoA>
      <InfoA print="1-908-514-1006" href="tel:1-908-514-1006">
        Phone
      </InfoA>
      <InfoLink print="azdavis.xyz" to="/">
        Website
      </InfoLink>
      <InfoA print="github.com/azdavis" href="https://github.com/azdavis">
        GitHub
      </InfoA>

Education

    <Term>May 2020</Term>
    <Defn>

Carnegie Mellon University - Pittsburgh, PA

B.S in Computer Science, Minor in Japanese Studies

GPA ~3.9

    </Defn>
    <Term>June 2016</Term>
    <Defn>

Summit High School - Summit, NJ

Summa Cum Laude

    </Defn>

Selected Coursework

    <Term>Fall 2018</Term>
    <Defn>

15-312: Foundations of Programming Languages

15-440: Distributed Systems

82-371: Advanced Japanese I

82-373: Structure of the Japanese Language

    </Defn>
    <Term>Spring 2018</Term>
    <Defn>

15-210: Parallel and Sequential Data Structures and Algorithms

15-418: Parallel Computer Architecture and Programming

82-272: Intermediate Japanese II

    </Defn>
    <Term>Fall 2017</Term>
    <Defn>

15-213: Introduction to Computer Systems

82-271: Intermediate Japanese I

82-273: Introduction to Japanese Language and Culture

    </Defn>

Activities

    <Term>Summer 2018</Term>
    <Defn>Internship: Stripe</Defn>
    <Term>Spring 2018</Term>
    <Defn>TA: 15-150</Defn>
    <Term>Fall 2017</Term>
    <Defn>TA: 15-131, 15-150</Defn>
    <Term>Summer 2017</Term>
    <Defn>TA: 15-150</Defn>
    <Term>Spring 2017</Term>
    <Defn>TartanHacks: helped to create a {mlWebapp}</Defn>
    <Term>Fall 2016</Term>
    <Defn>

HackCMU: helped to create a {cvPosterSim}

ScottyLabs: gave a talk on basic {frontendDev}

    </Defn>
    <Term>Summer 2015</Term>
    <Defn>
      Carnegie Mellon University Pre-College: took compressed-form CMU classes
    </Defn>
    <Term>Summer 2014</Term>
    <Defn>
      Northwestern University Center for Talent Development: learned HTML, CSS
    </Defn>

Skills

    <Term>Languages</Term>
    <Defn>JavaScript, Standard ML, Rust, Ruby, C</Defn>
    <Term>Markup</Term>
    <Defn>HTML, CSS, LaTeX, Markdown</Defn>
    <Term>Tools</Term>
    <Defn>Git, GitHub, Make, Shell, POSIX</Defn>

);

export const pageQuery = graphql`
  query Resume {
    site {
      siteMetadata {
        title
      }
    }
  }
`;
<|endoftext|>


<commit_before>import flyd, {on,stream} from 'flyd';
import timeTravelPlugin from './time-travel-plugin/';
import {Map as IMap} from 'immutable';
import {sub} from 'elegant-react';

window.stream = stream;

export default class Atoam {
  constructor(state) {
    this.wiredUpdateStreams = IMap({});
    this.state = state;

    // directly-updated state, used to update "watcher" App component
    this.didSetState$ = stream();

    // used to indicate "user" update
    this.didUpdateState$ = stream(state);

    // used to update state of the atom via stream pushes
    // ie., pushes to this._update$ will NOT trigger
    //      the this.didUpdateState$ stream
    this._update$ = stream();
    flyd.on(::this._updateState, this._update$);
  }

  _setState(state) {
    return this.didSetState$(this.state = state).val;
  }

  _updateState(transform) {
    return this._setState(this.state.update(transform));
  }

  getState() {
    return this.state;
  }

  updateState(transform) {
    return this.didUpdateState$(this._updateState(transform)).val;
  }

  // returns a stream into which you can push
  // transform functions (data -> data)
  wiredUpdateStream(...path) {
    // todo: watch for stream end and remove the stream from the array
    let s = this.wiredUpdateStreams.getIn(path);
    if (!s) this.wiredUpdateStreams.setIn(path, s = stream());
    else return s;

    on(sub(::this.updateState, ...path), s);
    return s;
  }
}
<commit_msg>commentgst<commit_after>import flyd, {on,stream} from 'flyd';
import timeTravelPlugin from './time-travel-plugin/';
import {Map as IMap} from 'immutable';
import {sub} from 'elegant-react';

window.stream = stream;

export default class Atoam {
  constructor(state) {
    this.wiredUpdateStreams = IMap({});
    this.state = state;

    // directly-updated state, used to update "watcher" App component
    this.didSetState$ = stream();

    // used to indicate "user" update
    this.didUpdateState$ = stream(state);

    // used to update state of the atom via stream pushes
    // ie., pushes to this._update$ will NOT trigger
    //      the this.didUpdateState$ stream
    this._update$ = stream();
    flyd.on(::this._updateState, this._update$);
  }

  _setState(state) {
    return this.didSetState$(this.state = state).val;
  }

  _updateState(transform) {
    return this._setState(this.state.update(transform));
  }

  getState() {
    return this.state;
  }

  updateState(transform) {
    return this.didUpdateState$(this._updateState(transform)).val;
  }

  // returns a stream into which you can push
  // transform functions (data -> data)
  //
  // Todo: I'm not sure if this is really useful because a
  //       subedit function could be used instead
  wiredUpdateStream(...path) {
    // todo: watch for stream end and remove the stream from the array
    let s = this.wiredUpdateStreams.getIn(path);
    if (!s) this.wiredUpdateStreams.setIn(path, s = stream());
    else return s;

    on(sub(::this.updateState, ...path), s);
    return s;
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');

let React;
let ReactDOM;
let ReactDOMServer;

function initModules() {
  // Reset warning cache.
  jest.resetModuleRegistry();
  React = require('react');
  ReactDOM = require('react-dom');
  ReactDOMServer = require('react-dom/server');

  // Make them available to the helpers.
  return {
    ReactDOM,
    ReactDOMServer,
  };
}

const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules);

describe('ReactDOMServerIntegration', () => {
  beforeEach(() => {
    resetModules();
  });

  describe('context', function() {
    let PurpleContext, RedContext, Consumer;
    beforeEach(() => {
      let Context = React.createContext('none');

      class Parent extends React.Component {
        render() {
          return (
            <Context.Provider value={this.props.text}>
              {this.props.children}
            </Context.Provider>
          );
        }
      }
      Consumer = Context.Consumer;
      PurpleContext = props => <Parent text="purple">{props.children}</Parent>;
      RedContext = props => <Parent text="red">{props.children}</Parent>;
    });

    itRenders('class child with context', async render => {
      class ClassChildWithContext extends React.Component {
        render() {
          return (

              <Consumer>{text => text}</Consumer>

          );
        }
      }

      const e = await render(
        <PurpleContext>
          <ClassChildWithContext />
        </PurpleContext>,
      );
      expect(e.textContent).toBe('purple');
    });

    itRenders('stateless child with context', async render => {
      function FunctionChildWithContext(props) {
        return <Consumer>{text => text}</Consumer>;
      }

      const e = await render(
        <PurpleContext>
          <FunctionChildWithContext />
        </PurpleContext>,
      );
      expect(e.textContent).toBe('purple');
    });

    itRenders('class child with default context', async render => {
      class ClassChildWithWrongContext extends React.Component {
        render() {
          return (

              <Consumer>{text => text}</Consumer>

          );
        }
      }

      const e = await render(<ClassChildWithWrongContext />);
      expect(e.textContent).toBe('none');
    });

    itRenders('stateless child with wrong context', async render => {
      function FunctionChildWithWrongContext(props) {
        return (

            <Consumer>{text => text}</Consumer>

        );
      }

      const e = await render(<FunctionChildWithWrongContext />);
      expect(e.textContent).toBe('none');
    });

    itRenders('with context passed through to a grandchild', async render => {
      function Grandchild(props) {
        return (

            <Consumer>{text => text}</Consumer>

        );
      }

      const Child = props => <Grandchild />;

      const e = await render(
        <PurpleContext>
          <Child />
        </PurpleContext>,
      );
      expect(e.textContent).toBe('purple');
    });

    itRenders('a child context overriding a parent context', async render => {
      const Grandchild = props => {
        return (

            <Consumer>{text => text}</Consumer>

        );
      };

      const e = await render(
        <PurpleContext>
          <RedContext>
            <Grandchild />
          </RedContext>
        </PurpleContext>,
      );
      expect(e.textContent).toBe('red');
    });

    itRenders('multiple contexts', async render => {
      const Theme = React.createContext('dark');
      const Language = React.createContext('french');
      class Parent extends React.Component {
        render() {
          return (
            <Theme.Provider value="light">
              <Child />
            </Theme.Provider>
          );
        }
      }

      function Child() {
        return (
          <Language.Provider value="english">
            <Grandchild />
          </Language.Provider>
        );
      }

      const Grandchild = props => {
        return (

            <Theme.Consumer>
              {theme =>
{theme}
}
            </Theme.Consumer>
            <Language.Consumer>
              {language =>
{language}
}
            </Language.Consumer>

        );
      };

      const e = await render(<Parent />);
      expect(e.querySelector('#theme').textContent).toBe('light');
      expect(e.querySelector('#language').textContent).toBe('english');
    });

    itRenders('nested context unwinding', async render => {
      const Theme = React.createContext('dark');
      const Language = React.createContext('french');

      const App = () => (

          <Theme.Provider value="light">
            <Language.Provider value="english">
              <Theme.Provider value="dark">
                <Theme.Consumer>
                  {theme =>
{theme}
}
                </Theme.Consumer>
              </Theme.Provider>
              <Theme.Consumer>
                {theme =>
{theme}
}
              </Theme.Consumer>
              <Language.Provider value="sanskrit">
                <Theme.Provider value="blue">
                  <Theme.Provider value="red">
                    <Language.Consumer>
                      {() => (
                        <Language.Provider value="chinese">
                          <Language.Provider value="hungarian" />
                          <Language.Consumer>
                            {language =>
{language}
}
                          </Language.Consumer>
                        </Language.Provider>
                      )}
                    </Language.Consumer>
                  </Theme.Provider>
                  <Language.Consumer>
                    {language => (
                      <React.Fragment>
                        <Theme.Consumer>
                          {theme =>
{theme}
}
                        </Theme.Consumer>

{language}

                      </React.Fragment>
                    )}
                  </Language.Consumer>
                </Theme.Provider>
              </Language.Provider>
            </Language.Provider>
          </Theme.Provider>
          <Language.Consumer>
            {language =>
{language}
}
          </Language.Consumer>

      );
      let e = await render(<App />);
      expect(e.querySelector('#theme1').textContent).toBe('dark');
      expect(e.querySelector('#theme2').textContent).toBe('light');
      expect(e.querySelector('#theme3').textContent).toBe('blue');
      expect(e.querySelector('#language1').textContent).toBe('chinese');
      expect(e.querySelector('#language2').textContent).toBe('sanskrit');
      expect(e.querySelector('#language3').textContent).toBe('french');
    });

    itRenders(
      'should warn with an error message when using Context as consumer in DEV',
      async render => {
        const Theme = React.createContext('dark');
        const Language = React.createContext('french');

        const App = () => (

            <Theme.Provider value="light">
              <Language.Provider value="english">
                <Theme.Provider value="dark">
                  <Theme>{theme =>
{theme}
}</Theme>
                </Theme.Provider>
              </Language.Provider>
            </Theme.Provider>

        );
        // We expect 1 error.
        await render(<App />, 1);
      },
    );

    // False positive regression test.
    itRenders(
      'should not warn when using Consumer from React < 16.6 with newer renderer',
      async render => {
        const Theme = React.createContext('dark');
        const Language = React.createContext('french');
        // React 16.5 and earlier didn't have a separate object.
        Theme.Consumer = Theme;

        const App = () => (

            <Theme.Provider value="light">
              <Language.Provider value="english">
                <Theme.Provider value="dark">
                  <Theme>{theme =>
{theme}
}</Theme>
                </Theme.Provider>
              </Language.Provider>
            </Theme.Provider>

        );
        // We expect 0 errors.
        await render(<App />, 0);
      },
    );

    itRenders(
      'should warn with an error message when using nested context consumers in DEV',
      async render => {
        const App = () => {
          const Theme = React.createContext('dark');
          const Language = React.createContext('french');

          return (

              <Theme.Provider value="light">
                <Language.Provider value="english">
                  <Theme.Provider value="dark">
                    <Theme.Consumer.Consumer>
                      {theme =>
{theme}
}
                    </Theme.Consumer.Consumer>
                  </Theme.Provider>
                </Language.Provider>
              </Theme.Provider>

          );
        };
        // We expect 1 error.
        await render(<App />, 1);
      },
    );

    itRenders(
      'should warn with an error message when using Context.Consumer.Provider DEV',
      async render => {
        const App = () => {
          const Theme = React.createContext('dark');
          const Language = React.createContext('french');

          return (

              <Theme.Provider value="light">
                <Language.Provider value="english">
                  <Theme.Consumer.Provider value="dark">
                    <Theme.Consumer>
                      {theme =>
{theme}
}
                    </Theme.Consumer>
                  </Theme.Consumer.Provider>
                </Language.Provider>
              </Theme.Provider>

          );
        };
        // We expect 1 error.
        await render(<App />, 1);
      },
    );

    it('does not pollute parallel node streams', () => {
      const LoggedInUser = React.createContext();

      const AppWithUser = user => (
        <LoggedInUser.Provider value={user}>

            <LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer>

            <LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer>

        </LoggedInUser.Provider>
      );

      const streamAmy = ReactDOMServer.renderToNodeStream(
        AppWithUser('Amy'),
      ).setEncoding('utf8');
      const streamBob = ReactDOMServer.renderToNodeStream(
        AppWithUser('Bob'),
      ).setEncoding('utf8');

      // Testing by filling the buffer using internal _read() with a small
      // number of bytes to avoid a test case which needs to align to a
      // highWaterMark boundary of 2^14 chars.
      streamAmy._read(20);
      streamBob._read(20);
      streamAmy._read(20);
      streamBob._read(20);

      expect(streamAmy.read()).toBe('AmyAmy');
      expect(streamBob.read()).toBe('BobBob');
    });

    it('does not pollute parallel node streams when many are used', () => {
      const CurrentIndex = React.createContext();

      const NthRender = index => (
        <CurrentIndex.Provider value={index}>

            <CurrentIndex.Consumer>{idx => idx}</CurrentIndex.Consumer>

            <CurrentIndex.Consumer>{idx => idx}</CurrentIndex.Consumer>

        </CurrentIndex.Provider>
      );

      let streams = [];

      // Test with more than 32 streams to test that growing the thread count
      // works properly.
      let streamCount = 34;

      for (let i = 0; i < streamCount; i++) {
        streams[i] = ReactDOMServer.renderToNodeStream(
          NthRender(i % 2 === 0 ? 'Expected to be recreated' : i),
        ).setEncoding('utf8');
      }

      // Testing by filling the buffer using internal _read() with a small
      // number of bytes to avoid a test case which needs to align to a
      // highWaterMark boundary of 2^14 chars.
      for (let i = 0; i < streamCount; i++) {
        streams[i]._read(20);
      }

      // Early destroy every other stream
      for (let i = 0; i < streamCount; i += 2) {
        streams[i].destroy();
      }

      // Recreate those same streams.
      for (let i = 0; i < streamCount; i += 2) {
        streams[i] = ReactDOMServer.renderToNodeStream(
          NthRender(i),
        ).setEncoding('utf8');
      }

      // Read a bit from all streams again.
      for (let i = 0; i < streamCount; i++) {
        streams[i]._read(20);
      }

      // Assert that all stream rendered the expected output.
      for (let i = 0; i < streamCount; i++) {
        expect(streams[i].read()).toBe(
          '' + i + '' + i + '',
        );
      }
    });
  });
});
<commit_msg>Add test coverage for readContext() on the server (#14649)<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 */

'use strict';

const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');

let React;
let ReactDOM;
let ReactDOMServer;

function initModules() {
  // Reset warning cache.
  jest.resetModuleRegistry();
  React = require('react');
  ReactDOM = require('react-dom');
  ReactDOMServer = require('react-dom/server');

  // Make them available to the helpers.
  return {
    ReactDOM,
    ReactDOMServer,
  };
}

const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules);

describe('ReactDOMServerIntegration', () => {
  beforeEach(() => {
    resetModules();
  });

  describe('context', function() {
    let Context, PurpleContextProvider, RedContextProvider, Consumer;
    beforeEach(() => {
      Context = React.createContext('none');

      class Parent extends React.Component {
        render() {
          return (
            <Context.Provider value={this.props.text}>
              {this.props.children}
            </Context.Provider>
          );
        }
      }
      Consumer = Context.Consumer;
      PurpleContextProvider = props => (
        <Parent text="purple">{props.children}</Parent>
      );
      RedContextProvider = props => (
        <Parent text="red">{props.children}</Parent>
      );
    });

    itRenders('class child with context', async render => {
      class ClassChildWithContext extends React.Component {
        render() {
          return (

              <Consumer>{text => text}</Consumer>

          );
        }
      }

      const e = await render(
        <PurpleContextProvider>
          <ClassChildWithContext />
        </PurpleContextProvider>,
      );
      expect(e.textContent).toBe('purple');
    });

    itRenders('stateless child with context', async render => {
      function FunctionChildWithContext(props) {
        return <Consumer>{text => text}</Consumer>;
      }

      const e = await render(
        <PurpleContextProvider>
          <FunctionChildWithContext />
        </PurpleContextProvider>,
      );
      expect(e.textContent).toBe('purple');
    });

    itRenders('class child with default context', async render => {
      class ClassChildWithWrongContext extends React.Component {
        render() {
          return (

              <Consumer>{text => text}</Consumer>

          );
        }
      }

      const e = await render(<ClassChildWithWrongContext />);
      expect(e.textContent).toBe('none');
    });

    itRenders('stateless child with wrong context', async render => {
      function FunctionChildWithWrongContext(props) {
        return (

            <Consumer>{text => text}</Consumer>

        );
      }

      const e = await render(<FunctionChildWithWrongContext />);
      expect(e.textContent).toBe('none');
    });

    itRenders('with context passed through to a grandchild', async render => {
      function Grandchild(props) {
        return (

            <Consumer>{text => text}</Consumer>

        );
      }

      const Child = props => <Grandchild />;

      const e = await render(
        <PurpleContextProvider>
          <Child />
        </PurpleContextProvider>,
      );
      expect(e.textContent).toBe('purple');
    });

    itRenders('a child context overriding a parent context', async render => {
      const Grandchild = props => {
        return (

            <Consumer>{text => text}</Consumer>

        );
      };

      const e = await render(
        <PurpleContextProvider>
          <RedContextProvider>
            <Grandchild />
          </RedContextProvider>
        </PurpleContextProvider>,
      );
      expect(e.textContent).toBe('red');
    });

    itRenders('readContext() in different components', async render => {
      function readContext(Ctx, observedBits) {
        const dispatcher =
          React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
            .ReactCurrentDispatcher.current;
        return dispatcher.readContext(Ctx, observedBits);
      }

      class Cls extends React.Component {
        render() {
          return readContext(Context);
        }
      }
      function Fn() {
        return readContext(Context);
      }
      const Memo = React.memo(() => {
        return readContext(Context);
      });
      const FwdRef = React.forwardRef((props, ref) => {
        return readContext(Context);
      });

      const e = await render(
        <PurpleContextProvider>
          <RedContextProvider>

              <Fn />
              <Cls />
              <Memo />
              <FwdRef />
              <Consumer>{() => readContext(Context)}</Consumer>

          </RedContextProvider>
        </PurpleContextProvider>,
      );
      expect(e.textContent).toBe('redredredredred');
    });

    itRenders('multiple contexts', async render => {
      const Theme = React.createContext('dark');
      const Language = React.createContext('french');
      class Parent extends React.Component {
        render() {
          return (
            <Theme.Provider value="light">
              <Child />
            </Theme.Provider>
          );
        }
      }

      function Child() {
        return (
          <Language.Provider value="english">
            <Grandchild />
          </Language.Provider>
        );
      }

      const Grandchild = props => {
        return (

            <Theme.Consumer>
              {theme =>
{theme}
}
            </Theme.Consumer>
            <Language.Consumer>
              {language =>
{language}
}
            </Language.Consumer>

        );
      };

      const e = await render(<Parent />);
      expect(e.querySelector('#theme').textContent).toBe('light');
      expect(e.querySelector('#language').textContent).toBe('english');
    });

    itRenders('nested context unwinding', async render => {
      const Theme = React.createContext('dark');
      const Language = React.createContext('french');

      const App = () => (

          <Theme.Provider value="light">
            <Language.Provider value="english">
              <Theme.Provider value="dark">
                <Theme.Consumer>
                  {theme =>
{theme}
}
                </Theme.Consumer>
              </Theme.Provider>
              <Theme.Consumer>
                {theme =>
{theme}
}
              </Theme.Consumer>
              <Language.Provider value="sanskrit">
                <Theme.Provider value="blue">
                  <Theme.Provider value="red">
                    <Language.Consumer>
                      {() => (
                        <Language.Provider value="chinese">
                          <Language.Provider value="hungarian" />
                          <Language.Consumer>
                            {language =>
{language}
}
                          </Language.Consumer>
                        </Language.Provider>
                      )}
                    </Language.Consumer>
                  </Theme.Provider>
                  <Language.Consumer>
                    {language => (
                      <React.Fragment>
                        <Theme.Consumer>
                          {theme =>
{theme}
}
                        </Theme.Consumer>

{language}

                      </React.Fragment>
                    )}
                  </Language.Consumer>
                </Theme.Provider>
              </Language.Provider>
            </Language.Provider>
          </Theme.Provider>
          <Language.Consumer>
            {language =>
{language}
}
          </Language.Consumer>

      );
      let e = await render(<App />);
      expect(e.querySelector('#theme1').textContent).toBe('dark');
      expect(e.querySelector('#theme2').textContent).toBe('light');
      expect(e.querySelector('#theme3').textContent).toBe('blue');
      expect(e.querySelector('#language1').textContent).toBe('chinese');
      expect(e.querySelector('#language2').textContent).toBe('sanskrit');
      expect(e.querySelector('#language3').textContent).toBe('french');
    });

    itRenders(
      'should warn with an error message when using Context as consumer in DEV',
      async render => {
        const Theme = React.createContext('dark');
        const Language = React.createContext('french');

        const App = () => (

            <Theme.Provider value="light">
              <Language.Provider value="english">
                <Theme.Provider value="dark">
                  <Theme>{theme =>
{theme}
}</Theme>
                </Theme.Provider>
              </Language.Provider>
            </Theme.Provider>

        );
        // We expect 1 error.
        await render(<App />, 1);
      },
    );

    // False positive regression test.
    itRenders(
      'should not warn when using Consumer from React < 16.6 with newer renderer',
      async render => {
        const Theme = React.createContext('dark');
        const Language = React.createContext('french');
        // React 16.5 and earlier didn't have a separate object.
        Theme.Consumer = Theme;

        const App = () => (

            <Theme.Provider value="light">
              <Language.Provider value="english">
                <Theme.Provider value="dark">
                  <Theme>{theme =>
{theme}
}</Theme>
                </Theme.Provider>
              </Language.Provider>
            </Theme.Provider>

        );
        // We expect 0 errors.
        await render(<App />, 0);
      },
    );

    itRenders(
      'should warn with an error message when using nested context consumers in DEV',
      async render => {
        const App = () => {
          const Theme = React.createContext('dark');
          const Language = React.createContext('french');

          return (

              <Theme.Provider value="light">
                <Language.Provider value="english">
                  <Theme.Provider value="dark">
                    <Theme.Consumer.Consumer>
                      {theme =>
{theme}
}
                    </Theme.Consumer.Consumer>
                  </Theme.Provider>
                </Language.Provider>
              </Theme.Provider>

          );
        };
        // We expect 1 error.
        await render(<App />, 1);
      },
    );

    itRenders(
      'should warn with an error message when using Context.Consumer.Provider DEV',
      async render => {
        const App = () => {
          const Theme = React.createContext('dark');
          const Language = React.createContext('french');

          return (

              <Theme.Provider value="light">
                <Language.Provider value="english">
                  <Theme.Consumer.Provider value="dark">
                    <Theme.Consumer>
                      {theme =>
{theme}
}
                    </Theme.Consumer>
                  </Theme.Consumer.Provider>
                </Language.Provider>
              </Theme.Provider>

          );
        };
        // We expect 1 error.
        await render(<App />, 1);
      },
    );

    it('does not pollute parallel node streams', () => {
      const LoggedInUser = React.createContext();

      const AppWithUser = user => (
        <LoggedInUser.Provider value={user}>

            <LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer>

            <LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer>

        </LoggedInUser.Provider>
      );

      const streamAmy = ReactDOMServer.renderToNodeStream(
        AppWithUser('Amy'),
      ).setEncoding('utf8');
      const streamBob = ReactDOMServer.renderToNodeStream(
        AppWithUser('Bob'),
      ).setEncoding('utf8');

      // Testing by filling the buffer using internal _read() with a small
      // number of bytes to avoid a test case which needs to align to a
      // highWaterMark boundary of 2^14 chars.
      streamAmy._read(20);
      streamBob._read(20);
      streamAmy._read(20);
      streamBob._read(20);

      expect(streamAmy.read()).toBe('AmyAmy');
      expect(streamBob.read()).toBe('BobBob');
    });

    it('does not pollute parallel node streams when many are used', () => {
      const CurrentIndex = React.createContext();

      const NthRender = index => (
        <CurrentIndex.Provider value={index}>

            <CurrentIndex.Consumer>{idx => idx}</CurrentIndex.Consumer>

            <CurrentIndex.Consumer>{idx => idx}</CurrentIndex.Consumer>

        </CurrentIndex.Provider>
      );

      let streams = [];

      // Test with more than 32 streams to test that growing the thread count
      // works properly.
      let streamCount = 34;

      for (let i = 0; i < streamCount; i++) {
        streams[i] = ReactDOMServer.renderToNodeStream(
          NthRender(i % 2 === 0 ? 'Expected to be recreated' : i),
        ).setEncoding('utf8');
      }

      // Testing by filling the buffer using internal _read() with a small
      // number of bytes to avoid a test case which needs to align to a
      // highWaterMark boundary of 2^14 chars.
      for (let i = 0; i < streamCount; i++) {
        streams[i]._read(20);
      }

      // Early destroy every other stream
      for (let i = 0; i < streamCount; i += 2) {
        streams[i].destroy();
      }

      // Recreate those same streams.
      for (let i = 0; i < streamCount; i += 2) {
        streams[i] = ReactDOMServer.renderToNodeStream(
          NthRender(i),
        ).setEncoding('utf8');
      }

      // Read a bit from all streams again.
      for (let i = 0; i < streamCount; i++) {
        streams[i]._read(20);
      }

      // Assert that all stream rendered the expected output.
      for (let i = 0; i < streamCount; i++) {
        expect(streams[i].read()).toBe(
          '' + i + '' + i + '',
        );
      }
    });
  });
});
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name requisition-validation.validationFactory
     *
     * @description
     * Provides validation of columns that require some custom checks.
     */
    angular
        .module('requisition-validation')
        .factory('validationFactory', validationFactory);

    validationFactory.$inject = ['messageService', 'TEMPLATE_COLUMNS', 'calculationFactory'];

    function validationFactory(messageService, TEMPLATE_COLUMNS, calculationFactory) {
        var factory = {
            stockOnHand: validateStockOnHand,
            totalConsumedQuantity: validateTotalConsumedQuantity,
            requestedQuantityExplanation: validateRequestedQuantityExplanation,
            requestedQuantity: validateRequestedQuantity,
            totalStockoutDays: validateTotalStockoutDays
        };
        return factory;

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name stockOnHand
         *
         * @description
         * Provides custom validator for the stock on hand column.
         *
         * @param  {Object} lineItem the line item to be validated
         * @return {String}          the error if field is invalid, undefined otherwise
         */
        function validateStockOnHand(lineItem) {
            if (lineItem.stockOnHand < 0) {
                return messageService.get('requisitionValidation.canNotBeNegative');
            }
        }

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name totalConsumedQuantity
         *
         * @description
         * Provides custom validator for the total consumed quantity column.
         *
         * @param  {Object} lineItem the line item to be validated
         * @return {String}          the error if field is invalid, undefined otherwise
         */
        function validateTotalConsumedQuantity(lineItem) {
            if (lineItem.totalConsumedQuantity < 0) {
                return messageService.get('requisitionValidation.canNotBeNegative');
            }
        }

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name requestedQuantityExplanation
         *
         * @description
         * Provides custom validator for the requested quantity explanation column.
         *
         * @param  {Object} lineItem    the line item to be validated
         * @param  {Object} requisition the requisition to validate the field for
         * @return {String}             the error if field is invalid, undefined otherwise
         */
        function validateRequestedQuantityExplanation(lineItem, requisition) {
            var requestedQuantityColumn = requisition.template.getColumn(TEMPLATE_COLUMNS.REQUESTED_QUANTITY),
                calculatedOrderQuantityColumn = requisition.template.getColumn(TEMPLATE_COLUMNS.CALCULATED_ORDER_QUANTITY),
                requestedQuantityExplanation = lineItem.requestedQuantityExplanation,
                requestedQuantity = lineItem.requestedQuantity;

            if (isDisplayed(requestedQuantityColumn) && isDisplayed(calculatedOrderQuantityColumn) &&
                    !(requestedQuantity === null || requestedQuantity === undefined) &&
                    !requestedQuantityExplanation) {

                return messageService.get('requisitionValidation.required');
            }
            return;
        }

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name requestedQuantity
         *
         * @description
         * Provides custom validator for the requested quantity column.
         *
         * @param  {Object} lineItem    the line item to be validated
         * @param  {Object} requisition the requisition to validate the field for
         * @return {String}             the error if field is invalid, undefined otherwise
         */
        function validateRequestedQuantity(lineItem, requisition) {
            var requestedQuantity = lineItem.requestedQuantity;

            if (isRequestedQuantityRequired(lineItem, requisition) && !isFilled(requestedQuantity)) {
                return messageService.get('requisitionValidation.required');
            }
        }

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name validateTotalStockoutDays
         *
         * @description
         * Provides custom validator for the total stock out days column.
         *
         * @param  {Object} lineItem    the line item to be validated
         * @param  {Object} requisition the requisition to validate the field for
         * @return {String}             the error if field is invalid, undefined otherwise
         */
        function validateTotalStockoutDays(lineItem, requisition) {
            var totalDays = 30 * requisition.processingPeriod.durationInMonths,
                totalStockoutDays = lineItem.totalStockoutDays,
                nonStockoutDays = totalDays - totalStockoutDays;

            if (nonStockoutDays < 0) {
                return messageService.get('requisitionValidation.valueExceedPeriodDuration');
            }
        }

        function isDisplayed(column) {
            return column && column.$display;
        }

        function isRequestedQuantityRequired(lineItem, requisition) {
            return lineItem.isNonFullSupply() || !isDisplayed(
                requisition.template.getColumn(TEMPLATE_COLUMNS.CALCULATED_ORDER_QUANTITY)
            );
        }

        function isFilled(value) {
            return value !== null && value !== undefined;
        }
    }

})();
<commit_msg>OLMIS-2466: Refactored validationFactory to use isFilled function<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name requisition-validation.validationFactory
     *
     * @description
     * Provides validation of columns that require some custom checks.
     */
    angular
        .module('requisition-validation')
        .factory('validationFactory', validationFactory);

    validationFactory.$inject = ['messageService', 'TEMPLATE_COLUMNS', 'calculationFactory'];

    function validationFactory(messageService, TEMPLATE_COLUMNS, calculationFactory) {
        var factory = {
            stockOnHand: validateStockOnHand,
            totalConsumedQuantity: validateTotalConsumedQuantity,
            requestedQuantityExplanation: validateRequestedQuantityExplanation,
            requestedQuantity: validateRequestedQuantity,
            totalStockoutDays: validateTotalStockoutDays
        };
        return factory;

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name stockOnHand
         *
         * @description
         * Provides custom validator for the stock on hand column.
         *
         * @param  {Object} lineItem the line item to be validated
         * @return {String}          the error if field is invalid, undefined otherwise
         */
        function validateStockOnHand(lineItem) {
            if (lineItem.stockOnHand < 0) {
                return messageService.get('requisitionValidation.canNotBeNegative');
            }
        }

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name totalConsumedQuantity
         *
         * @description
         * Provides custom validator for the total consumed quantity column.
         *
         * @param  {Object} lineItem the line item to be validated
         * @return {String}          the error if field is invalid, undefined otherwise
         */
        function validateTotalConsumedQuantity(lineItem) {
            if (lineItem.totalConsumedQuantity < 0) {
                return messageService.get('requisitionValidation.canNotBeNegative');
            }
        }

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name requestedQuantityExplanation
         *
         * @description
         * Provides custom validator for the requested quantity explanation column.
         *
         * @param  {Object} lineItem    the line item to be validated
         * @param  {Object} requisition the requisition to validate the field for
         * @return {String}             the error if field is invalid, undefined otherwise
         */
        function validateRequestedQuantityExplanation(lineItem, requisition) {
            var requestedQuantityColumn = requisition.template.getColumn(TEMPLATE_COLUMNS.REQUESTED_QUANTITY),
                calculatedOrderQuantityColumn = requisition.template.getColumn(TEMPLATE_COLUMNS.CALCULATED_ORDER_QUANTITY),
                requestedQuantityExplanation = lineItem.requestedQuantityExplanation,
                requestedQuantity = lineItem.requestedQuantity;

            if (isDisplayed(requestedQuantityColumn) && isDisplayed(calculatedOrderQuantityColumn) &&
                    isFilled(requestedQuantity) &&
                    !requestedQuantityExplanation) {

                return messageService.get('requisitionValidation.required');
            }
            return;
        }

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name requestedQuantity
         *
         * @description
         * Provides custom validator for the requested quantity column.
         *
         * @param  {Object} lineItem    the line item to be validated
         * @param  {Object} requisition the requisition to validate the field for
         * @return {String}             the error if field is invalid, undefined otherwise
         */
        function validateRequestedQuantity(lineItem, requisition) {
            var requestedQuantity = lineItem.requestedQuantity;

            if (isRequestedQuantityRequired(lineItem, requisition) && !isFilled(requestedQuantity)) {
                return messageService.get('requisitionValidation.required');
            }
        }

        /**
         * @ngdoc method
         * @methodOf requisition-validation.validationFactory
         * @name validateTotalStockoutDays
         *
         * @description
         * Provides custom validator for the total stock out days column.
         *
         * @param  {Object} lineItem    the line item to be validated
         * @param  {Object} requisition the requisition to validate the field for
         * @return {String}             the error if field is invalid, undefined otherwise
         */
        function validateTotalStockoutDays(lineItem, requisition) {
            var totalDays = 30 * requisition.processingPeriod.durationInMonths,
                totalStockoutDays = lineItem.totalStockoutDays,
                nonStockoutDays = totalDays - totalStockoutDays;

            if (nonStockoutDays < 0) {
                return messageService.get('requisitionValidation.valueExceedPeriodDuration');
            }
        }

        function isDisplayed(column) {
            return column && column.$display;
        }

        function isRequestedQuantityRequired(lineItem, requisition) {
            return lineItem.isNonFullSupply() || !isDisplayed(
                requisition.template.getColumn(TEMPLATE_COLUMNS.CALCULATED_ORDER_QUANTITY)
            );
        }

        function isFilled(value) {
            return value !== null && value !== undefined;
        }
    }

})();
<|endoftext|>


<commit_before>;(function($) {

  function Countdown() {
    this.today  = new Date();
    this.geddon = new Date(this.today.getFullYear(), 05, 08);
    this.remain = {
      days: null,
      hours: null,
      minutes: null,
      seconds: null
    };
  }

  Countdown.prototype.run = function() {
    var diff = this.getDateDiff();
    this.convertEpoch(diff);
    this.updateDisplay();
  };

  Countdown.prototype.getDateDiff = function() {
    return Math.abs(this.geddon.getTime() - this.today.getTime());
  };

  Countdown.prototype.convertEpoch = function(epoch) {
    this.remain.seconds = Math.floor(epoch/1000);
    this.remain.minutes = Math.floor(this.remain.seconds/60);
    this.remain.hours   = Math.floor(this.remain.minutes/60);
    this.remain.days    = Math.floor(this.remain.hours/24);

    this.remain.hours = this.remain.hours-(this.remain.days*24);
    this.remain.minutes = this.remain.minutes-(this.remain.days*24*60)-(this.remain.hours*60);
    this.remain.seconds = this.remain.seconds-(this.remain.days*24*60*60)-(this.remain.hours*60*60)-(this.remain.minutes*60);
  };

  Countdown.prototype.updateDisplay = function() {
    var days    = this.remain.days + ":",
        hours   = this.remain.hours + ":",
        minutes = this.remain.minutes + ":";
        seconds = this.remain.seconds;

    if(this.remain.days < 10) {
      days = "0" + days;
    }

    if(this.remain.hours < 10) {
      hours = "0" + hours;
    }

    if(this.remain.minutes < 10) {
      minutes = "0" + minutes;
    }

    if(this.remain.seconds < 10) {
      seconds = "0" + seconds;
    }

    $('#days').text(days);
    $('#hours').text(hours);
    $('#minutes').text(minutes);
    $('#seconds').text(seconds);
  };

  function loadApp() {
    var cd = new Countdown();
    cd.run();
  }

  setInterval(loadApp, 1000);

})(jQuery);<commit_msg>Set to 9am<commit_after>;(function($) {

  function Countdown() {
    this.today  = new Date();
    this.geddon = new Date(this.today.getFullYear(), 05, 08, 9, 0, 0);
    this.remain = {
      days: null,
      hours: null,
      minutes: null,
      seconds: null
    };
  }

  Countdown.prototype.run = function() {
    var diff = this.getDateDiff();
    this.convertEpoch(diff);
    this.updateDisplay();
  };

  Countdown.prototype.getDateDiff = function() {
    return Math.abs(this.geddon.getTime() - this.today.getTime());
  };

  Countdown.prototype.convertEpoch = function(epoch) {
    this.remain.seconds = Math.floor(epoch/1000);
    this.remain.minutes = Math.floor(this.remain.seconds/60);
    this.remain.hours   = Math.floor(this.remain.minutes/60);
    this.remain.days    = Math.floor(this.remain.hours/24);

    this.remain.hours = this.remain.hours-(this.remain.days*24);
    this.remain.minutes = this.remain.minutes-(this.remain.days*24*60)-(this.remain.hours*60);
    this.remain.seconds = this.remain.seconds-(this.remain.days*24*60*60)-(this.remain.hours*60*60)-(this.remain.minutes*60);
  };

  Countdown.prototype.updateDisplay = function() {
    var days    = this.remain.days + ":",
        hours   = this.remain.hours + ":",
        minutes = this.remain.minutes + ":";
        seconds = this.remain.seconds;

    if(this.remain.days < 10) {
      days = "0" + days;
    }

    if(this.remain.hours < 10) {
      hours = "0" + hours;
    }

    if(this.remain.minutes < 10) {
      minutes = "0" + minutes;
    }

    if(this.remain.seconds < 10) {
      seconds = "0" + seconds;
    }

    $('#days').text(days);
    $('#hours').text(hours);
    $('#minutes').text(minutes);
    $('#seconds').text(seconds);
  };

  function loadApp() {
    var cd = new Countdown();
    cd.run();
  }

  setInterval(loadApp, 1000);

})(jQuery);<|endoftext|>