<commit_before>var TuitionCard = {
    name: 'TuitionCard',
    dom_target: undefined,

    render_init: function() {
        if (!window.user.student) {
            remove_card(TuitionCard.dom_target);
            return;
        }
        WSData.fetch_tuition_data(TuitionCard.render_upon_data,
                                  TuitionCard.render_error);
        WSData.fetch_notice_data(TuitionCard.render_upon_data,
                                 TuitionCard.render_error);
    },

    _has_all_data: function () {
        if (WSData.tuition_data() && WSData.notice_data()) {
            return true;
        }
        return false;
    },

    render_error: function (status) {
        // notice never returns 404.
        if (status === 404) {
            // not student or SDB can't find the regid
            remove_card(TuitionCard.dom_target);
            return;
        }
        var raw = CardWithError.render("Tuition & Fees");
        TuitionCard.dom_target.html(raw);
    },

    render_upon_data: function() {
        // Having multiple callbacks come to this function,
        // delay rendering until all requests are complete.
        if (!TuitionCard._has_all_data()) {
            return;
        }

        TuitionCard._render();
    },

    process_tuition: function(data) {
        var is_credit = false;
        if (data.match(" CR")) {
            is_credit = true;
            data = data.replace(" CR", "");
        }
        return {
            tuition: data,
            is_credit: is_credit
        };
    },

    _render: function () {
        var template_data = WSData.tuition_data(),
            tuition_due_notice,
            display_date,
            due_date,
            has_credit_values;

        template_data.pce_tuition_dup = Notices.get_notices_for_tag("pce_tuition_dup");

        if (template_data.pce_accbalance == '0.00') {
            template_data.pce_accbalance = 0;
        }
        template_data.is_grad = window.user.grad;
        template_data.is_pce = false;  // window.user.pce;
        template_data.is_tacoma = window.user.tacoma_affil;
        template_data.is_bothell = window.user.bothell_affil;
        template_data.is_seattle = window.user.seattle_affil;

        has_credit_values = TuitionCard.process_tuition(template_data.tuition_accbalance);
        template_data.plain_tuition = has_credit_values.tuition;
        template_data.is_credit = has_credit_values.is_credit;

        tuition_due_notice = Notices.get_notices_for_tag("tuition_due_date")[0];

        if (tuition_due_notice !== undefined) {
            for (var i = 0; i < tuition_due_notice.attributes.length; i += 1) {
                if (tuition_due_notice.attributes[i].name === "Date") {
                    due_date = new Date(tuition_due_notice.attributes[i].value.replace(/-/g, "/"));
                    display_date = tuition_due_notice.attributes[i].formatted_value;
                }
            }
        }
        if (due_date !== undefined) {
            template_data.tuition_date = display_date;
            template_data.tuition_date_offset = TuitionCard._days_from_today(due_date);

            //Alert banners
            if(parseFloat(template_data.tuition_accbalance) > 0){
                if(template_data.tuition_date_offset === 0){
                    template_data.due_today = true;
                }
                if (template_data.tuition_date_offset < 0){
                    template_data.past_due = true;
                }
            }
        }
        template_data.has_balance = parseInt(template_data.tuition_accbalance) > 0;
        var finaid_tags = ["tuition_aidhold_title",
                           "tuition_missingdocs_title",
                           "tuition_loanpromissory_title",
                           "tuition_loancounseling_title",
                           "tuition_acceptreject_title",
                           "tuition_disbursedateA_title",
                           "tuition_disbursedateB_title",
                           "tuition_direct_deposit_title",
                           "tuition_aid_prioritydate_title",
                           "tuition_aid_reminder_title",
                           "tuition_summeraid_date_title",
                           "tuition_summeraid_avail_title"
                          ];
        template_data.finaid_notices = Notices.get_ordered_finaid_notices(finaid_tags);
        var source = $("#tuition_card").html();
        var template = Handlebars.compile(source);
        var raw = template(template_data);
        TuitionCard.dom_target.html(raw);
        LogUtils.cardLoaded(TuitionCard.name, TuitionCard.dom_target);
        TuitionCard._init_events();
    },

    _days_from_today: function (date) {
        var today = new Date();
        return Math.ceil((date - today) / (1000*60*60*24));
    },

    _init_events: function(){
        $("body").on('click', ".collapsed", function(e){
            var content = $(e.target).parents('li').find('.finaid-panel-collapse');
            if(content.attr('aria-hidden')){
                content.attr('aria-hidden', false);
            } else{
                content.attr('aria-hidden', true);
            }
        });
    }
};

/* node.js exports */
if (typeof exports == "undefined") {
    var exports = {};
}
exports.TuitionCard = TuitionCard;
<commit_msg>more specific targeting in tuition.js<commit_after>var TuitionCard = {
    name: 'TuitionCard',
    dom_target: undefined,

    render_init: function() {
        if (!window.user.student) {
            remove_card(TuitionCard.dom_target);
            return;
        }
        WSData.fetch_tuition_data(TuitionCard.render_upon_data,
                                  TuitionCard.render_error);
        WSData.fetch_notice_data(TuitionCard.render_upon_data,
                                 TuitionCard.render_error);
    },

    _has_all_data: function () {
        if (WSData.tuition_data() && WSData.notice_data()) {
            return true;
        }
        return false;
    },

    render_error: function (status) {
        // notice never returns 404.
        if (status === 404) {
            // not student or SDB can't find the regid
            remove_card(TuitionCard.dom_target);
            return;
        }
        var raw = CardWithError.render("Tuition & Fees");
        TuitionCard.dom_target.html(raw);
    },

    render_upon_data: function() {
        // Having multiple callbacks come to this function,
        // delay rendering until all requests are complete.
        if (!TuitionCard._has_all_data()) {
            return;
        }

        TuitionCard._render();
    },

    process_tuition: function(data) {
        var is_credit = false;
        if (data.match(" CR")) {
            is_credit = true;
            data = data.replace(" CR", "");
        }
        return {
            tuition: data,
            is_credit: is_credit
        };
    },

    _render: function () {
        var template_data = WSData.tuition_data(),
            tuition_due_notice,
            display_date,
            due_date,
            has_credit_values;

        template_data.pce_tuition_dup = Notices.get_notices_for_tag("pce_tuition_dup");

        if (template_data.pce_accbalance == '0.00') {
            template_data.pce_accbalance = 0;
        }
        template_data.is_grad = window.user.grad;
        template_data.is_pce = false;  // window.user.pce;
        template_data.is_tacoma = window.user.tacoma_affil;
        template_data.is_bothell = window.user.bothell_affil;
        template_data.is_seattle = window.user.seattle_affil;

        has_credit_values = TuitionCard.process_tuition(template_data.tuition_accbalance);
        template_data.plain_tuition = has_credit_values.tuition;
        template_data.is_credit = has_credit_values.is_credit;

        tuition_due_notice = Notices.get_notices_for_tag("tuition_due_date")[0];

        if (tuition_due_notice !== undefined) {
            for (var i = 0; i < tuition_due_notice.attributes.length; i += 1) {
                if (tuition_due_notice.attributes[i].name === "Date") {
                    due_date = new Date(tuition_due_notice.attributes[i].value.replace(/-/g, "/"));
                    display_date = tuition_due_notice.attributes[i].formatted_value;
                }
            }
        }
        if (due_date !== undefined) {
            template_data.tuition_date = display_date;
            template_data.tuition_date_offset = TuitionCard._days_from_today(due_date);

            //Alert banners
            if(parseFloat(template_data.tuition_accbalance) > 0){
                if(template_data.tuition_date_offset === 0){
                    template_data.due_today = true;
                }
                if (template_data.tuition_date_offset < 0){
                    template_data.past_due = true;
                }
            }
        }
        template_data.has_balance = parseInt(template_data.tuition_accbalance) > 0;
        var finaid_tags = ["tuition_aidhold_title",
                           "tuition_missingdocs_title",
                           "tuition_loanpromissory_title",
                           "tuition_loancounseling_title",
                           "tuition_acceptreject_title",
                           "tuition_disbursedateA_title",
                           "tuition_disbursedateB_title",
                           "tuition_direct_deposit_title",
                           "tuition_aid_prioritydate_title",
                           "tuition_aid_reminder_title",
                           "tuition_summeraid_date_title",
                           "tuition_summeraid_avail_title"
                          ];
        template_data.finaid_notices = Notices.get_ordered_finaid_notices(finaid_tags);
        var source = $("#tuition_card").html();
        var template = Handlebars.compile(source);
        var raw = template(template_data);
        TuitionCard.dom_target.html(raw);
        LogUtils.cardLoaded(TuitionCard.name, TuitionCard.dom_target);
        TuitionCard._init_events();
    },

    _days_from_today: function (date) {
        var today = new Date();
        return Math.ceil((date - today) / (1000*60*60*24));
    },

    _init_events: function(){
        $("body").on('click', "#tui_finaid_notices_accordion a.collapsed", function(e){
            var content = $(e.target).parents('li').find('.finaid-panel-collapse');
            if(content.attr('aria-hidden')){
                content.attr('aria-hidden', false);
            } else{
                content.attr('aria-hidden', true);
            }
        });
    }
};

/* node.js exports */
if (typeof exports == "undefined") {
    var exports = {};
}
exports.TuitionCard = TuitionCard;
<|endoftext|>


<commit_before>/**
 * Created by Nicholas Hallahan <nhallahan@spatialdev.com>
 *     on Mon Mar 17 2014
 */

// global map object used for debugging only
m = {};

angular.module('GeoAngular').controller('MapCtrl', function ($scope, leafletData, Route, Alias, VectorProvider) {
  console.log('MapCtrl');

  var routeParams = Route.get();

  var lastLayersStr = '';
  $scope.blur = '';

  //Init activeTheme property
  $scope.activeTheme = "Projects";

  function setParams(routeParams) {
    if (routeParams.landing) {
      console.log('landing');
      $scope.blur = 'blur';
    } else {
      $scope.blur = '';
    }
    var lat = parseFloat(routeParams.lat) || 0;
    var lng = parseFloat(routeParams.lng) || 0;
    var zoom = parseFloat(routeParams.zoom) || 2;
    var layersStr = routeParams.layers;
    var layers = layersStr.split(',') || Alias.redcross;

    // first layer should always be treated as the basemap
    var basemap = Alias.find(layers[0]) || Alias.redcross;
    var overlays = layers.slice(1);

//    $scope.layers = {
//      overlays: {}
//    };

    if (lastLayersStr !== layersStr) {
      console.log('Setting layers.');
      if (Array.isArray(overlays) && overlays.length > 0)
        addOverlays(overlays);

      $scope.defaults = {
        scrollWheelZoom: true
      };

      $scope.tiles = {
        url: basemap
      };
    }

    $scope.center = {
      lat: lat,
      lng: lng,
      zoom: zoom
    };

    lastLayersStr = layersStr;
  }
  setParams(routeParams);

  $scope.$on('route-init', function (event, params) {
    setParams(params);
  });

  $scope.$on('route-update', function (event, params) {
    setParams(params);
  });

  $scope.$on('remove-blur', function (event) {
    $scope.blur = '';
  });

  leafletData.getMap().then(function (map) {
    m = map;
    map.on('moveend', function () { // move is good too
      var c = map.getCenter();
      var lat = parseFloat(c.lat.toFixed(6));
      var lng = parseFloat(c.lng.toFixed(6));
      var zoom = map.getZoom();

      var params = Route.get();

      if (   params.lat  !== lat
          || params.lng  !== lng
          || params.zoom !== zoom ) {

        console.log('map lat,lng,zoom !== params');
        Route.update({
          lat: parseFloat(c.lat.toFixed(6)),
          lng: parseFloat(c.lng.toFixed(6)),
          zoom: map.getZoom()
        });

      }

    });
  });

  function addOverlays(overlays) {
    leafletData.getMap().then(function (map) {

      for (var i = 0, len = overlays.length; i < len; ++i) {
        var o = overlays[i];
        var vecRes = VectorProvider.createResource(o);
        vecRes.fetch(function(geojson, name){
          $scope.geojson = {
            data: geojson,
            style: {
              fillColor: "green",
              weight: 2,
              opacity: 1,
              color: 'white',
              dashArray: '3',
              fillOpacity: 0.7
            }
          }
        });
      }

    });

    // NH TODO: Put this in VectorProvider
//    leafletData.getMap().then(function (map) {
//      console.log('Adding Overlays...' + JSON.stringify(overlays));
//      for (var i = 0, len = overlays.length; i < len; ++i) {
//        var o = overlays[i];
//
//        // KML
//        if (o.slice(o.length - 3) === 'kml') {
//          addKml(o);
//        }
//
//      }
//
//    });
  }

  // NH TODO: Put this stuff in VectorProvider
  function addKml(url) {
    omnivore.kml(o).on('ready',function (p) {
      // when this is fired, the layer
      // is done being initialized
      console.log('kml ready');
      console.log(p);

    }).on('error',function (e) {
          console.warn('Error loading kml. Trying php proxy...');

          var layer = omnivore.kml('proxy.php?' + o).on('error', function (e) {
            console.error('giving up loading kml...');
          })

          layer.addTo(map);

        }).addTo(map);
  }

});
<commit_msg>cleaned out things im not using in map controller<commit_after>/**
 * Created by Nicholas Hallahan <nhallahan@spatialdev.com>
 *     on Mon Mar 17 2014
 */

// global map object used for debugging only
m = {};

angular.module('GeoAngular').controller('MapCtrl', function ($scope, leafletData, Route, Alias, VectorProvider) {
  console.log('MapCtrl');

  var routeParams = Route.get();

  var lastLayersStr = '';
  $scope.blur = '';

  //Init activeTheme property
  $scope.activeTheme = "Projects";

  function setParams(routeParams) {
    if (routeParams.landing) {
      console.log('landing');
      $scope.blur = 'blur';
    } else {
      $scope.blur = '';
    }
    var lat = parseFloat(routeParams.lat) || 0;
    var lng = parseFloat(routeParams.lng) || 0;
    var zoom = parseFloat(routeParams.zoom) || 2;
    var layersStr = routeParams.layers;
    var layers = layersStr.split(',') || Alias.redcross;

    // first layer should always be treated as the basemap
    var basemap = Alias.find(layers[0]) || Alias.redcross;
    var overlays = layers.slice(1);

    if (lastLayersStr !== layersStr) {
      console.log('Setting layers.');
      if (Array.isArray(overlays) && overlays.length > 0)
        addOverlays(overlays);

      $scope.defaults = {
        scrollWheelZoom: true
      };

      $scope.tiles = {
        url: basemap
      };
    }

    $scope.center = {
      lat: lat,
      lng: lng,
      zoom: zoom
    };

    lastLayersStr = layersStr;
  }
  setParams(routeParams);

  $scope.$on('route-init', function (event, params) {
    setParams(params);
  });

  $scope.$on('route-update', function (event, params) {
    setParams(params);
  });

  $scope.$on('remove-blur', function (event) {
    $scope.blur = '';
  });

  leafletData.getMap().then(function (map) {
    m = map;
    map.on('moveend', function () { // move is good too
      var c = map.getCenter();
      var lat = parseFloat(c.lat.toFixed(6));
      var lng = parseFloat(c.lng.toFixed(6));
      var zoom = map.getZoom();

      var params = Route.get();

      if (   params.lat  !== lat
          || params.lng  !== lng
          || params.zoom !== zoom ) {

        console.log('map lat,lng,zoom !== params');
        Route.update({
          lat: parseFloat(c.lat.toFixed(6)),
          lng: parseFloat(c.lng.toFixed(6)),
          zoom: map.getZoom()
        });

      }

    });
  });

  function addOverlays(overlays) {
    leafletData.getMap().then(function (map) {

      for (var i = 0, len = overlays.length; i < len; ++i) {
        var o = overlays[i];
        var vecRes = VectorProvider.createResource(o);
        vecRes.fetch(function(geojson, name){
          $scope.geojson = {
            data: geojson,
            style: {
              fillColor: "green",
              weight: 2,
              opacity: 1,
              color: 'white',
              dashArray: '3',
              fillOpacity: 0.7
            }
          }
        });
      }

    });
  }

});
<|endoftext|>


<commit_before>Blockly.Blocks['simplejob'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Receivers");
    this.appendValueInput("Receivers")
        .setCheck(["Receiver", "Array"]);
    this.appendDummyInput()
        .appendField("Filters And Transformers");
    this.appendValueInput("FiltersAndTransformers")
        .setCheck(["Filter", "Array", "Transformer"]);
    this.appendDummyInput()
        .appendField("Senders");
    this.appendValueInput("Senders")
        .setCheck(["Sender", "Array"]);
    this.setInputsInline(false);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.JavaScript['simplejob'] = function(block) {
  var value_receivers = Blockly.JavaScript.valueToCode(block, 'Receivers', Blockly.JavaScript.ORDER_ATOMIC);
  var value_filtersandtransformers = Blockly.JavaScript.valueToCode(block, 'FiltersAndTransformers', Blockly.JavaScript.ORDER_ATOMIC);
  var value_senders = Blockly.JavaScript.valueToCode(block, 'Senders', Blockly.JavaScript.ORDER_ATOMIC);
  debugger;
 //if(!Array.isArray(JSON.parse(value_receivers)))
	value_receivers=[value_receivers];

//if(!Array.isArray(JSON.parse(value_filtersandtransformers)))
	value_filtersandtransformers=[value_filtersandtransformers];

//if(!Array.isArray(JSON.parse(value_senders)))
	value_senders=[value_senders];

var code = '\n';
for(var i=0;i<value_receivers.length;i++){
	if(value_receivers[i] == null || value_receivers[i]=='null')
			continue;
	code+=value_receivers[i] + "\n";
}

for(var i=0;i<value_filtersandtransformers.length;i++){
	if(value_filtersandtransformers[i] == null || value_filtersandtransformers[i]=='null')
			continue;
	code+=value_filtersandtransformers[i]+"\n";
}

for(var i=0;i<value_senders.length;i++){
	if(value_senders[i] == null  || value_senders[i]=='null')
			continue;
	code+=value_senders[i]+"\n";
}
  return code;
};

<commit_msg>generating file<commit_after>Blockly.Blocks['simplejob'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Receivers");
    this.appendValueInput("Receivers")
        .setCheck(["Receiver", "Array"]);
    this.appendDummyInput()
        .appendField("Filters And Transformers");
    this.appendValueInput("FiltersAndTransformers")
        .setCheck(["Filter", "Array", "Transformer"]);
    this.appendDummyInput()
        .appendField("Senders");
    this.appendValueInput("Senders")
        .setCheck(["Sender", "Array"]);
    this.setInputsInline(false);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.JavaScript['simplejob'] = function(block) {
  var value_receivers = eval(Blockly.JavaScript.valueToCode(block, 'Receivers', Blockly.JavaScript.ORDER_ATOMIC));
  var value_filtersandtransformers = eval(Blockly.JavaScript.valueToCode(block, 'FiltersAndTransformers', Blockly.JavaScript.ORDER_ATOMIC));
  var value_senders = eval(Blockly.JavaScript.valueToCode(block, 'Senders', Blockly.JavaScript.ORDER_ATOMIC));
  debugger;
 if(!Array.isArray((value_receivers)))
	value_receivers=[value_receivers];

if(!Array.isArray((value_filtersandtransformers)))
	value_filtersandtransformers=[value_filtersandtransformers];

if(!Array.isArray((value_senders)))
	value_senders=[value_senders];

var code = '\n';
code+="{";
code += '\n';
code += "'$type': 'StanskinsImplementation.SimpleJob, StanskinsImplementation',";
code += '\n';

code += "'Receivers': {";
code += '\n';

code += "'$type': 'StankinsInterfaces.OrderedList`1[[StankinsInterfaces.IReceive, StankinsInterfaces]], StankinsInterfaces'";
code += '\n';

var nr=0;
for(var i=0;i<value_receivers.length;i++){
	var valLoop=value_receivers[i];
	if(valLoop == null || valLoop=='null')
			continue;
	code += ",'"+ nr++  + "': ";
	code += '\n';
	code+=JSON.stringify(valLoop) + "\n";
	code += "";
	code += '\n';
}
code += "},";//end of receivers
code += '\n';

code += '\n';
code += "'FiltersAndTransformers': {";
code += '\n';
code += "'$type': 'StankinsInterfaces.OrderedList`1[[StankinsInterfaces.IFilterTransformer, StankinsInterfaces]], StankinsInterfaces'";
code += '\n';

for(var i=0;i<value_filtersandtransformers.length;i++){
	var valLoop=value_filtersandtransformers[i];
	if(valLoop == null || valLoop=='null')
			continue;

	code += ",'"+ nr++  + "': ";
	code += '\n';
	code+=JSON.stringify(valLoop) + "\n";
	code += "";
	code += '\n';

}
code += "},";//end of filters transformers
code += '\n';

code += "'Senders': {";
code += '\n';
code += "'$type': 'StankinsInterfaces.OrderedList`1[[StankinsInterfaces.ISend, StankinsInterfaces]], StankinsInterfaces'";
code += '\n';

for(var i=0;i<value_senders.length;i++){
	var valLoop=value_senders[i];
	if(valLoop == null  || valLoop=='null')
			continue;
	code += ",'"+ nr++  + "': ";
	code += '\n';
	code+=JSON.stringify(valLoop) + "\n";
	code += "";
	code += '\n';

}
code += "}";//end of senders
code += '\n';

code += "}";//end of job
code += '\n';
  return code;
};

<|endoftext|>


<commit_before>goog.provide('ol.Graticule');

goog.require('goog.asserts');
goog.require('goog.math');
goog.require('ol.extent');
goog.require('ol.geom.GeometryLayout');
goog.require('ol.geom.LineString');
goog.require('ol.geom.flat.geodesic');
goog.require('ol.proj');
goog.require('ol.render.EventType');
goog.require('ol.style.Stroke');

/**
 * Render a grid for a coordinate system on a map.
 * @constructor
 * @param {olx.GraticuleOptions=} opt_options Options.
 * @api
 */
ol.Graticule = function(opt_options) {

  var options = goog.isDef(opt_options) ? opt_options : {};

  /**
   * @type {ol.Map}
   * @private
   */
  this.map_ = null;

  /**
   * @type {ol.proj.Projection}
   * @private
   */
  this.projection_ = null;

  /**
   * @type {number}
   * @private
   */
  this.maxLat_ = Infinity;

  /**
   * @type {number}
   * @private
   */
  this.maxLon_ = Infinity;

  /**
   * @type {number}
   * @private
   */
  this.minLat_ = -Infinity;

  /**
   * @type {number}
   * @private
   */
  this.minLon_ = -Infinity;

  /**
   * @type {number}
   * @private
   */
  this.targetSize_ = goog.isDef(options.targetSize) ?
      options.targetSize : 100;

  /**
   * @type {number}
   * @private
   */
  this.maxLines_ = goog.isDef(options.maxLines) ? options.maxLines : 100;
  goog.asserts.assert(this.maxLines_ > 0,
      'this.maxLines_ should be more than 0');

  /**
   * @type {Array.<ol.geom.LineString>}
   * @private
   */
  this.meridians_ = [];

  /**
   * @type {Array.<ol.geom.LineString>}
   * @private
   */
  this.parallels_ = [];

  /**
   * @type {ol.style.Stroke}
   * @private
   */
  this.strokeStyle_ = goog.isDef(options.strokeStyle) ?
      options.strokeStyle : ol.Graticule.DEFAULT_STROKE_STYLE_;

  /**
   * @type {ol.TransformFunction|undefined}
   * @private
   */
  this.fromLonLatTransform_ = undefined;

  /**
   * @type {ol.TransformFunction|undefined}
   * @private
   */
  this.toLonLatTransform_ = undefined;

  /**
   * @type {ol.Coordinate}
   * @private
   */
  this.projectionCenterLonLat_ = null;

  this.setMap(goog.isDef(options.map) ? options.map : null);
};

/**
 * @type {ol.style.Stroke}
 * @private
 * @const
 */
ol.Graticule.DEFAULT_STROKE_STYLE_ = new ol.style.Stroke({
  color: 'rgba(0,0,0,0.2)'
});

/**
 * TODO can be configurable
 * @type {Array.<number>}
 * @private
 */
ol.Graticule.intervals_ = [90, 45, 30, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05,
  0.01, 0.005, 0.002, 0.001];

/**
 * @param {number} lon Longitude.
 * @param {number} squaredTolerance Squared tolerance.
 * @param {ol.Extent} extent Extent.
 * @param {number} index Index.
 * @return {number} Index.
 * @private
 */
ol.Graticule.prototype.addMeridian_ =
    function(lon, squaredTolerance, extent, index) {
  var lineString = this.getMeridian_(lon, squaredTolerance, index);
  if (ol.extent.intersects(lineString.getExtent(), extent)) {
    this.meridians_[index++] = lineString;
  }
  return index;
};

/**
 * @param {number} lat Latitude.
 * @param {number} squaredTolerance Squared tolerance.
 * @param {ol.Extent} extent Extent.
 * @param {number} index Index.
 * @return {number} Index.
 * @private
 */
ol.Graticule.prototype.addParallel_ =
    function(lat, squaredTolerance, extent, index) {
  var lineString = this.getParallel_(lat, squaredTolerance, index);
  if (ol.extent.intersects(lineString.getExtent(), extent)) {
    this.parallels_[index++] = lineString;
  }
  return index;
};

/**
 * @param {ol.Extent} extent Extent.
 * @param {ol.Coordinate} center Center.
 * @param {number} resolution Resolution.
 * @param {number} squaredTolerance Squared tolerance.
 * @private
 */
ol.Graticule.prototype.createGraticule_ =
    function(extent, center, resolution, squaredTolerance) {

  var interval = this.getInterval_(resolution);
  if (interval == -1) {
    this.meridians_.length = this.parallels_.length = 0;
    return;
  }

  var centerLonLat = this.toLonLatTransform_(center);
  var centerLon = centerLonLat[0];
  var centerLat = centerLonLat[1];
  var maxLines = this.maxLines_;
  var cnt, idx, lat, lon;

  // Create meridians

  centerLon = Math.floor(centerLon / interval) * interval;
  lon = goog.math.clamp(centerLon, this.minLon_, this.maxLon_);

  idx = this.addMeridian_(lon, squaredTolerance, extent, 0);

  cnt = 0;
  while (lon != this.minLon_ && cnt++ < maxLines) {
    lon = Math.max(lon - interval, this.minLon_);
    idx = this.addMeridian_(lon, squaredTolerance, extent, idx);
  }

  lon = goog.math.clamp(centerLon, this.minLon_, this.maxLon_);

  cnt = 0;
  while (lon != this.maxLon_ && cnt++ < maxLines) {
    lon = Math.min(lon + interval, this.maxLon_);
    idx = this.addMeridian_(lon, squaredTolerance, extent, idx);
  }

  this.meridians_.length = idx;

  // Create parallels

  centerLat = Math.floor(centerLat / interval) * interval;
  lat = goog.math.clamp(centerLat, this.minLat_, this.maxLat_);

  idx = this.addParallel_(lat, squaredTolerance, extent, 0);

  cnt = 0;
  while (lat != this.minLat_ && cnt++ < maxLines) {
    lat = Math.max(lat - interval, this.minLat_);
    idx = this.addParallel_(lat, squaredTolerance, extent, idx);
  }

  lat = goog.math.clamp(centerLat, this.minLat_, this.maxLat_);

  cnt = 0;
  while (lat != this.maxLat_ && cnt++ < maxLines) {
    lat = Math.min(lat + interval, this.maxLat_);
    idx = this.addParallel_(lat, squaredTolerance, extent, idx);
  }

  this.parallels_.length = idx;

};

/**
 * @param {number} resolution Resolution.
 * @return {number} The interval in degrees.
 * @private
 */
ol.Graticule.prototype.getInterval_ = function(resolution) {
  var centerLon = this.projectionCenterLonLat_[0];
  var centerLat = this.projectionCenterLonLat_[1];
  var interval = -1;
  var i, ii, delta, dist;
  var target = Math.pow(this.targetSize_ * resolution, 2);
  /** @type {Array.<number>} **/
  var p1 = [];
  /** @type {Array.<number>} **/
  var p2 = [];
  for (i = 0, ii = ol.Graticule.intervals_.length; i < ii; ++i) {
    delta = ol.Graticule.intervals_[i] / 2;
    p1[0] = centerLon - delta;
    p1[1] = centerLat - delta;
    p2[0] = centerLon + delta;
    p2[1] = centerLat + delta;
    this.fromLonLatTransform_(p1, p1);
    this.fromLonLatTransform_(p2, p2);
    dist = Math.pow(p2[0] - p1[0], 2) + Math.pow(p2[1] - p1[1], 2);
    if (dist <= target) {
      break;
    }
    interval = ol.Graticule.intervals_[i];
  }
  return interval;
};

/**
 * Get the map associated with this graticule.
 * @return {ol.Map} The map.
 * @api
 */
ol.Graticule.prototype.getMap = function() {
  return this.map_;
};

/**
 * @param {number} lon Longitude.
 * @param {number} squaredTolerance Squared tolerance.
 * @return {ol.geom.LineString} The meridian line string.
 * @param {number} index Index.
 * @private
 */
ol.Graticule.prototype.getMeridian_ = function(lon, squaredTolerance, index) {
  goog.asserts.assert(lon >= this.minLon_,
      'lon should be larger than or equal to this.minLon_');
  goog.asserts.assert(lon <= this.maxLon_,
      'lon should be smaller than or equal to this.maxLon_');
  var flatCoordinates = ol.geom.flat.geodesic.meridian(lon,
      this.minLat_, this.maxLat_, this.projection_, squaredTolerance);
  goog.asserts.assert(flatCoordinates.length > 0,
      'flatCoordinates cannot be empty');
  var lineString = goog.isDef(this.meridians_[index]) ?
      this.meridians_[index] : new ol.geom.LineString(null);
  lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates);
  return lineString;
};

/**
 * Get the list of meridians.  Meridians are lines of equal longitude.
 * @return {Array.<ol.geom.LineString>} The meridians.
 * @api
 */
ol.Graticule.prototype.getMeridians = function() {
  return this.meridians_;
};

/**
 * @param {number} lat Latitude.
 * @param {number} squaredTolerance Squared tolerance.
 * @return {ol.geom.LineString} The parallel line string.
 * @param {number} index Index.
 * @private
 */
ol.Graticule.prototype.getParallel_ = function(lat, squaredTolerance, index) {
  goog.asserts.assert(lat >= this.minLat_,
      'lat should be larger than or equal to this.minLat_');
  goog.asserts.assert(lat <= this.maxLat_,
      'lat should be smaller than or equal to this.maxLat_');
  var flatCoordinates = ol.geom.flat.geodesic.parallel(lat,
      this.minLon_, this.maxLon_, this.projection_, squaredTolerance);
  goog.asserts.assert(flatCoordinates.length > 0,
      'flatCoordinates cannot be empty');
  var lineString = goog.isDef(this.parallels_[index]) ?
      this.parallels_[index] : new ol.geom.LineString(null);
  lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates);
  return lineString;
};

/**
 * Get the list of parallels.  Pallels are lines of equal latitude.
 * @return {Array.<ol.geom.LineString>} The parallels.
 * @api
 */
ol.Graticule.prototype.getParallels = function() {
  return this.parallels_;
};

/**
 * @param {ol.render.Event} e Event.
 * @private
 */
ol.Graticule.prototype.handlePostCompose_ = function(e) {
  var vectorContext = e.vectorContext;
  var frameState = e.frameState;
  var extent = framteState.extent;
  var viewState = frameState.viewState;
  var center = viewState.center;
  var projection = viewState.projection;
  var resolution = viewState.resolution;
  var pixelRatio = frameState.pixelRatio;
  var squaredTolerance =
      resolution * resolution / (4 * pixelRatio * pixelRatio);

  var updateProjectionInfo = goog.isNull(this.projection_) ||
      !ol.proj.equivalent(this.projection_, projection);

  if (updateProjectionInfo) {
    this.updateProjectionInfo_(projection);
  }

  //Fix the extent if wrapped (note: this is the same extent as vectorContext.extent_)
  var offsetX = 0;
  if (projection.canWrapX()) {
    var projectionExtent = projection.getExtent();
    var worldWidth = ol.extent.getWidth(projectionExtent);
    var x = frameState.focus[0];
    if (x < projectionExtent[0] || x > projectionExtent[2]) {
      var worldsAway = Math.ceil((projectionExtent[0] - x) / worldWidth);
      extent = [
        extent[0] + offsetX, extent[1],
        extent[2] + offsetX, extent[3]
      ];
    }
  }

  this.createGraticule_(extent, center, resolution, squaredTolerance);

  // Draw the lines
  vectorContext.setFillStrokeStyle(null, this.strokeStyle_);
  var i, l, line;
  for (i = 0, l = this.meridians_.length; i < l; ++i) {
    line = this.meridians_[i];
    vectorContext.drawLineStringGeometry(line, null);
  }
  for (i = 0, l = this.parallels_.length; i < l; ++i) {
    line = this.parallels_[i];
    vectorContext.drawLineStringGeometry(line, null);
  }
};

/**
 * @param {ol.proj.Projection} projection Projection.
 * @private
 */
ol.Graticule.prototype.updateProjectionInfo_ = function(projection) {
  goog.asserts.assert(!goog.isNull(projection), 'projection cannot be null');

  var extent = projection.getExtent();
  var worldExtent = projection.getWorldExtent();
  var maxLat = worldExtent[3];
  var maxLon = worldExtent[2];
  var minLat = worldExtent[1];
  var minLon = worldExtent[0];

  goog.asserts.assert(!goog.isNull(extent), 'extent cannot be null');
  goog.asserts.assert(goog.isDef(maxLat), 'maxLat should be defined');
  goog.asserts.assert(goog.isDef(maxLon), 'maxLon should be defined');
  goog.asserts.assert(goog.isDef(minLat), 'minLat should be defined');
  goog.asserts.assert(goog.isDef(minLon), 'minLon should be defined');

  this.maxLat_ = maxLat;
  this.maxLon_ = maxLon;
  this.minLat_ = minLat;
  this.minLon_ = minLon;

  var epsg4326Projection = ol.proj.get('EPSG:4326');

  this.fromLonLatTransform_ = ol.proj.getTransform(
      epsg4326Projection, projection);

  this.toLonLatTransform_ = ol.proj.getTransform(
      projection, epsg4326Projection);

  this.projectionCenterLonLat_ = this.toLonLatTransform_(
      ol.extent.getCenter(extent));

  this.projection_ = projection;
};

/**
 * Set the map for this graticule.  The graticule will be rendered on the
 * provided map.
 * @param {ol.Map} map Map.
 * @api
 */
ol.Graticule.prototype.setMap = function(map) {
  if (!goog.isNull(this.map_)) {
    this.map_.un(ol.render.EventType.POSTCOMPOSE,
        this.handlePostCompose_, this);
    this.map_.render();
  }
  if (!goog.isNull(map)) {
    map.on(ol.render.EventType.POSTCOMPOSE,
        this.handlePostCompose_, this);
    map.render();
  }
  this.map_ = map;
};
<commit_msg>Update graticule.js - fixed typo/build error<commit_after>goog.provide('ol.Graticule');

goog.require('goog.asserts');
goog.require('goog.math');
goog.require('ol.extent');
goog.require('ol.geom.GeometryLayout');
goog.require('ol.geom.LineString');
goog.require('ol.geom.flat.geodesic');
goog.require('ol.proj');
goog.require('ol.render.EventType');
goog.require('ol.style.Stroke');

/**
 * Render a grid for a coordinate system on a map.
 * @constructor
 * @param {olx.GraticuleOptions=} opt_options Options.
 * @api
 */
ol.Graticule = function(opt_options) {

  var options = goog.isDef(opt_options) ? opt_options : {};

  /**
   * @type {ol.Map}
   * @private
   */
  this.map_ = null;

  /**
   * @type {ol.proj.Projection}
   * @private
   */
  this.projection_ = null;

  /**
   * @type {number}
   * @private
   */
  this.maxLat_ = Infinity;

  /**
   * @type {number}
   * @private
   */
  this.maxLon_ = Infinity;

  /**
   * @type {number}
   * @private
   */
  this.minLat_ = -Infinity;

  /**
   * @type {number}
   * @private
   */
  this.minLon_ = -Infinity;

  /**
   * @type {number}
   * @private
   */
  this.targetSize_ = goog.isDef(options.targetSize) ?
      options.targetSize : 100;

  /**
   * @type {number}
   * @private
   */
  this.maxLines_ = goog.isDef(options.maxLines) ? options.maxLines : 100;
  goog.asserts.assert(this.maxLines_ > 0,
      'this.maxLines_ should be more than 0');

  /**
   * @type {Array.<ol.geom.LineString>}
   * @private
   */
  this.meridians_ = [];

  /**
   * @type {Array.<ol.geom.LineString>}
   * @private
   */
  this.parallels_ = [];

  /**
   * @type {ol.style.Stroke}
   * @private
   */
  this.strokeStyle_ = goog.isDef(options.strokeStyle) ?
      options.strokeStyle : ol.Graticule.DEFAULT_STROKE_STYLE_;

  /**
   * @type {ol.TransformFunction|undefined}
   * @private
   */
  this.fromLonLatTransform_ = undefined;

  /**
   * @type {ol.TransformFunction|undefined}
   * @private
   */
  this.toLonLatTransform_ = undefined;

  /**
   * @type {ol.Coordinate}
   * @private
   */
  this.projectionCenterLonLat_ = null;

  this.setMap(goog.isDef(options.map) ? options.map : null);
};

/**
 * @type {ol.style.Stroke}
 * @private
 * @const
 */
ol.Graticule.DEFAULT_STROKE_STYLE_ = new ol.style.Stroke({
  color: 'rgba(0,0,0,0.2)'
});

/**
 * TODO can be configurable
 * @type {Array.<number>}
 * @private
 */
ol.Graticule.intervals_ = [90, 45, 30, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05,
  0.01, 0.005, 0.002, 0.001];

/**
 * @param {number} lon Longitude.
 * @param {number} squaredTolerance Squared tolerance.
 * @param {ol.Extent} extent Extent.
 * @param {number} index Index.
 * @return {number} Index.
 * @private
 */
ol.Graticule.prototype.addMeridian_ =
    function(lon, squaredTolerance, extent, index) {
  var lineString = this.getMeridian_(lon, squaredTolerance, index);
  if (ol.extent.intersects(lineString.getExtent(), extent)) {
    this.meridians_[index++] = lineString;
  }
  return index;
};

/**
 * @param {number} lat Latitude.
 * @param {number} squaredTolerance Squared tolerance.
 * @param {ol.Extent} extent Extent.
 * @param {number} index Index.
 * @return {number} Index.
 * @private
 */
ol.Graticule.prototype.addParallel_ =
    function(lat, squaredTolerance, extent, index) {
  var lineString = this.getParallel_(lat, squaredTolerance, index);
  if (ol.extent.intersects(lineString.getExtent(), extent)) {
    this.parallels_[index++] = lineString;
  }
  return index;
};

/**
 * @param {ol.Extent} extent Extent.
 * @param {ol.Coordinate} center Center.
 * @param {number} resolution Resolution.
 * @param {number} squaredTolerance Squared tolerance.
 * @private
 */
ol.Graticule.prototype.createGraticule_ =
    function(extent, center, resolution, squaredTolerance) {

  var interval = this.getInterval_(resolution);
  if (interval == -1) {
    this.meridians_.length = this.parallels_.length = 0;
    return;
  }

  var centerLonLat = this.toLonLatTransform_(center);
  var centerLon = centerLonLat[0];
  var centerLat = centerLonLat[1];
  var maxLines = this.maxLines_;
  var cnt, idx, lat, lon;

  // Create meridians

  centerLon = Math.floor(centerLon / interval) * interval;
  lon = goog.math.clamp(centerLon, this.minLon_, this.maxLon_);

  idx = this.addMeridian_(lon, squaredTolerance, extent, 0);

  cnt = 0;
  while (lon != this.minLon_ && cnt++ < maxLines) {
    lon = Math.max(lon - interval, this.minLon_);
    idx = this.addMeridian_(lon, squaredTolerance, extent, idx);
  }

  lon = goog.math.clamp(centerLon, this.minLon_, this.maxLon_);

  cnt = 0;
  while (lon != this.maxLon_ && cnt++ < maxLines) {
    lon = Math.min(lon + interval, this.maxLon_);
    idx = this.addMeridian_(lon, squaredTolerance, extent, idx);
  }

  this.meridians_.length = idx;

  // Create parallels

  centerLat = Math.floor(centerLat / interval) * interval;
  lat = goog.math.clamp(centerLat, this.minLat_, this.maxLat_);

  idx = this.addParallel_(lat, squaredTolerance, extent, 0);

  cnt = 0;
  while (lat != this.minLat_ && cnt++ < maxLines) {
    lat = Math.max(lat - interval, this.minLat_);
    idx = this.addParallel_(lat, squaredTolerance, extent, idx);
  }

  lat = goog.math.clamp(centerLat, this.minLat_, this.maxLat_);

  cnt = 0;
  while (lat != this.maxLat_ && cnt++ < maxLines) {
    lat = Math.min(lat + interval, this.maxLat_);
    idx = this.addParallel_(lat, squaredTolerance, extent, idx);
  }

  this.parallels_.length = idx;

};

/**
 * @param {number} resolution Resolution.
 * @return {number} The interval in degrees.
 * @private
 */
ol.Graticule.prototype.getInterval_ = function(resolution) {
  var centerLon = this.projectionCenterLonLat_[0];
  var centerLat = this.projectionCenterLonLat_[1];
  var interval = -1;
  var i, ii, delta, dist;
  var target = Math.pow(this.targetSize_ * resolution, 2);
  /** @type {Array.<number>} **/
  var p1 = [];
  /** @type {Array.<number>} **/
  var p2 = [];
  for (i = 0, ii = ol.Graticule.intervals_.length; i < ii; ++i) {
    delta = ol.Graticule.intervals_[i] / 2;
    p1[0] = centerLon - delta;
    p1[1] = centerLat - delta;
    p2[0] = centerLon + delta;
    p2[1] = centerLat + delta;
    this.fromLonLatTransform_(p1, p1);
    this.fromLonLatTransform_(p2, p2);
    dist = Math.pow(p2[0] - p1[0], 2) + Math.pow(p2[1] - p1[1], 2);
    if (dist <= target) {
      break;
    }
    interval = ol.Graticule.intervals_[i];
  }
  return interval;
};

/**
 * Get the map associated with this graticule.
 * @return {ol.Map} The map.
 * @api
 */
ol.Graticule.prototype.getMap = function() {
  return this.map_;
};

/**
 * @param {number} lon Longitude.
 * @param {number} squaredTolerance Squared tolerance.
 * @return {ol.geom.LineString} The meridian line string.
 * @param {number} index Index.
 * @private
 */
ol.Graticule.prototype.getMeridian_ = function(lon, squaredTolerance, index) {
  goog.asserts.assert(lon >= this.minLon_,
      'lon should be larger than or equal to this.minLon_');
  goog.asserts.assert(lon <= this.maxLon_,
      'lon should be smaller than or equal to this.maxLon_');
  var flatCoordinates = ol.geom.flat.geodesic.meridian(lon,
      this.minLat_, this.maxLat_, this.projection_, squaredTolerance);
  goog.asserts.assert(flatCoordinates.length > 0,
      'flatCoordinates cannot be empty');
  var lineString = goog.isDef(this.meridians_[index]) ?
      this.meridians_[index] : new ol.geom.LineString(null);
  lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates);
  return lineString;
};

/**
 * Get the list of meridians.  Meridians are lines of equal longitude.
 * @return {Array.<ol.geom.LineString>} The meridians.
 * @api
 */
ol.Graticule.prototype.getMeridians = function() {
  return this.meridians_;
};

/**
 * @param {number} lat Latitude.
 * @param {number} squaredTolerance Squared tolerance.
 * @return {ol.geom.LineString} The parallel line string.
 * @param {number} index Index.
 * @private
 */
ol.Graticule.prototype.getParallel_ = function(lat, squaredTolerance, index) {
  goog.asserts.assert(lat >= this.minLat_,
      'lat should be larger than or equal to this.minLat_');
  goog.asserts.assert(lat <= this.maxLat_,
      'lat should be smaller than or equal to this.maxLat_');
  var flatCoordinates = ol.geom.flat.geodesic.parallel(lat,
      this.minLon_, this.maxLon_, this.projection_, squaredTolerance);
  goog.asserts.assert(flatCoordinates.length > 0,
      'flatCoordinates cannot be empty');
  var lineString = goog.isDef(this.parallels_[index]) ?
      this.parallels_[index] : new ol.geom.LineString(null);
  lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates);
  return lineString;
};

/**
 * Get the list of parallels.  Pallels are lines of equal latitude.
 * @return {Array.<ol.geom.LineString>} The parallels.
 * @api
 */
ol.Graticule.prototype.getParallels = function() {
  return this.parallels_;
};

/**
 * @param {ol.render.Event} e Event.
 * @private
 */
ol.Graticule.prototype.handlePostCompose_ = function(e) {
  var vectorContext = e.vectorContext;
  var frameState = e.frameState;
  var extent = frameState.extent;
  var viewState = frameState.viewState;
  var center = viewState.center;
  var projection = viewState.projection;
  var resolution = viewState.resolution;
  var pixelRatio = frameState.pixelRatio;
  var squaredTolerance =
      resolution * resolution / (4 * pixelRatio * pixelRatio);

  var updateProjectionInfo = goog.isNull(this.projection_) ||
      !ol.proj.equivalent(this.projection_, projection);

  if (updateProjectionInfo) {
    this.updateProjectionInfo_(projection);
  }

  //Fix the extent if wrapped (note: this is the same extent as vectorContext.extent_)
  var offsetX = 0;
  if (projection.canWrapX()) {
    var projectionExtent = projection.getExtent();
    var worldWidth = ol.extent.getWidth(projectionExtent);
    var x = frameState.focus[0];
    if (x < projectionExtent[0] || x > projectionExtent[2]) {
      var worldsAway = Math.ceil((projectionExtent[0] - x) / worldWidth);
      extent = [
        extent[0] + offsetX, extent[1],
        extent[2] + offsetX, extent[3]
      ];
    }
  }

  this.createGraticule_(extent, center, resolution, squaredTolerance);

  // Draw the lines
  vectorContext.setFillStrokeStyle(null, this.strokeStyle_);
  var i, l, line;
  for (i = 0, l = this.meridians_.length; i < l; ++i) {
    line = this.meridians_[i];
    vectorContext.drawLineStringGeometry(line, null);
  }
  for (i = 0, l = this.parallels_.length; i < l; ++i) {
    line = this.parallels_[i];
    vectorContext.drawLineStringGeometry(line, null);
  }
};

/**
 * @param {ol.proj.Projection} projection Projection.
 * @private
 */
ol.Graticule.prototype.updateProjectionInfo_ = function(projection) {
  goog.asserts.assert(!goog.isNull(projection), 'projection cannot be null');

  var extent = projection.getExtent();
  var worldExtent = projection.getWorldExtent();
  var maxLat = worldExtent[3];
  var maxLon = worldExtent[2];
  var minLat = worldExtent[1];
  var minLon = worldExtent[0];

  goog.asserts.assert(!goog.isNull(extent), 'extent cannot be null');
  goog.asserts.assert(goog.isDef(maxLat), 'maxLat should be defined');
  goog.asserts.assert(goog.isDef(maxLon), 'maxLon should be defined');
  goog.asserts.assert(goog.isDef(minLat), 'minLat should be defined');
  goog.asserts.assert(goog.isDef(minLon), 'minLon should be defined');

  this.maxLat_ = maxLat;
  this.maxLon_ = maxLon;
  this.minLat_ = minLat;
  this.minLon_ = minLon;

  var epsg4326Projection = ol.proj.get('EPSG:4326');

  this.fromLonLatTransform_ = ol.proj.getTransform(
      epsg4326Projection, projection);

  this.toLonLatTransform_ = ol.proj.getTransform(
      projection, epsg4326Projection);

  this.projectionCenterLonLat_ = this.toLonLatTransform_(
      ol.extent.getCenter(extent));

  this.projection_ = projection;
};

/**
 * Set the map for this graticule.  The graticule will be rendered on the
 * provided map.
 * @param {ol.Map} map Map.
 * @api
 */
ol.Graticule.prototype.setMap = function(map) {
  if (!goog.isNull(this.map_)) {
    this.map_.un(ol.render.EventType.POSTCOMPOSE,
        this.handlePostCompose_, this);
    this.map_.render();
  }
  if (!goog.isNull(map)) {
    map.on(ol.render.EventType.POSTCOMPOSE,
        this.handlePostCompose_, this);
    map.render();
  }
  this.map_ = map;
};
<|endoftext|>


<commit_before>var spawn = require("child_process").spawn;
var nodeUrl = require("url");

var _ = require("lodash");
var Bacon = require("baconjs");

var Logger = require("./logger.js");

var OpenBrowser = module.exports;

OpenBrowser.getCommand = function(url) {
  Logger.debug("Get the right command to open a tab in a browser…")

  try {
    var parsed = nodeUrl.parse(url);
    if(parsed.protocol === null || parsed.hostname === null) {
      return new Bacon.Error("Invalid url provided");
    }
  } catch(e) {
    return new Bacon.Error("Invalid url provided");
  }

  var args = [url];

  switch(process.platform) {
    case "darwin":
      return Bacon.constant({command: "open", args: args});
    case "linux":
      return Bacon.constant({command: "xdg-open", args: args});
    case "win32":
      return Bacon.constant({command: "start", args: args});
    default:
      return new Bacon.Error("Unsupported platform: " + process.platform);
  }
}

OpenBrowser.run = function(command) {
  return Bacon.fromBinder(function(sink) {
    Logger.debug("Opening browser")
    var browser = spawn(command.command, command.args, {
      detached: true,
      stdio: ['ignore', 'ignore', 'ignore']
    });

    // If we have to launch the browser,
    // unref the child process from the parrent process
    browser.unref();

    sink(new Bacon.Next());
    sink(new Bacon.End());

    return function(){};
  });
}

OpenBrowser.openPage = function(url) {
  var s_command = OpenBrowser.getCommand(url);

  return s_command.flatMapLatest(function(command) {
    return OpenBrowser.run(command);
  });
}
<commit_msg>Fix `clever login` support on windows<commit_after>var spawn = require("child_process").spawn;
var nodeUrl = require("url");

var _ = require("lodash");
var Bacon = require("baconjs");

var Logger = require("./logger.js");

var OpenBrowser = module.exports;

OpenBrowser.getCommand = function(url) {
  Logger.debug("Get the right command to open a tab in a browser…")

  try {
    var parsed = nodeUrl.parse(url);
    if(parsed.protocol === null || parsed.hostname === null) {
      return new Bacon.Error("Invalid url provided");
    }
  } catch(e) {
    return new Bacon.Error("Invalid url provided");
  }

  var args = [url];

  switch(process.platform) {
    case "darwin":
      return Bacon.constant({command: "open", args: args});
    case "linux":
      return Bacon.constant({command: "xdg-open", args: args});
    case "win32":
      return Bacon.constant({command: "explorer.exe", args: args});
    default:
      return new Bacon.Error("Unsupported platform: " + process.platform);
  }
}

OpenBrowser.run = function(command) {
  return Bacon.fromBinder(function(sink) {
    Logger.debug("Opening browser")
    var browser = spawn(command.command, command.args, {
      detached: true,
      stdio: ['ignore', 'ignore', 'ignore']
    });

    // If we have to launch the browser,
    // unref the child process from the parrent process
    browser.unref();

    sink(new Bacon.Next());
    sink(new Bacon.End());

    return function(){};
  });
}

OpenBrowser.openPage = function(url) {
  var s_command = OpenBrowser.getCommand(url);

  return s_command.flatMapLatest(function(command) {
    return OpenBrowser.run(command);
  });
}
<|endoftext|>


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

function PhantomEngine(config, logger) {
  this.config = config;
  this.logger = logger;
  this.engineSettings = {
    binary: phantomjs.path,
    userAgent: 'Prerender',
    loadImages: false,
    localToRemoteUrlAccessEnabled: true,
    webSecurityEnabled: true
  };
}

/*
 * Initialize the page
 */
PhantomEngine.prototype.init = function(html, initCallback, errorCallback) {
  var _this = this;

  this.initializationCallback = initCallback;
  this.hasInitializationCallback = true;

  this.engineSettings.onExit = function(code, signal) {
    if (code !== 0) {
      errorCallback("Erroneous exit code: " + code, signal);
    }
  };

  this.phantom = phantom.create("--load-images=no", this.engineSettings, function(ph) {
    _this.phantom.ph = ph;
    _this.phantom.ph.createPage(function(phantomPage) {
      _this.phantom.page = phantomPage;
      _this.phantom.page.set('onConsoleMessage', function(msg) {
        _this.logger.log('debug', '>>>', msg);
      });
      _this.phantom.page.set('onCallback', _.bind(_this.onPageReady, _this));
      _this.phantom.page.set('onError', function(msg) {
        _this.errorCallback("Phantom encountered an error: " + msg);
      });
      _this.phantom.page.set('onResourceError', function(msg) {
        _this.logger.log('error', "Phantom encountered an error loading a resource:", msg);
      });
      _this.phantom.page.set('viewportSize', {
        width: 1024,
        height: 768
      });
      // Add the event listener to the html, since calling page.evaluate happens too late
      html += "<script>" +
                "this.isPrerender = true;" +
                "document.addEventListener('XContentReady', function() {" +
                  "window.callPhantom();" +
                "}, false);" +
              "</script>";
      _this.phantom.page.setContent(html, _this.config.baseUrl);
    });
  });
};

/*
 * Load a route
 */
PhantomEngine.prototype.loadRoute = function(page, callback) {
  this.currentPage = page;
  this.pageCallback = callback;
  this.hasPageCallback = true;

  this.phantom.page.evaluate(function(url) {
    window.prerenderTransitionEvent.url = url;
    document.dispatchEvent(window.prerenderTransitionEvent);
  }, null, page.url);
};

/*
 * Callback handler for when a page finishes rendering
 */
PhantomEngine.prototype.onPageReady = function() {
  var _this = this;

  if (this.hasInitializationCallback) {
    this.hasInitializationCallback = false;
    this.initializationCallback();
  } else {
    setTimeout(function() {
      _this.phantom.page.evaluate(
        function() {
          var html = document.documentElement.outerHTML;
          if (document.doctype) {
            html = "<!DOCTYPE " + document.doctype.name + ">\n" + html;
          }
          return html;
        },
        function (html) {
          if (_this.hasPageCallback) {
            _this.hasPageCallback = false;
            _this.currentPage.statusCode = 200;
            _this.currentPage.html = html;
            _this.pageCallback(_this.currentPage);
          }
        }
      );
    }, this.config.contentReadyDelay);
  }
};

/*
 * Destroy the phantom process
 */
PhantomEngine.prototype.shutdown = function() {
  if (this.phantom && this.phantom.ph) {
    this.phantom.ph.exit();
  }
};

module.exports = PhantomEngine;
<commit_msg>Updating callback reference<commit_after>var _ = require('lodash');
var phantomjs = require('phantomjs');
var phantom = require('phantom');

function PhantomEngine(config, logger) {
  this.config = config;
  this.logger = logger;
  this.engineSettings = {
    binary: phantomjs.path,
    userAgent: 'Prerender',
    loadImages: false,
    localToRemoteUrlAccessEnabled: true,
    webSecurityEnabled: true
  };
}

/*
 * Initialize the page
 */
PhantomEngine.prototype.init = function(html, initCallback, errorCallback) {
  var _this = this;

  this.initializationCallback = initCallback;
  this.hasInitializationCallback = true;

  this.engineSettings.onExit = function(code, signal) {
    if (code !== 0) {
      errorCallback("Erroneous exit code: " + code, signal);
    }
  };

  this.phantom = phantom.create("--load-images=no", this.engineSettings, function(ph) {
    _this.phantom.ph = ph;
    _this.phantom.ph.createPage(function(phantomPage) {
      _this.phantom.page = phantomPage;
      _this.phantom.page.set('onConsoleMessage', function(msg) {
        _this.logger.log('debug', '>>>', msg);
      });
      _this.phantom.page.set('onCallback', _.bind(_this.onPageReady, _this));
      _this.phantom.page.set('onError', function(msg) {
        errorCallback("Phantom encountered an error: " + msg);
      });
      _this.phantom.page.set('onResourceError', function(msg) {
        _this.logger.log('error', "Phantom encountered an error loading a resource:", msg);
      });
      _this.phantom.page.set('viewportSize', {
        width: 1024,
        height: 768
      });
      // Add the event listener to the html, since calling page.evaluate happens too late
      html += "<script>" +
                "this.isPrerender = true;" +
                "document.addEventListener('XContentReady', function() {" +
                  "window.callPhantom();" +
                "}, false);" +
              "</script>";
      _this.phantom.page.setContent(html, _this.config.baseUrl);
    });
  });
};

/*
 * Load a route
 */
PhantomEngine.prototype.loadRoute = function(page, callback) {
  this.currentPage = page;
  this.pageCallback = callback;
  this.hasPageCallback = true;

  this.phantom.page.evaluate(function(url) {
    window.prerenderTransitionEvent.url = url;
    document.dispatchEvent(window.prerenderTransitionEvent);
  }, null, page.url);
};

/*
 * Callback handler for when a page finishes rendering
 */
PhantomEngine.prototype.onPageReady = function() {
  var _this = this;

  if (this.hasInitializationCallback) {
    this.hasInitializationCallback = false;
    this.initializationCallback();
  } else {
    setTimeout(function() {
      _this.phantom.page.evaluate(
        function() {
          var html = document.documentElement.outerHTML;
          if (document.doctype) {
            html = "<!DOCTYPE " + document.doctype.name + ">\n" + html;
          }
          return html;
        },
        function (html) {
          if (_this.hasPageCallback) {
            _this.hasPageCallback = false;
            _this.currentPage.statusCode = 200;
            _this.currentPage.html = html;
            _this.pageCallback(_this.currentPage);
          }
        }
      );
    }, this.config.contentReadyDelay);
  }
};

/*
 * Destroy the phantom process
 */
PhantomEngine.prototype.shutdown = function() {
  if (this.phantom && this.phantom.ph) {
    this.phantom.ph.exit();
  }
};

module.exports = PhantomEngine;
<|endoftext|>


<commit_before>var chalk = require('chalk')
var boldRed = chalk.bold.red
var boldGreen = chalk.bold.green
var boldCyan = chalk.bold.cyan

module.exports = {
  start({ taskname }) {
    console.log(boldCyan('-> ' + taskname))
  },

  success({ taskname }) {
    console.log(boldGreen('√ ' + taskname))
  },

  fail({ taskname, code, stderr }) {
    var header = 'x ' + taskname + ' exited with: ' + code
    console.error(boldRed(header), stderr)
  }
}
<commit_msg>Remove duplicated error message. Fixes: #3<commit_after>var chalk = require('chalk')
var boldRed = chalk.bold.red
var boldGreen = chalk.bold.green
var boldCyan = chalk.bold.cyan

module.exports = {
  start({ taskname }) {
    console.log(boldCyan('-> ' + taskname))
  },

  success({ taskname }) {
    console.log(boldGreen('√ ' + taskname))
  },

  fail({ taskname, code, stderr }) {
    var header = 'x ' + taskname + ' exited with: ' + code
    console.error(boldRed(header))
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict"

var templates = require('./templates')
var fs = require('fs')
var path = require('path')
var cli = require('yargs')
    .usage('Usage: $0 [options]')
    .option('max', {
        describe: 'Maximum number of generated devices',
        default: 5
    })
    .option('f', {
        boolean: true,
        alias: 'force',
        describe: 'Override existing config file'
    })
    .option('t', {
        alias: 'type',
        describe: 'Device types',
        default: 'phone',
        choices: templates.types
    })
    .version(function() {
        var pack = require('../package');
        return pack.name + " " + pack.version;
    })
    .help('help')
var argv = cli.argv

console.log(argv.t);

const CONFIG_FILE = path.join(process.cwd(), '/xd-testing.json')

fs.access(CONFIG_FILE, fs.F_OK, function(err) {
    if (!err && !argv.force) {
        console.log("There is already a file " + CONFIG_FILE);
    } else {
         // File isn't accessible, so write a new one

        // Generate config
        // For each setup use one chrome device and a power of two nexus4 devices

        var setups = []
        var deviceIndices = 'BCDEFGHJKLMNOPQRSTUVWXYZ'
        for (let t = 1; t < argv.max; t *= 2) {
            var devices = {"A": "chrome"}
            for (let i = 0; i < t; i++) {
                devices[deviceIndices[i]] = "nexus4"
            }
            setups.push({devices: devices})
        }
        var config = {setups: setups}

        var json = JSON.stringify(config, null, 2)

        fs.writeFile(CONFIG_FILE, json, err => {
            if (err) throw err
            console.log("Wrote config file to " + CONFIG_FILE)
            console.log(json)
        })
    }
})
<commit_msg>Generate setups config with specific device types<commit_after>#!/usr/bin/env node
"use strict"

var templates = require('./templates')
var fs = require('fs')
var path = require('path')
var cli = require('yargs')
    .usage('Usage: $0 [options]')
    .option('max', {
        describe: 'Maximum number of generated devices',
        default: 5
    })
    .option('f', {
        boolean: true,
        alias: 'force',
        describe: 'Override existing config file'
    })
    .option('t', {
        alias: 'type',
        describe: 'Device types',
        default: 'phone',
        choices: templates.types
    })
    .version(function() {
        var pack = require('../package');
        return pack.name + " " + pack.version;
    })
    .help('help')
var argv = cli.argv

const CONFIG_FILE = path.join(process.cwd(), '/xd-testing.json')

fs.access(CONFIG_FILE, fs.F_OK, function(err) {
    if (!err && !argv.force) {
        console.log("There is already a file " + CONFIG_FILE);
    } else {
        // File isn't accessible, so write a new one

        // Generate config
        // For each setup use a power of two devices
        var types = argv.type
        if (!(types instanceof Array)) {
            types = [types];
        }

        var setups = []
        var deviceIndices = 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
        for (let t = 1; t < argv.max; t *= 2) {
            var devices = {}
            for (let i = 0; i < t; i++) {
                devices[deviceIndices[i]] = templates.random.randomOfTypes(types)
            }
            setups.push({devices: devices})
        }
        var config = {setups: setups}

        var json = JSON.stringify(config, null, 2)

        fs.writeFile(CONFIG_FILE, json, err => {
            if (err) throw err
            console.log("Wrote config file to " + CONFIG_FILE)
            console.log(json)
        })
    }
})
<|endoftext|>


<commit_before>var _ = require("lodash");
var Q = require("q");
var semver = require("semver");
var path = require("path");
var url = require("url");
var fs = require("./fs");
var resolve = require('resolve');

var pkg = require("../../package.json");

var  RESOURCES = ["js", "css"];

var Plugin = function(name, root) {
    this.name = name;
    this.root = root;
    this.packageInfos = {};
    this.infos = {};

    _.each([
        "gitbook-plugin-"+name,
        "gitbook-theme-"+name,
        "gitbook-"+name,
        name,
    ], function(_name) {
        if (this.load(_name, __dirname)) return false;
        if (this.load(_name, path.resolve(root))) return false;
    }, this);
};

// Load from a name
Plugin.prototype.load = function(name, baseDir) {
    try {
        var res = resolve.sync(name+"/package.json", { basedir: baseDir });

        this.baseDir = path.dirname(res);
        this.packageInfos = require(res);
        this.infos = require(resolve.sync(name, { basedir: baseDir }));
        this.name = name;

        return true;
    } catch (e) {
        return false;
    }
};

// Return resources
Plugin.prototype.getResources = function(resource) {
    if (!this.infos.book || !this.infos.book[resource]) {
        return [];
    }
    return _.chain(this.infos.book[resource])
    .map(function(resource) {
        var parsed = url.parse(resource);
        if (parsed.protocol) return {"url": resource}
        else return { "path": this.name+"/"+resource };
    }.bind(this))
    .value();
};

// Test if it's a valid plugin
Plugin.prototype.isValid = function() {
    return (
        this.packageInfos
        && this.packageInfos.name
        && this.packageInfos.engines
        && this.packageInfos.engines.gitbook
        && semver.satisfies(pkg.version, this.packageInfos.engines.gitbook)
    );
};

// Resolve file path
Plugin.prototype.resolveFile = function(filename) {
    return path.resolve(this.baseDir, filename);
};

// Resolve file path
Plugin.prototype.callHook = function(name, context, data) {
    var hookFunc = this.infos.hooks? this.infos.hooks[name] : null;
    data = data || {};

    if (!hookFunc) return Q(data);

    return Q()
    .then(function() {
        return hookFunc.apply(context, [data]);
    });
};

// Has assets
Plugin.prototype.hasAssets = function(out) {
    return (this.infos.book && this.infos.book.assets);
};

// Copy plugin assets fodler
Plugin.prototype.copyAssets = function(out) {
    if (!this.hasAssets()) return Q();
    return fs.copy(
        this.resolveFile(this.infos.book.assets),
        out
    );
};

// Normalize a list of plugin name to use
Plugin.normalizeNames = function(names) {
    // Normalize list to an array
    names = _.isString(names) ? names.split(",") : (names || []);

    // List plugins to remove
    var toremove = _.chain(names)
    .filter(function(name) {
        return name.length > 0 && name[0] == "-";
    })
    .map(function(name) {
        return name.slice(1)
    })
    .value();

    // Merge with defaults
    names = _.chain(names)
    .concat(Plugin.defaults)
    .uniq()
    .value();

    // Remove plugins starting with
    names = _.filter(names, function(name) {
        return !_.contains(toremove, name) && !(name.length > 0 && name[0] == "-");
    });

    return names;
};

// Extract data from a list of plugin
Plugin.fromList = function(names, root) {
    var failed = [];

    // Load plugins
    var plugins = _.map(names, function(name) {
        var plugin = new Plugin(name, root);
        if (!plugin.isValid()) failed.push(name);
        return plugin;
    });

    if (_.size(failed) > 0) return Q.reject(new Error("Error loading plugins: "+failed.join(",")));

    // Get all resources
    var resources = _.chain(RESOURCES)
    .map(function(resource) {
        return [
            resource,
            _.chain(plugins)
            .map(function(plugin) {
                return plugin.getResources(resource);
            })
            .flatten()
            .value()
        ];
    })
    .object()
    .value();
    resources.html = {}

    _.each(plugins, function(plugin) {
        var html = plugin.infos.book.html || {};
        _.each(html, function(code, key) {
            if (!_.isFunction(code)) code = _.constant(code);
            if (!resources.html[key]) resources.html[key] = [];
            resources.html[key].push(code);
        })
    });

    return Q({
        'list': plugins,
        'resources': resources,
        'hook': function(name, context, data) {
            return _.reduce(plugins, function(prev, plugin) {
                return prev.then(function(ret) {
                    return plugin.callHook(name, context, ret);
                })
            }, Q(data));
        },
        'template': function(name) {
            var withTpl = _.find(plugins, function(plugin) {
                return (plugin.infos.templates
                    && plugin.infos.templates[name]);
            });

            if (!withTpl) return null;
            return withTpl.resolveFile(withTpl.infos.templates[name]);
        },
        'html': function(tag, context, options) {
            return _.map(resources.html[tag] || [], function(code) {
                return code.call(context, options);
            }).join("\n");
        }
    });
};

// Default plugins
Plugin.defaults = [
    "mixpanel",
    "mathjax"
];

module.exports = Plugin;
<commit_msg>Fix error when plugin don't extend book<commit_after>var _ = require("lodash");
var Q = require("q");
var semver = require("semver");
var path = require("path");
var url = require("url");
var fs = require("./fs");
var resolve = require('resolve');

var pkg = require("../../package.json");

var  RESOURCES = ["js", "css"];

var Plugin = function(name, root) {
    this.name = name;
    this.root = root;
    this.packageInfos = {};
    this.infos = {};

    _.each([
        "gitbook-plugin-"+name,
        "gitbook-theme-"+name,
        "gitbook-"+name,
        name,
    ], function(_name) {
        if (this.load(_name, __dirname)) return false;
        if (this.load(_name, path.resolve(root))) return false;
    }, this);
};

// Load from a name
Plugin.prototype.load = function(name, baseDir) {
    try {
        var res = resolve.sync(name+"/package.json", { basedir: baseDir });

        this.baseDir = path.dirname(res);
        this.packageInfos = require(res);
        this.infos = require(resolve.sync(name, { basedir: baseDir }));
        this.name = name;

        return true;
    } catch (e) {
        return false;
    }
};

// Return resources
Plugin.prototype.getResources = function(resource) {
    if (!this.infos.book || !this.infos.book[resource]) {
        return [];
    }
    return _.chain(this.infos.book[resource])
    .map(function(resource) {
        var parsed = url.parse(resource);
        if (parsed.protocol) return {"url": resource}
        else return { "path": this.name+"/"+resource };
    }.bind(this))
    .value();
};

// Test if it's a valid plugin
Plugin.prototype.isValid = function() {
    return (
        this.packageInfos
        && this.packageInfos.name
        && this.packageInfos.engines
        && this.packageInfos.engines.gitbook
        && semver.satisfies(pkg.version, this.packageInfos.engines.gitbook)
    );
};

// Resolve file path
Plugin.prototype.resolveFile = function(filename) {
    return path.resolve(this.baseDir, filename);
};

// Resolve file path
Plugin.prototype.callHook = function(name, context, data) {
    var hookFunc = this.infos.hooks? this.infos.hooks[name] : null;
    data = data || {};

    if (!hookFunc) return Q(data);

    return Q()
    .then(function() {
        return hookFunc.apply(context, [data]);
    });
};

// Has assets
Plugin.prototype.hasAssets = function(out) {
    return (this.infos.book && this.infos.book.assets);
};

// Copy plugin assets fodler
Plugin.prototype.copyAssets = function(out) {
    if (!this.hasAssets()) return Q();
    return fs.copy(
        this.resolveFile(this.infos.book.assets),
        out
    );
};

// Normalize a list of plugin name to use
Plugin.normalizeNames = function(names) {
    // Normalize list to an array
    names = _.isString(names) ? names.split(",") : (names || []);

    // List plugins to remove
    var toremove = _.chain(names)
    .filter(function(name) {
        return name.length > 0 && name[0] == "-";
    })
    .map(function(name) {
        return name.slice(1)
    })
    .value();

    // Merge with defaults
    names = _.chain(names)
    .concat(Plugin.defaults)
    .uniq()
    .value();

    // Remove plugins starting with
    names = _.filter(names, function(name) {
        return !_.contains(toremove, name) && !(name.length > 0 && name[0] == "-");
    });

    return names;
};

// Extract data from a list of plugin
Plugin.fromList = function(names, root) {
    var failed = [];

    // Load plugins
    var plugins = _.map(names, function(name) {
        var plugin = new Plugin(name, root);
        if (!plugin.isValid()) failed.push(name);
        return plugin;
    });

    if (_.size(failed) > 0) return Q.reject(new Error("Error loading plugins: "+failed.join(",")));

    // Get all resources
    var resources = _.chain(RESOURCES)
    .map(function(resource) {
        return [
            resource,
            _.chain(plugins)
            .map(function(plugin) {
                return plugin.getResources(resource);
            })
            .flatten()
            .value()
        ];
    })
    .object()
    .value();
    resources.html = {}

    _.each(plugins, function(plugin) {
        if (!plugin.infos.book || !plugin.infos.book.html) return;
        var html = plugin.infos.book.html || {};
        _.each(html, function(code, key) {
            if (!_.isFunction(code)) code = _.constant(code);
            if (!resources.html[key]) resources.html[key] = [];
            resources.html[key].push(code);
        })
    });

    return Q({
        'list': plugins,
        'resources': resources,
        'hook': function(name, context, data) {
            return _.reduce(plugins, function(prev, plugin) {
                return prev.then(function(ret) {
                    return plugin.callHook(name, context, ret);
                })
            }, Q(data));
        },
        'template': function(name) {
            var withTpl = _.find(plugins, function(plugin) {
                return (plugin.infos.templates
                    && plugin.infos.templates[name]);
            });

            if (!withTpl) return null;
            return withTpl.resolveFile(withTpl.infos.templates[name]);
        },
        'html': function(tag, context, options) {
            return _.map(resources.html[tag] || [], function(code) {
                return code.call(context, options);
            }).join("\n");
        }
    });
};

// Default plugins
Plugin.defaults = [
    "mixpanel",
    "mathjax"
];

module.exports = Plugin;
<|endoftext|>


<commit_before>import React from 'React'
import { View, TouchableOpacity, Text, TextInput, ScrollView, Animated } from 'react-native'
import { MultilineText } from '../DefaultText'
import DefaultText from '@Colors/colors'
import style from './PolicyStyle'
import Colors from '@Colors/colors'
import merge from '../../util/merge'
import KeyboardComponent from '../KeyboardComponent'
import { screenHeight } from '../../util/ScreenSizes'

let PIN_LENGTH = 4

class QuickUnlockDisclaimer extends React.Component {
  constructor() {
    super()
    this.state = {
      enteredPIN: ''
    }
  }

  updateEnteredPIN(enteredPIN) {
    this.setState({
      enteredPIN: enteredPIN
    })
  }

  getButtonColor() {
    if (this.inputValid()) {
      return Colors.primaryBlue
    }
    else {
      return Colors.gray5
    }
  }

  getButtonTextColor() {
    return this.getButtonColor() === Colors.gray5 ? 'black' : 'white'
  }

  inputValid() {
    var len = this.state.enteredPIN.length
    if (len == PIN_LENGTH && this.props.connection) {
      return true
    }

    return false
  }

  render() {
    console.log("props bottom is " + this.props.bottom)
    var bottom = this.props.bottom
    return (
      <View style={merge(style.outerContainer, {bottom: bottom})}>
        <View style={style.container}>
          <View style={style.header}>
            <Text style={style.headerText}>
              Quick Unlock Disclaimer
            </Text>
          </View>
          <View style={style.separator}/>
          <ScrollView style={style.instructionWrapper}>
          <Text style={style.instructionText}>
              Disclaimer:
              Enter your TXT2PAY PIN code and press 'Accept' to enable the Quick Unlock method. This will use the TXT2PAY PIN to reauthenticate the device as opposed to
              requiring the full password again. By accepting this option you are acknowledging that Bristol Pound takes no responsibility for any losses that occur as a
              direct result of the inherent reduction in security that this method employs.
              NOTE: You may logout at any time to reset this option.
          </Text>
          </ScrollView>
          <View style={style.pinEntry}>
            <TextInput
              style={style.textInput}
              autoFocus={true}
              value={this.state.enteredPIN}
              onSubmitEditing={() => this.inputValid() && this.props.acceptCallback(this.state.enteredPIN)}
              onChangeText={(enteredPIN) => this.updateEnteredPIN(enteredPIN)}
              placeholder="Enter PIN"
              keyboardType='numeric'
              secureTextEntry={true}
              maxLength={PIN_LENGTH}
            />
          </View>
          <View style={style.buttonRow}>
            <TouchableOpacity
              style={merge(style.buttonContainer, {borderWidth: 2, borderColor: Colors.primaryBlue})}
              onPress={this.props.rejectCallback}
            >
              <Text style={merge(style.buttonText, {color: Colors.primaryBlue})}>
                Cancel
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              disabled={!this.inputValid()}
              style={merge(style.buttonContainer, {backgroundColor: this.getButtonColor()})}
              onPress={() => this.props.acceptCallback(this.state.enteredPIN)}
            >
              <Text style={merge(style.buttonText, {color: this.getButtonTextColor()})}>
                Accept
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    )
  }
}

export default QuickUnlockDisclaimer
<commit_msg>changed disclaimer<commit_after>import React from 'React'
import { View, TouchableOpacity, Text, TextInput, ScrollView, Animated } from 'react-native'
import { MultilineText } from '../DefaultText'
import DefaultText from '@Colors/colors'
import style from './PolicyStyle'
import Colors from '@Colors/colors'
import merge from '../../util/merge'
import KeyboardComponent from '../KeyboardComponent'
import { screenHeight } from '../../util/ScreenSizes'

let PIN_LENGTH = 4

class QuickUnlockDisclaimer extends React.Component {
  constructor() {
    super()
    this.state = {
      enteredPIN: ''
    }
  }

  updateEnteredPIN(enteredPIN) {
    this.setState({
      enteredPIN: enteredPIN
    })
  }

  getButtonColor() {
    if (this.inputValid()) {
      return Colors.primaryBlue
    }
    else {
      return Colors.gray5
    }
  }

  getButtonTextColor() {
    return this.getButtonColor() === Colors.gray5 ? 'black' : 'white'
  }

  inputValid() {
    var len = this.state.enteredPIN.length
    if (len == PIN_LENGTH && this.props.connection) {
      return true
    }

    return false
  }

  render() {
    console.log("props bottom is " + this.props.bottom)
    var bottom = this.props.bottom
    return (
      <View style={merge(style.outerContainer, {bottom: bottom})}>
        <View style={style.container}>
          <View style={style.header}>
            <Text style={style.headerText}>
              Quick Unlock Disclaimer
            </Text>
          </View>
          <View style={style.separator}/>
          <View style={style.instructionWrapper}>
            <Text style={style.instructionText}>
                Disclaimer:
                Enter your Bristol Pound banking PIN code and press 'Accept' to enable the Quick Unlock method. This will use the Bristol Pound banking PIN to reauthenticate the device as opposed to
                requiring the full password again. By accepting this option you are acknowledging that Bristol Pound takes no responsibility for any losses that occur as a
                direct result of the inherent reduction in security.
                NOTE: You may logout at any time to reset this option.
            </Text>
          </View>
          <View style={style.pinEntry}>
            <TextInput
              style={style.textInput}
              autoFocus={true}
              value={this.state.enteredPIN}
              onSubmitEditing={() => this.inputValid() && this.props.acceptCallback(this.state.enteredPIN)}
              onChangeText={(enteredPIN) => this.updateEnteredPIN(enteredPIN)}
              placeholder="Enter PIN"
              keyboardType='numeric'
              secureTextEntry={true}
              maxLength={PIN_LENGTH}
            />
          </View>
          <View style={style.buttonRow}>
            <TouchableOpacity
              style={merge(style.buttonContainer, {borderWidth: 2, borderColor: Colors.primaryBlue})}
              onPress={this.props.rejectCallback}
            >
              <Text style={merge(style.buttonText, {color: Colors.primaryBlue})}>
                Cancel
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              disabled={!this.inputValid()}
              style={merge(style.buttonContainer, {backgroundColor: this.getButtonColor()})}
              onPress={() => this.props.acceptCallback(this.state.enteredPIN)}
            >
              <Text style={merge(style.buttonText, {color: this.getButtonTextColor()})}>
                Accept
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    )
  }
}

export default QuickUnlockDisclaimer
<|endoftext|>


<commit_before>import parseTransform from './transform';
import {entry, ref, transform} from '../util';
import {error} from 'vega-util';

export default function parseData(data, scope) {
  var transforms = [];

  if (data.transform) {
    data.transform.forEach(function(tx) {
      transforms.push(parseTransform(tx, scope));
    });
  }

  scope.addDataPipeline(data.name, analyze(data, scope, transforms));
}

/**
 * Analyze a data pipeline, add needed operators.
 */
function analyze(data, scope, ops) {
  // POSSIBLE TODOs:
  // - error checking for treesource on tree operators (BUT what if tree is upstream?)
  // - this is local analysis, perhaps some tasks better for global analysis...

  var output = [],
      source = null,
      modify = false,
      generate = false,
      upstream, i, n, t, m;

  if (data.values) {
    // hard-wired input data set
    output.push(source = collect(data.values));
  } else if (data.url) {
    // load data from external source
    // TODO: is loader a source?
    output.push(source = load(data));
  } else if (data.source) {
    // derives from another data set
    upstream = scope.getData(data.source);
    source = upstream.output;
    output.push(null); // populate later
  }

  // scan data transforms, add collectors as needed
  for (i=0, n=ops.length; i<n; ++i) {
    t = ops[i];
    m = t.metadata;

    if (!source && !m.source) {
      output.push(source = collect());
    }
    output.push(t);

    if (m.generates) generate = true;
    if (m.modifies && !generate) modify = true;

    if (m.source) source = t;
    else if (m.changes) source = null;
  }

  if (upstream) {
    if (modify) { // relay if we modify upstream tuples
      output[0] = collect();
      output.unshift(transform('Relay', {pulse: ref(upstream.output)}));
    } else {
      output[0] = transform('NoOp', {pulse: ref(upstream.output)});
    }
  }

  if (!source) output.push(collect());
  output.push(transform('Sieve', {}));
  return output;
}

function collect(values) {
  var s = entry('Collect', values, {});
  return s.metadata = {source: true}, s;
}

function load(/*data*/) {
  // TODO: add load operator
  error('Load data from URL not yet supported.');
}
<commit_msg>Add external data loading.<commit_after>import parseTransform from './transform';
import {entry, ref, transform} from '../util';

export default function parseData(data, scope) {
  var transforms = [];

  if (data.transform) {
    data.transform.forEach(function(tx) {
      transforms.push(parseTransform(tx, scope));
    });
  }

  scope.addDataPipeline(data.name, analyze(data, scope, transforms));
}

/**
 * Analyze a data pipeline, add needed operators.
 */
function analyze(data, scope, ops) {
  // POSSIBLE TODOs:
  // - error checking for treesource on tree operators (BUT what if tree is upstream?)
  // - this is local analysis, perhaps some tasks better for global analysis...

  var output = [],
      source = null,
      modify = false,
      generate = false,
      upstream, i, n, t, m;

  if (data.values) {
    // hard-wired input data set
    output.push(source = collect({$ingest: data.values, $format: data.format}));
  } else if (data.url) {
    // load data from external source
    output.push(source = collect({$request: data.url, $format: data.format}));
  } else if (data.source) {
    // derives from another data set
    upstream = scope.getData(data.source);
    source = upstream.output;
    output.push(null); // populate later
  }

  // scan data transforms, add collectors as needed
  for (i=0, n=ops.length; i<n; ++i) {
    t = ops[i];
    m = t.metadata;

    if (!source && !m.source) {
      output.push(source = collect());
    }
    output.push(t);

    if (m.generates) generate = true;
    if (m.modifies && !generate) modify = true;

    if (m.source) source = t;
    else if (m.changes) source = null;
  }

  if (upstream) {
    if (modify) { // relay if we modify upstream tuples
      output[0] = collect();
      output.unshift(transform('Relay', {pulse: ref(upstream.output)}));
    } else {
      output[0] = transform('NoOp', {pulse: ref(upstream.output)});
    }
  }

  if (!source) output.push(collect());
  output.push(transform('Sieve', {}));
  return output;
}

function collect(values) {
  var s = entry('Collect', values, {});
  return s.metadata = {source: true}, s;
}
<|endoftext|>