<commit_before>var modulus = require('../modulus'),
    librarian = require('../common/api').librarian,
    userConfig = require('../common/api').userConfig,
    fs = require('fs'),
    path = require('path'),
    ProgressBar = require('progress'),
    Progress = require('../util/progress'),
    Errors = require('../util/errors'),
    request = require('request'),
    http = require('http'),
    uploader = require('chunk-loader').Client,
    https = require('https');

http.globalAgent.maxSockets = Number.MAX_VALUE;
https.globalAgent.maxSockets = Number.MAX_VALUE;

//-----------------------------------------------------------------------------
var Project = function() {

};

//-----------------------------------------------------------------------------
Project.prototype.create = function(name, creatorId, callback) {
  librarian.project.create({
    name: name,
    creator: creatorId
  }, false, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.restart = function(projectId, callback) {
  librarian.project.restart(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Restarting [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.stop = function(projectId, callback) {
  librarian.project.stop(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Stopping [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.stopped) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.start = function(projectId, callback) {
  librarian.project.start(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Starting [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.find = function(opts, callback) {
  librarian.project.find(opts, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.saveVars = function(projectId, vars, callback) {
  librarian.project.saveVars(projectId, vars, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.deploy = function(projectId, file, callback) {
  var host = librarian._http._host;
  var port = librarian._http._port;
  var protocol = librarian._http._ssl ? 'https' : 'http';

  modulus.io.print('Uploading project...');
  var status = Project.status.uploading;

  // start checking for status changes
  // show progress for upload and inderminate progress for deploying
  var ubar = new ProgressBar('Upload progress [:bar] :percent', {
    complete: '=',
    incomplete: ' ',
    width: 20,
    total: 100
  });
  ubar.tick();

  var client = uploader.uploadFile(file,
    {
      beginProtocol: 'http',
      uploadProtocol: 'http',
      beginPort: '443',
      uploadPort: '80',
      host: host,
      port: port,
      debug: false,
      encrypted: true,
      tag: { projectId: projectId, authToken: userConfig.data.apiKey }
    }
  );

  client.on('progress', function(p) {
    ubar.tick(((p.sent / p.total) * 100) - ubar.curr);
  });

  client.on('error', function(err) {
    callback(err);
  });

  client.on('complete', function() {
    //var dbar = new Progress.indeterminate('Deploying [:bar]');

    // check every second for project status change
    var projectStatus = function () {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {
        if(!err) {
          if(proj && proj.status) {
            if(proj.status.toLowerCase() !== status) {
              var newStatus = proj.status.toLowerCase();
              if(newStatus === Project.status.deploying) {
                status = newStatus;
                modulus.io.print('\nDeploying Project...');
                //dbar.start();
              } else if(newStatus === Project.status.running && status !== Project.status.uploading) {
                //dbar.stop();
                modulus.io.print(' ');
                return callback(null, proj.domain);
              }
            }
          }
        }

        if(status !== Project.status.running) {
          setTimeout(projectStatus, 1000);
        }
      });
    };
    projectStatus();

    var logLength = 0;
    var deployLogs = function() {
      if(status === Project.status.deploying) {
        librarian.project.getDeployLogs(projectId, userConfig.data.apiKey, function(err, result) {
          for(var key in result) {
            var log = result[key];
            modulus.io.write(log.substring(logLength));
            logLength = log.length;
            break;
          }
        });
      }

      if(status !== Project.status.running) {
        setTimeout(deployLogs, 1000);
      }
    };
    deployLogs();
  });
};

/**
 * Gets the logs for the specified project id.
 * @param {string} projectId The ID of the project.
 * @param {function} callback Function invoked with log results.
 */
//-----------------------------------------------------------------------------
Project.prototype.getLogs = function(projectId, callback) {
  librarian.project.getLog(projectId, userConfig.data.apiKey, callback);
};

/**
 * Downloads the logs as a tarball for the specified project id.
 * @param {string} projectId - the ID of the project.
 * @param {string} projectName - the name of the project
 * @param {string} outLocation - the path to the directory where the tarball should be downloaded
 * @param {function} callback - function invoked with the file stream. Responsible for the actual download.
 */
//-----------------------------------------------------------------------------
Project.prototype.downloadLogs = function(projectId, projectName, outLocation, callback) {
  librarian.project.downloadLogs(projectId, userConfig.data.apiKey, function(err, req, res){
    if(err){
      callback(Errors.getMessage(err));
    }
    if(res.statusCode == 404){
      callback("Problem downloading logs: " + res.statusCode);
    }

    var date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
    var outFile = projectName + '_' + date + '.tar.gz';
    outFile = outFile.replace(/ /g, '_').replace(/:/g,'.').replace(/[[\]{}@~`<>()*+=%&!?,\\^$|#\s]/g,'');
    if(outLocation!=null && typeof outLocation == 'string'){
      outFile = outLocation;
      outFile = outFile.replace(/\//g, '/');
      if(!fs.existsSync(path.dirname(outLocation))){
        return callback('Directory ' + path.dirname(outLocation) + ' does not exist.');
      };
    }
    var dir = '';
    if(path.dirname(outLocation) == '.'){
      dir = __dirname;
    } else {
      dir = path.dirname(path.resolve(outLocation));
    }

    var result = {};
    var stream = fs.createWriteStream(outFile);

    res.pipe(stream);
    res.on('end', function(err, stdout, stderr){
      if(err){
        callback(Errors.getMessage(err));
      }
      if(stderr){
        result.stderr = stderr;
      }
      if(stdout){
        result.stdout = stdout;
      }
      result.msg = ' - ' + path.basename(outFile) + ' downloaded to ' + dir;
      result.outFile = outFile;
      callback(null, result);
    });
  });
};

/**
 * Wipes all project logs for a given project
 * @param {integer} projectId - project id
 * @param {function} callback - callback function
*/
//-----------------------------------------------------------------------------
Project.prototype.clearLogs = function(projectId, callback){
  librarian.project.clearLogs(projectId, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.scale = function(projectId, instances, callback) {
  librarian.project.scale(projectId, {instances:instances}, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Scaling [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.status = {
  uploading : 'uploading',
  deploying : 'deploying',
  running : 'running',
  stopped: 'stopped'
};

module.exports = new Project();<commit_msg>Quick formatting fix.<commit_after>var modulus = require('../modulus'),
    librarian = require('../common/api').librarian,
    userConfig = require('../common/api').userConfig,
    fs = require('fs'),
    path = require('path'),
    ProgressBar = require('progress'),
    Progress = require('../util/progress'),
    Errors = require('../util/errors'),
    request = require('request'),
    http = require('http'),
    uploader = require('chunk-loader').Client,
    https = require('https');

http.globalAgent.maxSockets = Number.MAX_VALUE;
https.globalAgent.maxSockets = Number.MAX_VALUE;

//-----------------------------------------------------------------------------
var Project = function() {

};

//-----------------------------------------------------------------------------
Project.prototype.create = function(name, creatorId, callback) {
  librarian.project.create({
    name: name,
    creator: creatorId
  }, false, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.restart = function(projectId, callback) {
  librarian.project.restart(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Restarting [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.stop = function(projectId, callback) {
  librarian.project.stop(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Stopping [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.stopped) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.start = function(projectId, callback) {
  librarian.project.start(projectId, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Starting [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.prototype.find = function(opts, callback) {
  librarian.project.find(opts, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.saveVars = function(projectId, vars, callback) {
  librarian.project.saveVars(projectId, vars, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.deploy = function(projectId, file, callback) {
  var host = librarian._http._host;
  var port = librarian._http._port;
  var protocol = librarian._http._ssl ? 'https' : 'http';

  modulus.io.print('Uploading project...');
  var status = Project.status.uploading;

  // start checking for status changes
  // show progress for upload and inderminate progress for deploying
  var ubar = new ProgressBar('Upload progress [:bar] :percent', {
    complete: '=',
    incomplete: ' ',
    width: 20,
    total: 100
  });
  ubar.tick();

  var client = uploader.uploadFile(file,
    {
      beginProtocol: 'http',
      uploadProtocol: 'http',
      beginPort: '443',
      uploadPort: '80',
      host: host,
      port: port,
      debug: false,
      encrypted: true,
      tag: { projectId: projectId, authToken: userConfig.data.apiKey }
    }
  );

  client.on('progress', function(p) {
    ubar.tick(((p.sent / p.total) * 100) - ubar.curr);
  });

  client.on('error', function(err) {
    callback(err);
  });

  client.on('complete', function() {
    //var dbar = new Progress.indeterminate('Deploying [:bar]');

    // check every second for project status change
    var projectStatus = function () {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {
        if(!err) {
          if(proj && proj.status) {
            if(proj.status.toLowerCase() !== status) {
              var newStatus = proj.status.toLowerCase();
              if(newStatus === Project.status.deploying) {
                status = newStatus;
                modulus.io.print('\nDeploying Project...');
                //dbar.start();
              } else if(newStatus === Project.status.running && status !== Project.status.uploading) {
                //dbar.stop();
                modulus.io.print(' ');
                return callback(null, proj.domain);
              }
            }
          }
        }

        if(status !== Project.status.running) {
          setTimeout(projectStatus, 1000);
        }
      });
    };
    projectStatus();

    var logLength = 0;
    var deployLogs = function() {
      if(status === Project.status.deploying) {
        librarian.project.getDeployLogs(projectId, userConfig.data.apiKey, function(err, result) {
          for(var key in result) {
            var log = result[key];
            modulus.io.write(log.substring(logLength));
            logLength = log.length;
            break;
          }
        });
      }

      if(status !== Project.status.running) {
        setTimeout(deployLogs, 1000);
      }
    };
    deployLogs();
  });
};

/**
 * Gets the logs for the specified project id.
 * @param {string} projectId The ID of the project.
 * @param {function} callback Function invoked with log results.
 */
//-----------------------------------------------------------------------------
Project.prototype.getLogs = function(projectId, callback) {
  librarian.project.getLog(projectId, userConfig.data.apiKey, callback);
};

/**
 * Downloads the logs as a tarball for the specified project id.
 * @param {string} projectId - the ID of the project.
 * @param {string} projectName - the name of the project
 * @param {string} outLocation - the path to the directory where the tarball should be downloaded
 * @param {function} callback - function invoked with the file stream. Responsible for the actual download.
 */
//-----------------------------------------------------------------------------
Project.prototype.downloadLogs = function(projectId, projectName, outLocation, callback) {
  librarian.project.downloadLogs(projectId, userConfig.data.apiKey, function(err, req, res){
    if(err){
      callback(Errors.getMessage(err));
    }
    if(res.statusCode == 404){
      callback("Problem downloading logs: " + res.statusCode);
    }

    var date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
    var outFile = projectName + '_' + date + '.tar.gz';
    outFile = outFile.replace(/ /g, '_').replace(/:/g,'.').replace(/[[\]{}@~`<>()*+=%&!?,\\^$|#\s]/g,'');
    if(outLocation!=null && typeof outLocation == 'string'){
      outFile = outLocation;
      outFile = outFile.replace(/\//g, '/');
      if(!fs.existsSync(path.dirname(outLocation))){
        return callback('Directory ' + path.dirname(outLocation) + ' does not exist.');
      };
    }
    var dir = '';
    if(path.dirname(outLocation) == '.'){
      dir = __dirname;
    } else {
      dir = path.dirname(path.resolve(outLocation));
    }

    var result = {};
    var stream = fs.createWriteStream(outFile);

    res.pipe(stream);
    res.on('end', function(err, stdout, stderr){
      if(err){
        callback(Errors.getMessage(err));
      }
      if(stderr){
        result.stderr = stderr;
      }
      if(stdout){
        result.stdout = stdout;
      }
      result.msg = path.basename(outFile) + ' downloaded to ' + dir + '.';
      result.outFile = outFile;
      callback(null, result);
    });
  });
};

/**
 * Wipes all project logs for a given project
 * @param {integer} projectId - project id
 * @param {function} callback - callback function
*/
//-----------------------------------------------------------------------------
Project.prototype.clearLogs = function(projectId, callback){
  librarian.project.clearLogs(projectId, userConfig.data.apiKey, callback);
};

//-----------------------------------------------------------------------------
Project.prototype.scale = function(projectId, instances, callback) {
  librarian.project.scale(projectId, {instances:instances}, userConfig.data.apiKey, function(err, result) {
    if(err) {
      return callback(Errors.getMessage(err));
    }

    var dbar = new Progress.indeterminate('Scaling [:bar]');
    dbar.start();

    var checkStatus = function() {
      librarian.project.find({projectId : projectId}, userConfig.data.apiKey, function(err, proj) {

        if(err) {
          return callback(Errors.getMessage(err));
        }

        if(proj.status.toLowerCase() === Project.status.running) {
          dbar.stop();
          modulus.io.print(' ');
          return callback(null, proj);
        }
        else {
          setTimeout(checkStatus, 1000);
        }
      });
    };

    setTimeout(checkStatus, 1000);
  });
};

//-----------------------------------------------------------------------------
Project.status = {
  uploading : 'uploading',
  deploying : 'deploying',
  running : 'running',
  stopped: 'stopped'
};

module.exports = new Project();<|endoftext|>


<commit_before>var Map = {};
Map.map = null;
Map.markers = null;

$(document).on('pageshow', '#map', function() {
    initMap();
});

function initMap() {
    Map.markers = [];

    $('#map-canvas').css('height', 500);
    Map.map = Map.createMap('map-canvas', 34.87728, 135.576798); // kutc

    utils.getCurrentLocation().done(function(location) {
	var pos = new google.maps.LatLng(location.latitude,
					 location.longitude);

	Map.currentLocation = Map.createMarker(Map.map, 'Current location',
					       location.latitude, location.longitude, false);
    });

    Map.infoWindow = new google.maps.InfoWindow;

    utils.fetchPosts().done(function(json) {
	for (var i = 0; i < json.length; i++) {
	    var marker = Map.createMarker(Map.map, json[i].title,
					  json[i].latitude, json[i].longitude, false);
	    marker.data = json[i];
	    Map.markers.push(marker);

	    google.maps.event.addListener(marker, 'click', function() {
		var content = Map.jsonToContent(this.data);
		Map.infoWindow.setContent(content);
		Map.infoWindow.open(Map.map, this);
	    });
	}
    });
}

Map.createMap = function(id, lat, lng) {
    var mapOptions = {
	center: new google.maps.LatLng(lat, lng),
	zoom: 8,
	mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById(id), mapOptions);
    return map;
};

Map.createMarker = function(map, title, lat, lng, draggable) {
    var marker = new google.maps.Marker({
	position: new google.maps.LatLng(lat, lng),
	map: map,
	title : title,
	draggable: draggable
    });
    return marker;
};

Map.jsonToContent = function(json) {
    var title = json.title;
    var created_at = json.created_at;
    var posted_by = json.posted_by;
    var comment = json.comment;

    var content =
	    '
' +
	    '
' + title + '
' +
	    '
' + created_at + '
' +
	    '
' + posted_by + '
' +
	    '
' + comment + '
' +
	    '
';

    return content;
};<commit_msg>Minor change<commit_after>var Map = {};
Map.map = null;
Map.markers = null;

$(document).on('pageshow', '#map', function() {
    Map.initMap();
});

Map.initMap = function() {
    Map.markers = [];

    $('#map-canvas').css('height', 500);
    Map.map = Map.createMap('map-canvas', 34.87728, 135.576798); // kutc

    utils.getCurrentLocation().done(function(location) {
	var pos = new google.maps.LatLng(location.latitude,
					 location.longitude);

	Map.currentLocation = Map.createMarker(Map.map, 'Current location',
					       location.latitude, location.longitude, false);
    });

    Map.infoWindow = new google.maps.InfoWindow;

    utils.fetchPosts().done(function(json) {
	for (var i = 0; i < json.length; i++) {
	    var marker = Map.createMarker(Map.map, json[i].title,
					  json[i].latitude, json[i].longitude, false);
	    marker.data = json[i];
	    Map.markers.push(marker);

	    google.maps.event.addListener(marker, 'click', function() {
		var content = Map.jsonToContent(this.data);
		Map.infoWindow.setContent(content);
		Map.infoWindow.open(Map.map, this);
	    });
	}
    });
};

Map.createMap = function(id, lat, lng) {
    var mapOptions = {
	center: new google.maps.LatLng(lat, lng),
	zoom: 8,
	mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById(id), mapOptions);
    return map;
};

Map.createMarker = function(map, title, lat, lng, draggable) {
    var marker = new google.maps.Marker({
	position: new google.maps.LatLng(lat, lng),
	map: map,
	title : title,
	draggable: draggable
    });
    return marker;
};

Map.jsonToContent = function(json) {
    var title = json.title;
    var created_at = json.created_at;
    var posted_by = json.posted_by;
    var comment = json.comment;

    var content =
	    '
' +
	    '
' + title + '
' +
	    '
' + created_at + '
' +
	    '
' + posted_by + '
' +
	    '
' + comment + '
' +
	    '
';

    return content;
};<|endoftext|>


<commit_before><commit_msg>Widgets flip fix.<commit_after><|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2017, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * 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 License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* jshint esversion:6 */

var _ = require('lodash');
var { MGDL_PER_MMOLL, MGDL_UNITS, MMOLL_UNITS, DEFAULT_BG_BOUNDS } = require('../../data/util/constants');

var Categorizer = function(bgClasses, bgUnits = MGDL_UNITS){
  var classes = _.cloneDeep(bgClasses);
  var defaults = {
    'very-low': { boundary: DEFAULT_BG_BOUNDS.veryLow },
    low: { boundary: DEFAULT_BG_BOUNDS.targetLower },
    target: { boundary: DEFAULT_BG_BOUNDS.targetUpper },
    high: { boundary: DEFAULT_BG_BOUNDS.veryHigh },
  };

  if (bgUnits === MMOLL_UNITS) {
    _.forOwn(defaults, function(value, key) {
      defaults[key].boundary = Math.round(value.boundary/MGDL_PER_MMOLL);
    });
  }

  _.defaults(classes, defaults);

  return function(d) {
    if (d.value < classes['very-low'].boundary) {
      return 'verylow';
    }
    else if (d.value >= classes['very-low'].boundary &&
      d.value < classes.low.boundary) {
      return 'low';
    }
    else if (d.value >= classes.low.boundary &&
      d.value <= classes.target.boundary) {
      return 'target';
    }
    else if (d.value > classes.target.boundary &&
      d.value <= classes.high.boundary) {
      return 'high';
    }
    else if (d.value > classes.high.boundary) {
      return 'veryhigh';
    }
  };
};

module.exports = Categorizer;
<commit_msg>Fix BG unit conversion issue<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2017, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * 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 License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* jshint esversion:6 */

var _ = require('lodash');
var d3 = require('d3');
var { MGDL_PER_MMOLL, MGDL_UNITS, MMOLL_UNITS, DEFAULT_BG_BOUNDS } = require('../../data/util/constants');

var Categorizer = function(bgClasses, bgUnits = MGDL_UNITS){
  var classes = _.cloneDeep(bgClasses);
  var defaults = {
    'very-low': { boundary: DEFAULT_BG_BOUNDS.veryLow },
    low: { boundary: DEFAULT_BG_BOUNDS.targetLower },
    target: { boundary: DEFAULT_BG_BOUNDS.targetUpper },
    high: { boundary: DEFAULT_BG_BOUNDS.veryHigh },
  };

  if (bgUnits === MMOLL_UNITS) {
    _.forOwn(defaults, function(value, key) {
      defaults[key].boundary = d3.format('.1f')(value.boundary/MGDL_PER_MMOLL);
    });
  }

  _.defaults(classes, defaults);

  return function(d) {
    if (d.value < classes['very-low'].boundary) {
      return 'verylow';
    }
    else if (d.value >= classes['very-low'].boundary &&
      d.value < classes.low.boundary) {
      return 'low';
    }
    else if (d.value >= classes.low.boundary &&
      d.value <= classes.target.boundary) {
      return 'target';
    }
    else if (d.value > classes.target.boundary &&
      d.value <= classes.high.boundary) {
      return 'high';
    }
    else if (d.value > classes.high.boundary) {
      return 'veryhigh';
    }
  };
};

module.exports = Categorizer;
<|endoftext|>


<commit_before>'use strict';

/**
 * @module e2e
 */

/**
 * A web page to help writing end to end tests with protractor for OpenVeo.
 *
 * Do not use this directly but extend it.
 *
 * @example
 *
 *     var Page = require('@openveo/test').e2e.Page;
 *
 *     function MyPage() {
 *       MyPage.super_.call(this);
 *       this.path = 'be/myPage';
 *     }
 *
 *     module.exports = MyPage;
 *     util.inherits(MyPage, Page);
 *
 *     var page = new MyPage();
 *     page.load().then(function() {
 *       console.log('Page fully loaded');
 *     });
 *
 * @class Page
 * @constructor
 */
function Page() {

  /**
   * Protractor expected conditions.
   *
   * @property EC
   * @type ExpectedConditions
   */
  this.EC = protractor.ExpectedConditions;

  /**
   * Protractor control flow.
   *
   * @property flow
   * @type ControlFlow
   */
  this.flow = browser.controlFlow();

  /**
   * Body element.
   *
   * @property bodyElement
   * @type ElementFinder
   */
  this.bodyElement = element(by.css('body'));

  /**
   * Page element.
   *
   * Page wrapper holding the content scrollbar.
   *
   * @property pageElement
   * @type ElementFinder
   */
  this.pageElement = element(by.id('page-content-wrapper'));
}

module.exports = Page;

/**
 * Loads the page.
 *
 * @example
 *
 *     var Page = require('@openveo/test').e2e.Page;
 *
 *     function MyPage() {
 *       MyPage.super_.call(this);
 *       this.path = 'be/myPage';
 *     }
 *
 *     module.exports = MyPage;
 *     util.inherits(MyPage, Page);
 *
 *     var page = new MyPage();
 *     page.load().then(function() {
 *       console.log('Page fully loaded');
 *     });
 *
 * @method load
 * @return {Promise} Promise resolving when the page is fully loaded
 */
Page.prototype.load = function() {
  var self = this;
  var expectedUrl = process.protractorConf.baseUrl + this.path;

  // Load url of the page
  return browser.get(this.path).then(function() {

    // Deactivate animations
    self.bodyElement.allowAnimations(false);

    // Verify if loaded page is the expected one
    return browser.getCurrentUrl().then(function(currentUrl) {
      if (currentUrl.replace(/\/$/, '') !== expectedUrl)
        return protractor.promise.rejected(new Error('Failed loading page ' + expectedUrl +
                                                     ' (got ' + currentUrl + ')'));
      else
        return self.onLoaded();
    });

  }).then(function() {
    return protractor.promise.fulfilled();
  });

};

/**
 * Gets page title as described by the HTMLTitleElement.
 *
 * @example
 *
 *     // With MyPage extending Page
 *     var page = new MyPage();
 *     assert.eventually.equal(page.getTitle(), 'My page title');
 *
 * @method getTitle
 * @return {Promise} Promise resolving with the title of the page
 */
Page.prototype.getTitle = function() {
  return browser.getTitle();
};

/**
 * Removes all cookies on the actual page.
 *
 * @method deleteCookies
 * @return {Promise} Promise resolving when all cookies are deleted
 */
Page.prototype.deleteCookies = function() {
  return browser.driver.manage().deleteAllCookies();
};

/**
 * Sends an http request and return its reponse.
 *
 * This will execute the request from the page.
 *
 * @param {String} path Request's path
 * @param {String} method HTTP method to use
 * @param {Object} data Request's data to send in body
 * @return {Promise} Promise resolving with the request's response
 */
Page.prototype.sendRequest = function(path, method, data) {
  var url = process.protractorConf.baseUrl + path;

  return browser.executeAsyncScript(function() {
    var callback = arguments[arguments.length - 1];
    var url = arguments[0];
    var method = arguments[1];
    var data = arguments[2];
    var $http = angular.injector(['ng']).get('$http');
    $http({
      url: url,
      method: method,
      data: data,
      responseType: 'json'
    }).then(function(response) {
      callback(response);
    }, function(response) {
      callback(response);
    });
  }, url, method, data);
};

/**
 * Refreshes actual page.
 *
 * @method refresh
 * @return {Promise} Promise resolving when the page is fully loaded
 */
Page.prototype.refresh = function() {
  var self = this;

  return browser.refresh().then(function() {
    self.bodyElement.allowAnimations(false);
    return self.onLoaded();
  }).then(function() {
    return protractor.promise.fulfilled();
  });
};

/**
 * Handles page loaded.
 *
 * Use this method to perform actions after the page is loaded. Typically, verify that the page is loaded by
 * waiting for elements to be present on the page.
 *
 * By default it does nothing, override it to define your own behaviour.
 *
 * @method onLoaded
 * @return {Promise} Promise resolving when the page is fully loaded
 */
Page.prototype.onLoaded = function() {};
<commit_msg>Correct bug when comparing expected page url and loaded page url in end to end tests<commit_after>'use strict';

/**
 * @module e2e
 */

/**
 * A web page to help writing end to end tests with protractor for OpenVeo.
 *
 * Do not use this directly but extend it.
 *
 * @example
 *
 *     var Page = require('@openveo/test').e2e.Page;
 *
 *     function MyPage() {
 *       MyPage.super_.call(this);
 *       this.path = 'be/myPage';
 *     }
 *
 *     module.exports = MyPage;
 *     util.inherits(MyPage, Page);
 *
 *     var page = new MyPage();
 *     page.load().then(function() {
 *       console.log('Page fully loaded');
 *     });
 *
 * @class Page
 * @constructor
 */
function Page() {

  /**
   * Protractor expected conditions.
   *
   * @property EC
   * @type ExpectedConditions
   */
  this.EC = protractor.ExpectedConditions;

  /**
   * Protractor control flow.
   *
   * @property flow
   * @type ControlFlow
   */
  this.flow = browser.controlFlow();

  /**
   * Body element.
   *
   * @property bodyElement
   * @type ElementFinder
   */
  this.bodyElement = element(by.css('body'));

  /**
   * Page element.
   *
   * Page wrapper holding the content scrollbar.
   *
   * @property pageElement
   * @type ElementFinder
   */
  this.pageElement = element(by.id('page-content-wrapper'));
}

module.exports = Page;

/**
 * Loads the page.
 *
 * @example
 *
 *     var Page = require('@openveo/test').e2e.Page;
 *
 *     function MyPage() {
 *       MyPage.super_.call(this);
 *       this.path = 'be/myPage';
 *     }
 *
 *     module.exports = MyPage;
 *     util.inherits(MyPage, Page);
 *
 *     var page = new MyPage();
 *     page.load().then(function() {
 *       console.log('Page fully loaded');
 *     });
 *
 * @method load
 * @return {Promise} Promise resolving when the page is fully loaded
 */
Page.prototype.load = function() {
  var self = this;
  var expectedUrl = process.protractorConf.baseUrl + this.path;

  // Load url of the page
  return browser.get(this.path).then(function() {

    // Deactivate animations
    self.bodyElement.allowAnimations(false);

    // Verify if loaded page is the expected one
    return browser.getCurrentUrl().then(function(currentUrl) {
      if (currentUrl.replace(/\/$/, '') !== expectedUrl.replace(/\/$/, ''))
        return protractor.promise.rejected(new Error('Failed loading page ' + expectedUrl +
                                                     ' (got ' + currentUrl + ')'));
      else
        return self.onLoaded();
    });

  }).then(function() {
    return protractor.promise.fulfilled();
  });

};

/**
 * Gets page title as described by the HTMLTitleElement.
 *
 * @example
 *
 *     // With MyPage extending Page
 *     var page = new MyPage();
 *     assert.eventually.equal(page.getTitle(), 'My page title');
 *
 * @method getTitle
 * @return {Promise} Promise resolving with the title of the page
 */
Page.prototype.getTitle = function() {
  return browser.getTitle();
};

/**
 * Removes all cookies on the actual page.
 *
 * @method deleteCookies
 * @return {Promise} Promise resolving when all cookies are deleted
 */
Page.prototype.deleteCookies = function() {
  return browser.driver.manage().deleteAllCookies();
};

/**
 * Sends an http request and return its reponse.
 *
 * This will execute the request from the page.
 *
 * @param {String} path Request's path
 * @param {String} method HTTP method to use
 * @param {Object} data Request's data to send in body
 * @return {Promise} Promise resolving with the request's response
 */
Page.prototype.sendRequest = function(path, method, data) {
  var url = process.protractorConf.baseUrl + path;

  return browser.executeAsyncScript(function() {
    var callback = arguments[arguments.length - 1];
    var url = arguments[0];
    var method = arguments[1];
    var data = arguments[2];
    var $http = angular.injector(['ng']).get('$http');
    $http({
      url: url,
      method: method,
      data: data,
      responseType: 'json'
    }).then(function(response) {
      callback(response);
    }, function(response) {
      callback(response);
    });
  }, url, method, data);
};

/**
 * Refreshes actual page.
 *
 * @method refresh
 * @return {Promise} Promise resolving when the page is fully loaded
 */
Page.prototype.refresh = function() {
  var self = this;

  return browser.refresh().then(function() {
    self.bodyElement.allowAnimations(false);
    return self.onLoaded();
  }).then(function() {
    return protractor.promise.fulfilled();
  });
};

/**
 * Handles page loaded.
 *
 * Use this method to perform actions after the page is loaded. Typically, verify that the page is loaded by
 * waiting for elements to be present on the page.
 *
 * By default it does nothing, override it to define your own behaviour.
 *
 * @method onLoaded
 * @return {Promise} Promise resolving when the page is fully loaded
 */
Page.prototype.onLoaded = function() {};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Thu Mar 17 2016 17:00:48 GMT+0100 (CET)

module.exports = function(config) {
  var configuration = {

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      {pattern: 'api_keys.json', included: false},
      'node_modules/es6-promise/dist/es6-promise.js',
      'node_modules/axios/dist/axios.js',
      'src/*.js',
      'spec/*Spec.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'/*, 'coverage'*/],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS', 'Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    customLaunchers: {
      Chrome_travis: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    }

  };

  if (process.env.TRAVIS) {
    configuration.browsers = ['PhantomJS', 'Chrome_travis'];
  }

  config.set(configuration);
};
<commit_msg>Hm, forget Chrome on Travis<commit_after>// Karma configuration
// Generated on Thu Mar 17 2016 17:00:48 GMT+0100 (CET)

module.exports = function(config) {
  var configuration = {

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      {pattern: 'api_keys.json', included: false},
      'node_modules/es6-promise/dist/es6-promise.js',
      'node_modules/axios/dist/axios.js',
      'src/*.js',
      'spec/*Spec.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'/*, 'coverage'*/],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS', 'Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    customLaunchers: {
      Chrome_travis: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    }

  };

  if (process.env.TRAVIS) {
    configuration.browsers = ['PhantomJS' /*, 'Chrome_travis'*/];
  }

  config.set(configuration);
};
<|endoftext|>


<commit_before>var IMAGE_URLS = {
  CONDOM: "images/igmikc-map-icon-condom.png",
  EVENT: "images/igmikc-map-icon-event.png",
  TREATMENT: "images/igmikc-map-icon-treatment.png"
};
var DEFAULT_MAP_CENTER = {
  LAT: 39.0397266,
  LNG: -94.5785667
};
var POINT_TYPE = {
  CONDOM: 'condom',
  EVENT: 'event',
  TREATMENT: 'treatment'
};
var map;

function mobileAndTabletcheck() {
  var check = false;
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  return check;
}
function showMap (center) {
  map = new google.maps.Map(document.getElementById('googleMap'), {
    center:center,
    zoom:11,
    scrollwheel:false,
    draggable:true,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  });

  // Create a


<commit_before>/**
 * @author Your Name
 * @copyright Your office or the organisation that pays you
 * @license MIT license
 */

/**
 * @requires sMap/Module.js
 */

sMap.WebParams = OpenLayers.Class({

	initialize : function(map) {
		this.map = map;
	},

	/**
	 * Shortened function name...
	 * @returns {String}
	 */
	getParams : function() {
		return this.getParamsAsString();
	},
	/**
	 * Make CGI-parameters which can recreate the current map.
	 * Other modules can listen to the event "creatingwebparams"
	 * and add their own parameters. They can
	 * access the params from the object sMap.db.webParams
	 *
	 * @param prependDomain {Boolean} If true - prepend the root URL with a "?"
	 * 		before the params.
	 * @returns {String} key=value&key2=value2
	 */
	getParamsAsString : function(prependDomain) {
		var webParamsObj = this.getParamsAsObject(),
			webParams = "",
			key = null,
			val = null;
		for (key in webParamsObj) {
			val = webParamsObj[key];
			webParams = webParams + "&" + key.toLowerCase()+"="+val;
		}
		webParams = webParams.substring(1); // Remove starting "&"

		if (prependDomain === true) {
			webParams = sMap.config.rootURL + "?" + webParams;
		}

		return webParams;
	},

	/**
	 * Make CGI-parameters which can recreate the current map.
	 * Other modules can listen to the event "creatingwebparams"
	 * and add their own parameters. They can
	 * access the params from the object sMap.db.webParams .
	 *
	 * @returns {Object} {key : value, key2 : value2}
	 */
	getParamsAsObject : function() {

		var obj = {};
		var orgParams = OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters());

		// Get center
		var p = this.map.getCenter();
		var center = obj.CENTER = [p.lon, p.lat];

		// Get zoom
		var zoom = obj.ZOOM = this.map.getZoom();

		// Get layers
		var layers = sMap.config.layers.overlays;
		for (var i=0,len=layers.length; i<len; i++) {
			var t = layers[i];
			var layer = t && t.name && this.map.getLayersByName(t.name).length ? this.map.getLayersByName(t.name)[0] : null;
			if (layer && layer.getVisibility()===true) {
				if (!obj.OL) {
					obj.OL = [];
				}
				if ($.inArray(layer.name, obj.OL) == -1) {
					// Append layerName if it does not exist.
					obj.OL.push(layer.name);
				}
			}
		}
		layers = sMap.config.layers.baselayers;
		for (var i=0,len=layers.length; i<len; i++) {
			var t = layers[i];
			var layer = this.map.getLayersByName(t.name)[0];
			if (layer && layer.getVisibility()===true) {
				obj.BL = layer.name;
				break;
			}
		}

		// Get width and height of map (if provided)
		if (orgParams.WIDTH) {
			obj.WIDTH = orgParams.WIDTH;
		}
		if (orgParams.HEIGHT) {
			obj.HEIGHT = orgParams.HEIGHT;
		}

		// Get language code if it was sent in from start OR if
		// current code is different than default.
		var code = sMap.Lang.getCode();
		if (orgParams.LANG || (code != sMap.Lang.defaultCode)) {
			obj.LANG = code;
		}
		if (orgParams.CONFIG) {
			obj.CONFIG = orgParams.CONFIG;
		}

		sMap.db.webParams = obj;

		// Listeners to this event must access the params object through
		// sMap.db.webParams and add its own parameters like:
		// sMap.db.webParams.MYPARAMETER = ["one", "two"];
		// The key does not have to be in upper-case (it will be made automatically below).

		sMap.events.triggerEvent("creatingwebparams", this, {} );

		// By now all listeners have added their own parameters. Lets make them upper-case.
		sMap.db.webParams = OpenLayers.Util.upperCaseObject(sMap.db.webParams);

		return sMap.db.webParams;
	},

	/**
	 * Get the URL the user called the map with the last time.
	 * @returns {Object} {key : value, key2 : value2}
	 */
	getStartingParamsAsObject : function() {
		return OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters());
	},

	/**
	 * Pre-process params in order to:
	 * 	- support older APIs
	 *
	 * @param params {Object}
	 * @returns {void}
	 */
	processParams: function(params) {
		params = params || {};
		params = $.extend({}, params);

		if (params.MAPTYPE) {
			params.BL = params.MAPTYPE;
			delete params.MAPTYPE;
		}
		if (params.OVERLAYS) {
			params.OL = params.OVERLAYS;
			delete params.OVERLAYS;
		}
		if (params.ZOOMLEVEL) {
			params.ZOOM = params.ZOOMLEVEL;
			delete params.ZOOMLEVEL;
		}
		if (params.ADDMARKER) {
			params.FEATURES = params.ADDMARKER.replace(/=/g, "%3D");
			delete params.ADDMARKER;
		}
		return params;
	},

	/**
	 * Apply parameters to the map. Modules can listen to the
	 * event "beforeapplyingwebparams" or "afterapplyingwebparams"
	 * and add apply their parameters as they like. 'Before' and 'after'
	 * points to the time before and after applying default parameters
	 * (i.e. parameters defined in this class, like zoom, center).
	 *
	 * Modules can access the params from the object sMap.db.webParamsObj .
	 *
	 * @param params {String || Object}
	 *     Params to apply on the map (without reloading it).
	 *     Note! If params is of type "object" keys must be upper-case.
	 */
	applyParams : function(params) {
		params = params || this.getStartingParamsAsObject();

		params = this.processParams(params);

		if (typeof params == "string") {
			params = OpenLayers.Util.upperCaseObject(params);
		}
		sMap.db.startingWebParamsObject = params;
		sMap.events.triggerEvent("beforeapplyingwebparams", this, {} );

		this.applyDefaultParams(params);

		sMap.events.triggerEvent("afterapplyingwebparams", this, {
			params: params
		});
	},

	/**
	 * Apply default parameters.
	 *
	 * @param paramsObj {Object}
	 * @returns
	 */
	applyDefaultParams : function(paramsObj) {
		paramsObj = paramsObj || this.getParamsAsObject();

		this.map.zoomToMaxExtent();

		var zoom = parseInt(paramsObj.ZOOM);
		if (zoom && zoom > 0) {
			this.map.zoomTo(zoom);
		}
		if (paramsObj.LANG) {
			sMap.Lang.setCode(paramsObj.LANG || "sv-SE");
		}
		if (paramsObj.CENTER) {
			if (typeof paramsObj.CENTER === "string") {
				paramsObj.CENTER = paramsObj.CENTER.split(",");
			}
			this.map.setCenter(new OpenLayers.LonLat(parseFloat(paramsObj.CENTER[0]), parseFloat(paramsObj.CENTER[1])), null, false, false);
		}

		if (paramsObj.BL) { //&& this.map.getLayersByName(paramsObj.BL).length) {
			this.map.setBaseLayer(paramsObj.BL);
		}
		if (paramsObj.OL) {
			var olArr = paramsObj.OL instanceof Array ? paramsObj.OL : paramsObj.OL.split(","),
				arrLayersToAdd = [];
			for (var i=0,len=olArr.length; i<len; i++) {
				var layerName = olArr[i];
				var t = sMap.cmd.getLayerConfig(layerName);
				if (!t) {
					debug.warn(sMap.lang.errWebParamLayerNotFound);
				}
				else {
					t.startVisible = true;
					arrLayersToAdd.push(t);
				}
			}
			sMap.layer.addOverlays(arrLayersToAdd);
		}

		if (this.map.allOverlays===true && !paramsObj.BL && !paramsObj.OL) {
			// Add the first overlay.
			var overlays = sMap.config.layers.overlays;
			if (!overlays || !overlays.length) {
				// No baselayers nor overlays => problem!
				debug.error(sMap.lang.errNoBaseNorOverlays);
				return;
			}
			var t = overlays[0];
			t.startVisible = true;
			sMap.layer.addOverlays([t]);
		}

		/*
		 * If no zoom or center provided - zoom to default extent.
		 */
		if (!paramsObj.ZOOM && !paramsObj.CENTER) {
			var b = sMap.config.defaultExtent;
			if (b)
				this.map.zoomToExtent(new OpenLayers.Bounds(b.w, b.s, b.e, b.n), false);
			else
				this.map.zoomToMaxExtent();
		}
	},

	CLASS_NAME : "sMap.WebParams"

});

<commit_msg>#21 OL=all&buffer=3<commit_after>/**
 * @author Your Name
 * @copyright Your office or the organisation that pays you
 * @license MIT license
 */

/**
 * @requires sMap/Module.js
 */

sMap.WebParams = OpenLayers.Class({

	initialize : function(map) {
		this.map = map;
	},

	/**
	 * Shortened function name...
	 * @returns {String}
	 */
	getParams : function() {
		return this.getParamsAsString();
	},
	/**
	 * Make CGI-parameters which can recreate the current map.
	 * Other modules can listen to the event "creatingwebparams"
	 * and add their own parameters. They can
	 * access the params from the object sMap.db.webParams
	 *
	 * @param prependDomain {Boolean} If true - prepend the root URL with a "?"
	 * 		before the params.
	 * @returns {String} key=value&key2=value2
	 */
	getParamsAsString : function(prependDomain) {
		var webParamsObj = this.getParamsAsObject(),
			webParams = "",
			key = null,
			val = null;
		for (key in webParamsObj) {
			val = webParamsObj[key];
			webParams = webParams + "&" + key.toLowerCase()+"="+val;
		}
		webParams = webParams.substring(1); // Remove starting "&"

		if (prependDomain === true) {
			webParams = sMap.config.rootURL + "?" + webParams;
		}

		return webParams;
	},

	/**
	 * Make CGI-parameters which can recreate the current map.
	 * Other modules can listen to the event "creatingwebparams"
	 * and add their own parameters. They can
	 * access the params from the object sMap.db.webParams .
	 *
	 * @returns {Object} {key : value, key2 : value2}
	 */
	getParamsAsObject : function() {

		var obj = {};
		var orgParams = OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters());

		// Get center
		var p = this.map.getCenter();
		var center = obj.CENTER = [p.lon, p.lat];

		// Get zoom
		var zoom = obj.ZOOM = this.map.getZoom();

		// Get layers
		var layers = sMap.config.layers.overlays;
		for (var i=0,len=layers.length; i<len; i++) {
			var t = layers[i];
			var layer = t && t.name && this.map.getLayersByName(t.name).length ? this.map.getLayersByName(t.name)[0] : null;
			if (layer && layer.getVisibility()===true) {
				if (!obj.OL) {
					obj.OL = [];
				}
				if ($.inArray(layer.name, obj.OL) == -1) {
					// Append layerName if it does not exist.
					obj.OL.push(layer.name);
				}
			}
		}
		layers = sMap.config.layers.baselayers;
		for (var i=0,len=layers.length; i<len; i++) {
			var t = layers[i];
			var layer = this.map.getLayersByName(t.name)[0];
			if (layer && layer.getVisibility()===true) {
				obj.BL = layer.name;
				break;
			}
		}

		// Get width and height of map (if provided)
		if (orgParams.WIDTH) {
			obj.WIDTH = orgParams.WIDTH;
		}
		if (orgParams.HEIGHT) {
			obj.HEIGHT = orgParams.HEIGHT;
		}

		// Get language code if it was sent in from start OR if
		// current code is different than default.
		var code = sMap.Lang.getCode();
		if (orgParams.LANG || (code != sMap.Lang.defaultCode)) {
			obj.LANG = code;
		}
		if (orgParams.CONFIG) {
			obj.CONFIG = orgParams.CONFIG;
		}

		sMap.db.webParams = obj;

		// Listeners to this event must access the params object through
		// sMap.db.webParams and add its own parameters like:
		// sMap.db.webParams.MYPARAMETER = ["one", "two"];
		// The key does not have to be in upper-case (it will be made automatically below).

		sMap.events.triggerEvent("creatingwebparams", this, {} );

		// By now all listeners have added their own parameters. Lets make them upper-case.
		sMap.db.webParams = OpenLayers.Util.upperCaseObject(sMap.db.webParams);

		return sMap.db.webParams;
	},

	/**
	 * Get the URL the user called the map with the last time.
	 * @returns {Object} {key : value, key2 : value2}
	 */
	getStartingParamsAsObject : function() {
		return OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters());
	},

	/**
	 * Pre-process params in order to:
	 * 	- support older APIs
	 *
	 * @param params {Object}
	 * @returns {void}
	 */
	processParams: function(params) {
		params = params || {};
		params = $.extend({}, params);

		if (params.MAPTYPE) {
			params.BL = params.MAPTYPE;
			delete params.MAPTYPE;
		}
		if (params.OVERLAYS) {
			params.OL = params.OVERLAYS;
			delete params.OVERLAYS;
		}
		if (params.ZOOMLEVEL) {
			params.ZOOM = params.ZOOMLEVEL;
			delete params.ZOOMLEVEL;
		}
		if (params.ADDMARKER) {
			params.FEATURES = params.ADDMARKER.replace(/=/g, "%3D");
			delete params.ADDMARKER;
		}
		return params;
	},

	/**
	 * Apply parameters to the map. Modules can listen to the
	 * event "beforeapplyingwebparams" or "afterapplyingwebparams"
	 * and add apply their parameters as they like. 'Before' and 'after'
	 * points to the time before and after applying default parameters
	 * (i.e. parameters defined in this class, like zoom, center).
	 *
	 * Modules can access the params from the object sMap.db.webParamsObj .
	 *
	 * @param params {String || Object}
	 *     Params to apply on the map (without reloading it).
	 *     Note! If params is of type "object" keys must be upper-case.
	 */
	applyParams : function(params) {
		params = params || this.getStartingParamsAsObject();

		params = this.processParams(params);

		if (typeof params == "string") {
			params = OpenLayers.Util.upperCaseObject(params);
		}
		sMap.db.startingWebParamsObject = params;
		sMap.events.triggerEvent("beforeapplyingwebparams", this, {} );

		this.applyDefaultParams(params);

		sMap.events.triggerEvent("afterapplyingwebparams", this, {
			params: params
		});
	},

	/**
	 * Apply default parameters.
	 *
	 * @param paramsObj {Object}
	 * @returns
	 */
	applyDefaultParams : function(paramsObj) {
		paramsObj = paramsObj || this.getParamsAsObject();

		this.map.zoomToMaxExtent();

		var zoom = parseInt(paramsObj.ZOOM);
		if (zoom && zoom > 0) {
			this.map.zoomTo(zoom);
		}
		if (paramsObj.LANG) {
			sMap.Lang.setCode(paramsObj.LANG || "sv-SE");
		}
		if (paramsObj.CENTER) {
			if (typeof paramsObj.CENTER === "string") {
				paramsObj.CENTER = paramsObj.CENTER.split(",");
			}
			this.map.setCenter(new OpenLayers.LonLat(parseFloat(paramsObj.CENTER[0]), parseFloat(paramsObj.CENTER[1])), null, false, false);
		}

		if (paramsObj.BL) { //&& this.map.getLayersByName(paramsObj.BL).length) {
			this.map.setBaseLayer(paramsObj.BL);
		}
		if (paramsObj.OL) {
			var olArr = paramsObj.OL instanceof Array ? paramsObj.OL : paramsObj.OL.split(","),
				arrLayersToAdd = [];
			if (paramsObj.OL == "all"){
				for (var i=0,len=sMap.config.layers.overlays.length; i<len; i++){
					var t = sMap.config.layers.overlays[i];
					t.startVisible = true;
					if (paramsObj.BUFFER){
						t.options.buffer = paramsObj.BUFFER;
					}
					arrLayersToAdd.push(t);
				}
			} else {
				for (var i=0,len=olArr.length; i<len; i++) {
					var layerName = olArr[i];
					var t = sMap.cmd.getLayerConfig(layerName);
					if (!t) {
						debug.warn(sMap.lang.errWebParamLayerNotFound);
					}
					else {
						t.startVisible = true;
						if (paramsObj.BUFFER){
							t.options.buffer = paramsObj.BUFFER;
						}
						arrLayersToAdd.push(t);
					}
				}
			}
			sMap.layer.addOverlays(arrLayersToAdd);
		}

		if (this.map.allOverlays===true && !paramsObj.BL && !paramsObj.OL) {
			// Add the first overlay.
			var overlays = sMap.config.layers.overlays;
			if (!overlays || !overlays.length) {
				// No baselayers nor overlays => problem!
				debug.error(sMap.lang.errNoBaseNorOverlays);
				return;
			}
			var t = overlays[0];
			t.startVisible = true;
			sMap.layer.addOverlays([t]);
		}

		/*
		 * If no zoom or center provided - zoom to default extent.
		 */
		if (!paramsObj.ZOOM && !paramsObj.CENTER) {
			var b = sMap.config.defaultExtent;
			if (b){
				this.map.zoomToExtent(new OpenLayers.Bounds(b.w, b.s, b.e, b.n), false);
			} else {
				this.map.zoomToMaxExtent();
			}
		}
	},

	CLASS_NAME : "sMap.WebParams"

});

<|endoftext|>


<commit_before>import resource from 'resource-router-middleware';
import music from '../models/music';

export default resource({
    mergeParams: true,

	/** Property name to store preloaded entity on `request`. */
	id : 'music',

	/** For requests with an `id`, you can auto-load the entity.
	 *  Errors terminate the request, success sets `req[id] = data`.
	 */

	load(req, id, callback) {
		var mus = music.find( mus => mus.id==id ),
		  err = mus ? null : 'Not found';

		callback(err, mus);
	},

	/** GET / - List all entities */
	index({ params }, res) {
        var mus = music.find( m => m.cat_id==params.id )

		res.json(mus);
	},

	/** POST / - Create a new entity */
	create({ body }, res) {
		body.id = music.length.toString(36);
		music.push(body);
		res.json(body);
	},

	/** GET /:id - Return a given entity */
	read(req, res) {
		res.json(req.music);
	},

	/** PUT /:id - Update a given entity */
	update({ facet, body }, res) {
		for (let key in body) {
			if (key!=='id') {
				facet[key] = body[key];
			}
		}
		res.sendStatus(204);
	},

	/** DELETE /:id - Delete a given entity */
	delete({ facet }, res) {
		music.splice(music.indexOf(facet), 1);
		res.sendStatus(204);
	}
});
<commit_msg>Fixed multiple music select issue<commit_after>import resource from 'resource-router-middleware';
import music from '../models/music';

export default resource({
    mergeParams: true,

	/** Property name to store preloaded entity on `request`. */
	id : 'music',

	/** For requests with an `id`, you can auto-load the entity.
	 *  Errors terminate the request, success sets `req[id] = data`.
	 */

	load(req, id, callback) {
		var mus = music.find( mus => mus.id==id ),
		  err = mus ? null : 'Not found';

		callback(err, mus);
	},

	/** GET / - List all entities */
	index({ params }, res) {
        //var mus = music.find( m => m.cat_id==params.id )
        var mus = []
        for (var value of music) {
            if(value.cat_id == params.id){
                mus.push(value);
            }
        }

		res.json(mus);
	},

	/** POST / - Create a new entity */
	create({ body }, res) {
		body.id = music.length.toString(36);
		music.push(body);
		res.json(body);
	},

	/** GET /:id - Return a given entity */
	read(req, res) {
		res.json(req.music);
	},

	/** PUT /:id - Update a given entity */
	update({ facet, body }, res) {
		for (let key in body) {
			if (key!=='id') {
				facet[key] = body[key];
			}
		}
		res.sendStatus(204);
	},

	/** DELETE /:id - Delete a given entity */
	delete({ facet }, res) {
		music.splice(music.indexOf(facet), 1);
		res.sendStatus(204);
	}
});
<|endoftext|>


<commit_before>"use strict";

var http = require("http");
var https = require("https");
var parseObject = require("./parseobject");

/**
 * littlerequester
 * Make an HTTP/HTTPS request and return
 *
 *@name littlerequester
 *@function
 *@param {Object} options An object with the following fields:
 * - "url" (String): Request url
 * - "type" (String): Return data type either json or raw
 * - "headers" (Object): Object with header to use in request (ex: user-agent)
 *@return {Promise} Return a promise
 */

function littlerequester(options) {
	return new Promise((resolve, reject) => {
    try {
      if (typeof options != "object") {
        reject("Your options is not an Object");
      }

      if (!options.type) {
        options.type = "raw";
      }

      options = parseObject(options);

      (options.request.protocol.includes("http:") ? http : https).request(options.request, res => {
        res.setEncoding("utf-8");
        var data = '';

        res.on("data", chunk => {
        	data += chunk.toString();
        }).on("error", e => {
                reject(e);
        }).on("end", () => {
          if(options.type.toLowerCase() === "raw") {
            resolve({data: data, res:res});
          }
          else if (options.type.toLowerCase() === "json") {
            try {
              var json = JSON.parse(data);
              resolve({data: json, res:res});
            }
            catch (e) {
              reject(e);
            }
          }
          else {
            resolve({data: data, res:res});
          }
        });

      }).on("error", e => {
        reject(e);
      }).end();
    }
    catch (e) {
      reject(e);
    }
	});
}

module.exports = littlerequester;
<commit_msg>fix weird indent<commit_after>"use strict";

var http = require("http");
var https = require("https");
var parseObject = require("./parseobject");

/**
 * littlerequester
 * Make an HTTP/HTTPS request and return
 *
 *@name littlerequester
 *@function
 *@param {Object} options An object with the following fields:
 * - "url" (String): Request url
 * - "type" (String): Return data type either json or raw
 * - "headers" (Object): Object with header to use in request (ex: user-agent)
 *@return {Promise} Return a promise
 */

function littlerequester(options) {
  return new Promise((resolve, reject) => {
    try {
      if (typeof options != "object") {
        reject("Your options is not an Object");
      }

      if (!options.type) {
        options.type = "raw";
      }

      options = parseObject(options);

      (options.request.protocol.includes("http:") ? http : https).request(options.request, res => {
        res.setEncoding("utf-8");
        var data = '';

        res.on("data", chunk => {
        	data += chunk.toString();
        }).on("error", e => {
                reject(e);
        }).on("end", () => {
          if(options.type.toLowerCase() === "raw") {
            resolve({data: data, res:res});
          }
          else if (options.type.toLowerCase() === "json") {
            try {
              var json = JSON.parse(data);
              resolve({data: json, res:res});
            }
            catch (e) {
              reject(e);
            }
          }
          else {
            resolve({data: data, res:res});
          }
        });

      }).on("error", e => {
        reject(e);
      }).end();
    }
    catch (e) {
      reject(e);
    }
  });
}

module.exports = littlerequester;
<|endoftext|>


<commit_before>var width = 960, height = 500, centered;

var vehicleCounts = d3.map(), fipsCodes = d3.map(), stateMap = d3.map();

var projection = d3.geo.albersUsa()
    .scale(width)
    .translate([width / 2, height / 2]);

var path = d3.geo.path().projection(projection);

queue()
    .defer(d3.json, "data/us.json")
    .defer(d3.csv, "data/US_FIPS_Codes.csv", function(d) {
      fipsCodes.set(d.stateNumber.replace(/^0/, '') + d.countyNumber, {
        stateName: d.state,
        stateNumber: d.stateNumber,
        countyName: d.county
      });
    })
    .defer(d3.csv, "cyclemake.php?class=Motorcycle&make=", function(d) { vehicleCounts.set(d.fips, +d.data); })
    .await(ready);

var map, legend, g, legendTitle = "# of motorcycles for sale";

function ready(error, us) {
  us = us[0];
  $("#huge-map").html("");
  map = d3.select("#huge-map").append("svg")
      .attr("width", width)
      .attr("height", height);

  map.append("rect")
      .attr("class", "background")
      .attr("width", width)
      .attr("height", height)
      .on("click", mapClick);

  legend = d3.select("#huge-map").append("svg")
      .attr("id", "legend")
      .attr("width", "100%")
      .attr("height", 50);

  g = map.append("g");

  var vehicleCountColor = d3.scale.log()
      .domain([1, d3.max(vehicleCounts.values())])
      .interpolate(d3.interpolateHsl)
      .nice(10)
      .base(2)
      .range([d3.hsl(210, 1, 0.95), d3.hsl(210, 1, 0.05)]);

  g.append("g")
      .attr("class", "states")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.states).features)
    .enter().append("path")
      .attr("d", path)
      .attr("stateId", function(d) { stateMap.set(d.id, d); return d.id; });

  g.append("g")
      .attr("class", "counties")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.counties).features)
    .enter().append("path")
      .style("fill", function(d) { return vehicleCountColor(+vehicleCounts.get(d.id)); })
      .attr("d", path)
      .attr("stateId", function(d) {
        var fips = fipsCodes.get(d.id);
        return fips ? fips.stateNumber.replace(/^0/, '') : null;
      })
      .attr("countyId", function(d) { return d.id; });

  g.append("g")
      .attr("class", "countiesOverlay")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.counties).features)
    .enter().append("path")
      .attr("d", path)
      .attr("stateId", function(d) {
        var fips = fipsCodes.get(d.id);
        return fips ? fips.stateNumber.replace(/^0/, '') : null;
      })
      .attr("countyId", function(d) { return d.id; })
      .on("click", mapClick)
      .on("mouseover", function() {
        var element = d3.selectAll('[stateId="' + d3.select(this).attr("stateId") + '"]');
        var elementClass = element.attr("class");
        if (elementClass !== "countiesOverlay stateZoomed") {
          element.attr("class", "countiesOverlay stateActive");
        }
      })
      .on("mouseout", function() {
        var element = d3.selectAll('[stateId="' + d3.select(this).attr("stateId") + '"]');
        var elementClass = element.attr("class");
        if (elementClass !== "countiesOverlay stateZoomed") {
          element.attr("class", centered ? "countiesOverlay stateInactive" : "countiesOverlay");
        }
      });

  g.append("path")
      .datum(topojson.mesh(us, us.objects.states))
      .attr("class", "state-borders")
      .attr("d", path);

  colorlegend("#legend", vehicleCountColor, "log", {title: legendTitle});

  if ($('#collapse-data-more').is(':visible')) {
      generateChart();
  }
}

function mapClick(d) {
  var x, y, k;
  var stateId = d3.select(this).attr("stateId");
  var state = stateMap.get(stateId);

  if (d && centered !== state) {
    var centroid = path.centroid(state), bounds = path.bounds(state);
    x = centroid[0];
    y = centroid[1];
    k = 0.75 / Math.max((bounds[1][0] - bounds[0][0]) / width, (bounds[1][1] - bounds[0][1]) / height);
    centered = state;
    d3.selectAll('.countiesOverlay:not([stateId="' + stateId + '"])').attr("class", "countiesOverlay stateInactive");
    d3.selectAll('.countiesOverlay[stateId="' + stateId + '"]').attr("class", "countiesOverlay stateZoomed");
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
    d3.selectAll(".countiesOverlay").attr("class", "countiesOverlay");
  }

  g.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")");
}
<commit_msg>Who the hell knows...<commit_after>var width = 960, height = 500, centered;

var vehicleCounts = d3.map(), fipsCodes = d3.map(), stateMap = d3.map();

var projection = d3.geo.albersUsa()
    .scale(width)
    .translate([width / 2, height / 2]);

var path = d3.geo.path().projection(projection);

queue()
    .defer(d3.json, "data/us.json")
    .defer(d3.csv, "data/US_FIPS_Codes.csv", function(d) {
      fipsCodes.set(d.stateNumber.replace(/^0/, '') + d.countyNumber, {
        stateName: d.state,
        stateNumber: d.stateNumber,
        countyName: d.county
      });
    })
    .defer(d3.csv, "cyclemake.php?class=Motorcycle&make=", function(d) { vehicleCounts.set(d.fips, +d.data); })
    .await(ready);

var map, legend, g, legendTitle = "# of motorcycles for sale";

function ready(error, us) {
  $("#huge-map").html("");
  map = d3.select("#huge-map").append("svg")
      .attr("width", width)
      .attr("height", height);

  map.append("rect")
      .attr("class", "background")
      .attr("width", width)
      .attr("height", height)
      .on("click", mapClick);

  legend = d3.select("#huge-map").append("svg")
      .attr("id", "legend")
      .attr("width", "100%")
      .attr("height", 50);

  g = map.append("g");

  var vehicleCountColor = d3.scale.log()
      .domain([1, d3.max(vehicleCounts.values())])
      .interpolate(d3.interpolateHsl)
      .nice(10)
      .base(2)
      .range([d3.hsl(210, 1, 0.95), d3.hsl(210, 1, 0.05)]);

  g.append("g")
      .attr("class", "states")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.states).features)
    .enter().append("path")
      .attr("d", path)
      .attr("stateId", function(d) { stateMap.set(d.id, d); return d.id; });

  g.append("g")
      .attr("class", "counties")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.counties).features)
    .enter().append("path")
      .style("fill", function(d) { return vehicleCountColor(+vehicleCounts.get(d.id)); })
      .attr("d", path)
      .attr("stateId", function(d) {
        var fips = fipsCodes.get(d.id);
        return fips ? fips.stateNumber.replace(/^0/, '') : null;
      })
      .attr("countyId", function(d) { return d.id; });

  g.append("g")
      .attr("class", "countiesOverlay")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.counties).features)
    .enter().append("path")
      .attr("d", path)
      .attr("stateId", function(d) {
        var fips = fipsCodes.get(d.id);
        return fips ? fips.stateNumber.replace(/^0/, '') : null;
      })
      .attr("countyId", function(d) { return d.id; })
      .on("click", mapClick)
      .on("mouseover", function() {
        var element = d3.selectAll('[stateId="' + d3.select(this).attr("stateId") + '"]');
        var elementClass = element.attr("class");
        if (elementClass !== "countiesOverlay stateZoomed") {
          element.attr("class", "countiesOverlay stateActive");
        }
      })
      .on("mouseout", function() {
        var element = d3.selectAll('[stateId="' + d3.select(this).attr("stateId") + '"]');
        var elementClass = element.attr("class");
        if (elementClass !== "countiesOverlay stateZoomed") {
          element.attr("class", centered ? "countiesOverlay stateInactive" : "countiesOverlay");
        }
      });

  g.append("path")
      .datum(topojson.mesh(us, us.objects.states))
      .attr("class", "state-borders")
      .attr("d", path);

  colorlegend("#legend", vehicleCountColor, "log", {title: legendTitle});

  if ($('#collapse-data-more').is(':visible')) {
      generateChart();
  }
}

function mapClick(d) {
  var x, y, k;
  var stateId = d3.select(this).attr("stateId");
  var state = stateMap.get(stateId);

  if (d && centered !== state) {
    var centroid = path.centroid(state), bounds = path.bounds(state);
    x = centroid[0];
    y = centroid[1];
    k = 0.75 / Math.max((bounds[1][0] - bounds[0][0]) / width, (bounds[1][1] - bounds[0][1]) / height);
    centered = state;
    d3.selectAll('.countiesOverlay:not([stateId="' + stateId + '"])').attr("class", "countiesOverlay stateInactive");
    d3.selectAll('.countiesOverlay[stateId="' + stateId + '"]').attr("class", "countiesOverlay stateZoomed");
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
    d3.selectAll(".countiesOverlay").attr("class", "countiesOverlay");
  }

  g.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")");
}
<|endoftext|>


<commit_before>var _ = require('lodash');

module.exports = exports = {
	Link: require('./Link'),
	Field: require('./Field'),
	Accessor: require('./Accessor'),
	Response: require('./Response'),
	Resource: require('./Resource'),
	Transaction: require('./Transaction'),
	ResourceView: require('./ResourceView'),
	middleware: require('./middleware'),
	accessors: require('./accessors'),
	selectors: require('./selectors'),
	filters: require('./filters'),
	errors: require('./errors'),
};

_.merge(exports, exports.errors);
_.merge(exports, exports.filters);
_.merge(exports, exports.accessors);
_.merge(exports, exports.selectors);
_.merge(exports, exports.middleware);
<commit_msg>Forgot to require Registry in lib/index.js<commit_after>var _ = require('lodash');

module.exports = exports = {
	Registry: require('./Registry'),
	Link: require('./Link'),
	Field: require('./Field'),
	Accessor: require('./Accessor'),
	Response: require('./Response'),
	Resource: require('./Resource'),
	Transaction: require('./Transaction'),
	ResourceView: require('./ResourceView'),
	middleware: require('./middleware'),
	accessors: require('./accessors'),
	selectors: require('./selectors'),
	filters: require('./filters'),
	errors: require('./errors'),
};

_.merge(exports, exports.errors);
_.merge(exports, exports.filters);
_.merge(exports, exports.accessors);
_.merge(exports, exports.selectors);
_.merge(exports, exports.middleware);
<|endoftext|>


<commit_before><commit_msg>Underscore is now used as a bower component<commit_after><|endoftext|>


<commit_before>'use strict';

var webdriverConfig = {
    hostname: 'fe.nhnent.com',
    port: 4444,
    remoteHost: true
};

/**
 * manipulate config by server
 * @param {Object} defaultConfig - base configuration
 * @param {'ne'|null|undefined} server - ne: team selenium grid, null or undefined: local machine
 */
function setConfig(defaultConfig, server) {
    if (server === 'ne') {
        defaultConfig.customLaunchers = {
            'IE8': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '8'
            },
            'IE9': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '9'
            },
            'IE10': {
                base: 'WebDriver',
                browserName: 'internet explorer',
                config: webdriverConfig,
                version: '10'
            },
            'IE11': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '11'
            },
            'Edge': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'MicrosoftEdge'
            },
            'Chrome-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'chrome'
            },
            'Firefox-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'firefox'
            },
            'Safari-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'safari'
            }
        };
        defaultConfig.browsers = [
            'IE8',
            'IE9',
            'IE10',
            'IE11',
            'Edge',
            'Chrome-WebDriver',
            'Firefox-WebDriver',
            'Safari-WebDriver'
        ];
        defaultConfig.reporters.push('coverage');
        defaultConfig.reporters.push('junit');
        defaultConfig.coverageReporter = {
            dir: 'report/coverage/',
            reporters: [{
                type: 'html',
                subdir: function(browser) {
                    return 'report-html/' + browser;
                }
            },
            {
                type: 'cobertura',
                subdir: function(browser) {
                    return 'report-cobertura/' + browser;
                },
                file: 'cobertura.txt'
            }
            ]
        };
        defaultConfig.junitReporter = {
            outputDir: 'report',
            suite: ''
        };
    } else {
        defaultConfig.browsers = [
            'ChromeHeadless'
        ];
    }
}

module.exports = function(config) {
    var defaultConfig = {
        basePath: './',
        frameworks: ['jasmine'],
        files: [
            'test/*.test.js'
        ],
        preprocessors: {
            './test/*.test.js': ['webpack', 'sourcemap']
        },
        reporters: ['dots'],
        webpack: {
            devtool: 'inline-source-map',
            module: {
                preLoaders: [
                    {
                        test: /\.js$/,
                        exclude: /(test|bower_components|node_modules)/,
                        loader: 'istanbul-instrumenter'
                    },
                    {
                        test: /\.js$/,
                        exclude: /(bower_components|node_modules)/,
                        loader: 'eslint-loader'
                    }
                ]
            }
        },

        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        singleRun: true
    };

    /* eslint-disable */
    setConfig(defaultConfig, process.env.KARMA_SERVER);
    config.set(defaultConfig);
};
<commit_msg>chore: add path of junit report on karma config file<commit_after>'use strict';

var webdriverConfig = {
    hostname: 'fe.nhnent.com',
    port: 4444,
    remoteHost: true
};

/**
 * manipulate config by server
 * @param {Object} defaultConfig - base configuration
 * @param {'ne'|null|undefined} server - ne: team selenium grid, null or undefined: local machine
 */
function setConfig(defaultConfig, server) {
    if (server === 'ne') {
        defaultConfig.customLaunchers = {
            'IE8': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '8'
            },
            'IE9': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '9'
            },
            'IE10': {
                base: 'WebDriver',
                browserName: 'internet explorer',
                config: webdriverConfig,
                version: '10'
            },
            'IE11': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '11'
            },
            'Edge': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'MicrosoftEdge'
            },
            'Chrome-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'chrome'
            },
            'Firefox-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'firefox'
            },
            'Safari-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'safari'
            }
        };
        defaultConfig.browsers = [
            'IE8',
            'IE9',
            'IE10',
            'IE11',
            'Edge',
            'Chrome-WebDriver',
            'Firefox-WebDriver',
            'Safari-WebDriver'
        ];
        defaultConfig.reporters.push('coverage');
        defaultConfig.reporters.push('junit');
        defaultConfig.coverageReporter = {
            dir: 'report/coverage/',
            reporters: [{
                type: 'html',
                subdir: function(browser) {
                    return 'report-html/' + browser;
                }
            },
            {
                type: 'cobertura',
                subdir: function(browser) {
                    return 'report-cobertura/' + browser;
                },
                file: 'cobertura.txt'
            }
            ]
        };
        defaultConfig.junitReporter = {
            outputDir: 'report/junit',
            suite: ''
        };
    } else {
        defaultConfig.browsers = [
            'ChromeHeadless'
        ];
    }
}

module.exports = function(config) {
    var defaultConfig = {
        basePath: './',
        frameworks: ['jasmine'],
        files: [
            'test/*.test.js'
        ],
        preprocessors: {
            './test/*.test.js': ['webpack', 'sourcemap']
        },
        reporters: ['dots'],
        webpack: {
            devtool: 'inline-source-map',
            module: {
                preLoaders: [
                    {
                        test: /\.js$/,
                        exclude: /(test|bower_components|node_modules)/,
                        loader: 'istanbul-instrumenter'
                    },
                    {
                        test: /\.js$/,
                        exclude: /(bower_components|node_modules)/,
                        loader: 'eslint-loader'
                    }
                ]
            }
        },

        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        singleRun: true
    };

    /* eslint-disable */
    setConfig(defaultConfig, process.env.KARMA_SERVER);
    config.set(defaultConfig);
};
<|endoftext|>