<commit_before>define([
    'jquery',
    'backbone',
    'knockout',
    'knockout-mapping',
    'underscore',
    'openlayers',
    'views/forms/sections/branch-list',
    'views/map',
    'map/map-tools',
], function ($, Backbone, ko, koMapping, _, ol, BranchList, MapView) {
    var wkt = new ol.format.WKT();
    return BranchList.extend({
        initialize: function(options) {
            var self = this;
            var map = new MapView({
                el: this.$el.find('.map')
            });

            var addFeature = function (feature, editing) {
                var branch = koMapping.fromJS({
                    'editing': ko.observable(editing),
                    'nodes': ko.observableArray(self.defaults)
                });
                var geom = feature.getGeometry();
                if (editing) {
                    self.removeEditedBranch();
                }
                geom.transform(ol.proj.get('EPSG:3857'), ol.proj.get('EPSG:4326'));
                _.each(branch.nodes(), function(node) {
                    if (node.entitytypeid() === self.dataKey) {
                        node.value(wkt.writeGeometry(geom));
                    }
                });
                self.viewModel.branch_lists.push(branch);
                self.trigger('change', 'geometrychange', branch);
                self.trigger('geometrychange', feature, wkt.writeGeometry(geom));
            };

            var bulkAddFeatures = function (features) {
                _.each(features, function(feature, i) {
                    addFeature(feature, i===features.length-1);
                });
                zoomToFeatureOverlay();
            };

            map.map.on('click', function(e) {
                map.map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
                    if (_.contains(feature.getKeys(), 'branch')) {
                        self.removeEditedBranch();
                        feature.get('branch').editing(true);
                    }
                });
            });

            map.on('layerDropped', function (layer) {
                var features = layer.getSource().getFeatures();

                bulkAddFeatures(features);

                map.map.removeLayer(layer);
            });

            var getGeomNode = function (branch) {
                var geomNode = null;
                _.each(branch.nodes(), function(node) {
                    if (node.entitytypeid() === self.dataKey) {
                        geomNode = node;
                    }
                });
                return geomNode;
            };

            this.baseLayers = map.baseLayers;

            BranchList.prototype.initialize.apply(this, arguments);

            self.addDefaultNode(self.dataKey, '')

            var style = function (feature) {
                var editing = feature.get('editing');
                return [new ol.style.Style({
                    fill: new ol.style.Fill({
                        color: 'rgba(92, 184, 92, 0.5)'
                    }),
                    stroke: new ol.style.Stroke({
                        color: '#5cb85c',
                        width: editing ? 4 : 2
                    }),
                    image: new ol.style.Circle({
                        radius: editing ? 9 : 7,
                        fill: new ol.style.Fill({
                            color: 'rgba(92, 184, 92, 0.5)'
                        }),
                        stroke: new ol.style.Stroke({
                            color: '#5cb85c',
                            width: editing ? 4 : 2
                        })
                    })
                })];
            }

            var featureOverlay = new ol.FeatureOverlay({
                style: style
            });

            var zoomToFeatureOverlay = function () {
                var extent = null;
                _.each(featureOverlay.getFeatures().getArray(), function(feature) {
                    var featureExtent = feature.getGeometry().getExtent();
                    if (!extent) {
                        extent = featureExtent;
                    } else {
                        extent = ol.extent.extend(extent, featureExtent);
                    }
                });
                if (extent) {
                    map.map.getView().fitExtent(extent,(map.map.getSize()));
                    if (map.map.getView().getZoom() > 12) {
                        map.map.getView().setZoom(12)
                    }
                }
            }

            var refreshFreatureOverlay = function () {
                featureOverlay.getFeatures().clear();
                _.each(self.getBranchLists(), function(branch) {
                    var geom = wkt.readGeometry(getGeomNode(branch).value());
                    geom.transform(ol.proj.get('EPSG:4326'), ol.proj.get('EPSG:3857'));
                    var feature = new ol.Feature({
                        geometry: geom,
                        branch: branch,
                        editing: branch.editing()
                    });

                    branch.editing.subscribe(function () {
                        feature.set('editing', branch.editing());
                        map.map.render();
                    });

                    feature.on('change', function () {
                        var cloneFeature = feature.clone();
                        var geom = cloneFeature.getGeometry();
                        geom.transform(ol.proj.get('EPSG:3857'), ol.proj.get('EPSG:4326'));
                        getGeomNode(branch).value(wkt.writeGeometry(geom));
                        self.removeEditedBranch();
                        branch.editing(true);
                        self.trigger('change', 'geometrychange', branch);
                        self.trigger('geometrychange', feature, wkt.writeGeometry(geom));
                    });
                    try {
                        featureOverlay.addFeature(feature);
                        }
                    catch(err) {
                        console.log(err.message);
                        }
                });
            }

            self.viewModel.branch_lists.subscribe(refreshFreatureOverlay);
            refreshFreatureOverlay();
            zoomToFeatureOverlay();

            this.on('formloaded', function(){
                map.map.updateSize()
            });

            var draw = null;

            self.$el.find(".geometry-btn").click(function (){
                var geometryType = $(this).data('geometrytype');
                if (draw) {
                    map.map.removeInteraction(draw);
                }
                draw = new ol.interaction.Draw({
                    features: featureOverlay.getFeatures(),
                    type: geometryType
                });
                draw.on('drawend', function(e) {
                    addFeature(e.feature, true);
                    map.map.removeInteraction(draw);
                });
                map.map.addInteraction(draw);

                self.$el.find("#inventory-home").click();
            });

            self.$el.find("#inventory-home").click(function (){
                self.$el.find("#overlay-panel").addClass("hidden");
                self.$el.find("#basemaps-panel").addClass("hidden");

                self.$el.find("#inventory-basemaps").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-basemaps").addClass("arches-map-tools");

                self.$el.find("#inventory-overlays").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-overlays").addClass("arches-map-tools");

                self.$el.find("#inventory-home").addClass("arches-map-tools-pressed");
                self.$el.find("#inventory-home").removeClass("arches-map-tools");

                return false;
            });
            self.$el.find("#inventory-basemaps").click(function (){
                self.$el.find("#overlay-panel").addClass("hidden");
                self.$el.find("#basemaps-panel").removeClass("hidden");

                self.$el.find("#inventory-home").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-home").addClass("arches-map-tools");

                self.$el.find("#inventory-overlays").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-overlays").addClass("arches-map-tools");

                self.$el.find("#inventory-basemaps").addClass("arches-map-tools-pressed");
                self.$el.find("#inventory-basemaps").removeClass("arches-map-tools");

                return false;
            });

            self.$el.find("#inventory-overlays").click(function (){
                self.$el.find("#overlay-panel").removeClass("hidden");
                self.$el.find("#basemaps-panel").addClass("hidden");

                self.$el.find("#inventory-home").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-home").addClass("arches-map-tools");

                self.$el.find("#inventory-basemaps").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-basemaps").addClass("arches-map-tools");

                self.$el.find("#inventory-overlays").addClass("arches-map-tools-pressed");
                self.$el.find("#inventory-overlays").removeClass("arches-map-tools");

                return false;
            });

            this.$el.find(".close").click(function (){
                $("#inventory-home").click()
            });

            $(".basemap").click(function (){
                var basemap = $(this).attr('id');
                _.each(map.baseLayers, function(baseLayer){
                    baseLayer.layer.setVisible(baseLayer.id == basemap);
                });
                $("#inventory-home").click()
            });

            // manage input of lat/long and live display in DMS
            $('.coord-input').keyup(function () {
                if (this.id == "latinput") {
                    var dms = ConvertDDToDMS(this.value);
                    var dmsstring = DMSString(dms);
                    $('#lat-dms-display').html('
'+dmsstring+'
');
                }
                if (this.id == "longinput") {
                    var dms = ConvertDDToDMS(this.value,true);
                    var dmsstring = DMSString(dms);
                    $('#long-dms-display').html('
'+dmsstring+'
');
                }
                if (!this.value.match(/[0-9]/)) {
                    this.value = this.value.replace(/[^0-9]/g, '');
                };
                if (!this.value.match(/^[+\-]?[0-9]{1,3}\.[0-9]{5,}/)) {
                    $('#'+this.id).css({ color: "red" })
                } else {
                    $('#'+this.id).css({ color: "black" })
                }
            });

            // take the input lat/long and add to map by making a feature from wkt
            this.$el.find('#add-lat-long').on('click', function() {
                var latdd = $('#latinput').val();
                var longdd = $('#longinput').val();
                var wkt = 'POINT('+longdd+' '+latdd+')';
                var format = new ol.format.WKT();
                var feature = format.readFeature(wkt, {
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                bulkAddFeatures([feature]);
                $("#inventory-home").click()
                $('.coord-input').val("");
            });

            var formatConstructors = [
                ol.format.GPX,
                ol.format.GeoJSON,
                ol.format.KML
            ];

            this.$el.find('.geom-upload').on('change', function() {
                if (this.files.length > 0) {
                    var file = this.files[0];
                    var reader = new FileReader();
                    reader.onloadend = function(e) {
                        var features = [];
                        var result = this.result;
                        _.each(formatConstructors, function(formatConstructor) {
                            var format = new formatConstructor();
                            var readFeatures;
                            try {
                                readFeatures = format.readFeatures(result);
                            } catch (e) {
                                readFeatures = null;
                            }
                            if (readFeatures !== null) {
                                _.each(readFeatures, function (feature) {
                                    var featureProjection = format.readProjection(result);
                                    var transform = ol.proj.getTransform(featureProjection, ol.proj.get('EPSG:3857'));
                                    var geometry = feature.getGeometry();
                                    if (geometry) {
                                        geometry.applyTransform(transform);
                                    }
                                    features.push(feature);
                                });
                            }
                        });
                        if (features.length > 0) {
                            bulkAddFeatures(features);
                        }
                    };
                    reader.readAsText(file);
                }
            });

            featureOverlay.setMap(map.map);

            var modify = new ol.interaction.Modify({
              features: featureOverlay.getFeatures(),
              deleteCondition: function(event) {
                return ol.events.condition.shiftKeyOnly(event) &&
                    ol.events.condition.singleClick(event);
              }
            });
            map.map.addInteraction(modify);
        },
        getBranchLists: function() {
            var self = this;
            var branch_lists = [];
            _.each(this.viewModel.branch_lists(), function(list){
                _.each(list.nodes(), function(node) {
                    if (node.entitytypeid() === self.dataKey && node.value() !== '') {
                        branch_lists.push(list);
                    }
                });
            }, this);
            return branch_lists;
        },
        removeEditedBranch: function(){
            var branch = this.getEditedBranch();
            if (branch) {
                branch.editing(false);
            }
            return branch;
        },
    });
});<commit_msg>make arches js variables available<commit_after>define([
    'jquery',
    'backbone',
    'knockout',
    'knockout-mapping',
    'underscore',
    'openlayers',
    'views/forms/sections/branch-list',
    'arches',
    'views/map',
    'map/map-tools',
], function ($, Backbone, ko, koMapping, _, ol, BranchList, arches, MapView) {
    var wkt = new ol.format.WKT();
    return BranchList.extend({
        initialize: function(options) {
            var self = this;
            var map = new MapView({
                el: this.$el.find('.map')
            });

            var addFeature = function (feature, editing) {
                var branch = koMapping.fromJS({
                    'editing': ko.observable(editing),
                    'nodes': ko.observableArray(self.defaults)
                });
                var geom = feature.getGeometry();
                if (editing) {
                    self.removeEditedBranch();
                }
                geom.transform(ol.proj.get('EPSG:3857'), ol.proj.get('EPSG:4326'));
                _.each(branch.nodes(), function(node) {
                    if (node.entitytypeid() === self.dataKey) {
                        node.value(wkt.writeGeometry(geom));
                    }
                });
                self.viewModel.branch_lists.push(branch);
                self.trigger('change', 'geometrychange', branch);
                self.trigger('geometrychange', feature, wkt.writeGeometry(geom));
            };

            var bulkAddFeatures = function (features) {
                _.each(features, function(feature, i) {
                    addFeature(feature, i===features.length-1);
                });
                zoomToFeatureOverlay();
            };

            map.map.on('click', function(e) {
                map.map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
                    if (_.contains(feature.getKeys(), 'branch')) {
                        self.removeEditedBranch();
                        feature.get('branch').editing(true);
                    }
                });
            });

            map.on('layerDropped', function (layer) {
                var features = layer.getSource().getFeatures();

                bulkAddFeatures(features);

                map.map.removeLayer(layer);
            });

            var getGeomNode = function (branch) {
                var geomNode = null;
                _.each(branch.nodes(), function(node) {
                    if (node.entitytypeid() === self.dataKey) {
                        geomNode = node;
                    }
                });
                return geomNode;
            };

            this.baseLayers = map.baseLayers;

            BranchList.prototype.initialize.apply(this, arguments);

            self.addDefaultNode(self.dataKey, '')

            var style = function (feature) {
                var editing = feature.get('editing');
                return [new ol.style.Style({
                    fill: new ol.style.Fill({
                        color: 'rgba(92, 184, 92, 0.5)'
                    }),
                    stroke: new ol.style.Stroke({
                        color: '#5cb85c',
                        width: editing ? 4 : 2
                    }),
                    image: new ol.style.Circle({
                        radius: editing ? 9 : 7,
                        fill: new ol.style.Fill({
                            color: 'rgba(92, 184, 92, 0.5)'
                        }),
                        stroke: new ol.style.Stroke({
                            color: '#5cb85c',
                            width: editing ? 4 : 2
                        })
                    })
                })];
            }

            var featureOverlay = new ol.FeatureOverlay({
                style: style
            });

            var zoomToFeatureOverlay = function () {
                var extent = null;
                _.each(featureOverlay.getFeatures().getArray(), function(feature) {
                    var featureExtent = feature.getGeometry().getExtent();
                    if (!extent) {
                        extent = featureExtent;
                    } else {
                        extent = ol.extent.extend(extent, featureExtent);
                    }
                });
                if (extent) {
                    map.map.getView().fitExtent(extent,(map.map.getSize()));
                    if (map.map.getView().getZoom() > 12) {
                        map.map.getView().setZoom(12)
                    }
                }
            }

            var refreshFreatureOverlay = function () {
                featureOverlay.getFeatures().clear();
                _.each(self.getBranchLists(), function(branch) {
                    var geom = wkt.readGeometry(getGeomNode(branch).value());
                    geom.transform(ol.proj.get('EPSG:4326'), ol.proj.get('EPSG:3857'));
                    var feature = new ol.Feature({
                        geometry: geom,
                        branch: branch,
                        editing: branch.editing()
                    });

                    branch.editing.subscribe(function () {
                        feature.set('editing', branch.editing());
                        map.map.render();
                    });

                    feature.on('change', function () {
                        var cloneFeature = feature.clone();
                        var geom = cloneFeature.getGeometry();
                        geom.transform(ol.proj.get('EPSG:3857'), ol.proj.get('EPSG:4326'));
                        getGeomNode(branch).value(wkt.writeGeometry(geom));
                        self.removeEditedBranch();
                        branch.editing(true);
                        self.trigger('change', 'geometrychange', branch);
                        self.trigger('geometrychange', feature, wkt.writeGeometry(geom));
                    });
                    try {
                        featureOverlay.addFeature(feature);
                        }
                    catch(err) {
                        console.log(err.message);
                        }
                });
            }

            self.viewModel.branch_lists.subscribe(refreshFreatureOverlay);
            refreshFreatureOverlay();
            zoomToFeatureOverlay();

            this.on('formloaded', function(){
                map.map.updateSize()
            });

            var draw = null;

            self.$el.find(".geometry-btn").click(function (){
                var geometryType = $(this).data('geometrytype');
                if (draw) {
                    map.map.removeInteraction(draw);
                }
                draw = new ol.interaction.Draw({
                    features: featureOverlay.getFeatures(),
                    type: geometryType
                });
                draw.on('drawend', function(e) {
                    addFeature(e.feature, true);
                    map.map.removeInteraction(draw);
                });
                map.map.addInteraction(draw);

                self.$el.find("#inventory-home").click();
            });

            self.$el.find("#inventory-home").click(function (){
                self.$el.find("#overlay-panel").addClass("hidden");
                self.$el.find("#basemaps-panel").addClass("hidden");

                self.$el.find("#inventory-basemaps").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-basemaps").addClass("arches-map-tools");

                self.$el.find("#inventory-overlays").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-overlays").addClass("arches-map-tools");

                self.$el.find("#inventory-home").addClass("arches-map-tools-pressed");
                self.$el.find("#inventory-home").removeClass("arches-map-tools");

                return false;
            });
            self.$el.find("#inventory-basemaps").click(function (){
                self.$el.find("#overlay-panel").addClass("hidden");
                self.$el.find("#basemaps-panel").removeClass("hidden");

                self.$el.find("#inventory-home").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-home").addClass("arches-map-tools");

                self.$el.find("#inventory-overlays").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-overlays").addClass("arches-map-tools");

                self.$el.find("#inventory-basemaps").addClass("arches-map-tools-pressed");
                self.$el.find("#inventory-basemaps").removeClass("arches-map-tools");

                return false;
            });

            self.$el.find("#inventory-overlays").click(function (){
                self.$el.find("#overlay-panel").removeClass("hidden");
                self.$el.find("#basemaps-panel").addClass("hidden");

                self.$el.find("#inventory-home").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-home").addClass("arches-map-tools");

                self.$el.find("#inventory-basemaps").removeClass("arches-map-tools-pressed");
                self.$el.find("#inventory-basemaps").addClass("arches-map-tools");

                self.$el.find("#inventory-overlays").addClass("arches-map-tools-pressed");
                self.$el.find("#inventory-overlays").removeClass("arches-map-tools");

                return false;
            });

            this.$el.find(".close").click(function (){
                $("#inventory-home").click()
            });

            $(".basemap").click(function (){
                var basemap = $(this).attr('id');
                _.each(map.baseLayers, function(baseLayer){
                    baseLayer.layer.setVisible(baseLayer.id == basemap);
                });
                $("#inventory-home").click()
            });

            // manage input of lat/long and live display in DMS
            $('.coord-input').keyup(function () {
                if (this.id == "latinput") {
                    var dms = ConvertDDToDMS(this.value);
                    var dmsstring = DMSString(dms);
                    $('#lat-dms-display').html('
'+dmsstring+'
');
                }
                if (this.id == "longinput") {
                    var dms = ConvertDDToDMS(this.value,true);
                    var dmsstring = DMSString(dms);
                    $('#long-dms-display').html('
'+dmsstring+'
');
                }
                if (!this.value.match(/[0-9]/)) {
                    this.value = this.value.replace(/[^0-9]/g, '');
                };
                if (!this.value.match(/^[+\-]?[0-9]{1,3}\.[0-9]{5,}/)) {
                    $('#'+this.id).css({ color: "red" })
                } else {
                    $('#'+this.id).css({ color: "black" })
                }
            });

            // take the input lat/long and add to map by making a feature from wkt
            this.$el.find('#add-lat-long').on('click', function() {
                var latdd = $('#latinput').val();
                var longdd = $('#longinput').val();
                var wkt = 'POINT('+longdd+' '+latdd+')';
                var format = new ol.format.WKT();
                var feature = format.readFeature(wkt, {
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                });
                bulkAddFeatures([feature]);
                $("#inventory-home").click()
                $('.coord-input').val("");
            });

            var formatConstructors = [
                ol.format.GPX,
                ol.format.GeoJSON,
                ol.format.KML
            ];

            this.$el.find('.geom-upload').on('change', function() {
                if (this.files.length > 0) {
                    var file = this.files[0];
                    var reader = new FileReader();
                    reader.onloadend = function(e) {
                        var features = [];
                        var result = this.result;
                        _.each(formatConstructors, function(formatConstructor) {
                            var format = new formatConstructor();
                            var readFeatures;
                            try {
                                readFeatures = format.readFeatures(result);
                            } catch (e) {
                                readFeatures = null;
                            }
                            if (readFeatures !== null) {
                                _.each(readFeatures, function (feature) {
                                    var featureProjection = format.readProjection(result);
                                    var transform = ol.proj.getTransform(featureProjection, ol.proj.get('EPSG:3857'));
                                    var geometry = feature.getGeometry();
                                    if (geometry) {
                                        geometry.applyTransform(transform);
                                    }
                                    features.push(feature);
                                });
                            }
                        });
                        if (features.length > 0) {
                            bulkAddFeatures(features);
                        }
                    };
                    reader.readAsText(file);
                }
            });

            featureOverlay.setMap(map.map);

            var modify = new ol.interaction.Modify({
              features: featureOverlay.getFeatures(),
              deleteCondition: function(event) {
                return ol.events.condition.shiftKeyOnly(event) &&
                    ol.events.condition.singleClick(event);
              }
            });
            map.map.addInteraction(modify);
        },
        getBranchLists: function() {
            var self = this;
            var branch_lists = [];
            _.each(this.viewModel.branch_lists(), function(list){
                _.each(list.nodes(), function(node) {
                    if (node.entitytypeid() === self.dataKey && node.value() !== '') {
                        branch_lists.push(list);
                    }
                });
            }, this);
            return branch_lists;
        },
        removeEditedBranch: function(){
            var branch = this.getEditedBranch();
            if (branch) {
                branch.editing(false);
            }
            return branch;
        },
    });
});<|endoftext|>


<commit_before>const http = require('http');
const gpio = require('wpi-gpio');

gpio.BCM_GPIO = true;

http.get('http://10.0.0.70', (res, err) => {
  res.on(err, (err) => {
    console.log(err);
  });

  res.on(data, (data) => {
    console.log(res);
  })
  console.info(gpio);
})
<commit_msg>silly me<commit_after>const http = require('http');
const gpio = require('wpi-gpio');

gpio.BCM_GPIO = true;

http.get('http://10.0.0.70', (res, err) => {
  res.on('err', (err) => {
    console.log(err);
  });

  res.on('data', (data) => {
    console.log(res);
  })
  console.info(gpio);
})
<|endoftext|>


<commit_before>'use strict';

const http = require('http');
const gpio = require('pi-gpio');

const n = 3;
const sec = (num) => {
  return num * 1000;
}
const min = (num) => {
  return sec(num);
};

const timer = sec(3);
const mainMin = (15);

console.log('sec', timeer, 'mainMin', mainMin);

gpio.BCM_GPIO = true;

function cycleOff (pin) {
  setTimout(() => {
    gpio.write(pin, 0, () => {
      cycleOn();
    });
  }, timer);
};

function cycleOn (pin) {
  setTimout(() => {
    gpio.write(pin, 0, () => {
      done();;
    });
  }, 0);
};

function done () {
  conesole.info('Station reset', new Date(););
}

const getWeather = () => {
  http.get('http://10.0.0.70', (res, err) => {
      res.setEncoding('utf8');
      res.on('err', (err) => {
          console.log(err.message);
      });

      res.on('data', (data) => {
          let status = JSON.parse(data);
          status = status.connected;

          if (status !== true) {
            cycleOff();
          } else {
              console.log('ok....')
          }
      });
  });
}

const mainTimer = () => {
  const setTimeout(getWeather, )
}
<commit_msg>incomplete...<commit_after>'use strict';

const http = require('http');
const gpio = require('pi-gpio');

const n = 3;
const sec = (num) => {
  return num * 1000;
}
const min = (num) => {
  return sec(num);
};

const timer = sec(3);
const mainMin = (15);

console.log('sec', timeer, 'mainMin', mainMin);

gpio.BCM_GPIO = true;

function cycleOff (pin) {
  setTimout(() => {
    gpio.write(pin, 0, () => {
      cycleOn();
    });
  }, timer);
};

function cycleOn (pin) {
  setTimout(() => {
    gpio.write(pin, 0, () => {
      done();
    });
  }, 0);
};

function done () {
  conesole.info('Station reset', new Date());
}

const getWeather = () => {
  http.get('http://10.0.0.70', (res, err) => {
      res.setEncoding('utf8');
      res.on('err', (err) => {
          console.log(err.message);
      });

      res.on('data', (data) => {
          let status = JSON.parse(data);
          status = status.connected;

          if (status !== true) {
            cycleOff();
          } else {
              console.log('ok....')
          }
      });
  });
}

const mainTimer = () => {
  const setTimeout(getWeather, mainMin)
}
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var pages = angular.module('feincms.pages', [
        'ngRoute',
        'project_settings',
        'djangularRestFramework'
    ]);

    pages.constant('FEINCMS_PAGES', {
        // API endpoints
        PAGES_ENDPOINT: '/pages',
        // Angular routes
        PAGES: '/pages/'
    });

    pages.config(['$routeProvider', 'FEINCMS_PAGES', 'PROJECT_SETTINGS', function ($routeProvider, FEINCMS_PAGES, PROJECT_SETTINGS) {
        var MODULE_SETTINGS = angular.extend({}, FEINCMS_PAGES, PROJECT_SETTINGS.FEINCMS_PAGES);

        $routeProvider
            .when(MODULE_SETTINGS.PAGES + ':slug/', {
                templateUrl: 'templates/feincms/pages/detail.html',
                controller: 'PagesDetailCtrl'
            });
    }]);

    pages.controller('PagesDetailCtrl', ['$scope', '$routeParams', 'drf', 'FEINCMS_PAGES', 'PROJECT_SETTINGS', function ($scope, $routeParams, drf, FEINCMS_PAGES, PROJECT_SETTINGS) {
        var MODULE_SETTINGS = angular.extend({}, FEINCMS_PAGES, PROJECT_SETTINGS.FEINCMS_PAGES);

        var url = PROJECT_SETTINGS.API_ROOT + MODULE_SETTINGS.PAGES_ENDPOINT;
        url = url + '/' + $routeParams.slug;

        drf.loadItem(url)
            .then(function (response) {
                $scope.response = response;
            });
    }]);

    pages.directive('pageGroup', ['drf', 'FEINCMS_PAGES', 'PROJECT_SETTINGS', function (drf, FEINCMS_PAGES, PROJECT_SETTINGS) {
        var MODULE_SETTINGS = angular.extend({}, FEINCMS_PAGES, PROJECT_SETTINGS.FEINCMS_PAGES);

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                drf.loadList(PROJECT_SETTINGS.API_ROOT + MODULE_SETTINGS.PAGES_ENDPOINT + '?group=' + encodeURI(attrs.pageGroup))
                    .then(function (response) {
                        scope.pages = response;
                    });
            }
        };
    }]);

    pages.directive('feincmsPageRegion', ['$location', 'drf', 'FEINCMS_PAGES', 'PROJECT_SETTINGS', function ($location, drf, FEINCMS_PAGES, PROJECT_SETTINGS) {
        var MODULE_SETTINGS = angular.extend({}, FEINCMS_PAGES, PROJECT_SETTINGS.FEINCMS_PAGES);

        return {
            restrict: 'A',
            scope: {
                region: '@'
            },
            replace: true,
            templateUrl: 'templates/feincms/pages/region.html',
            link: function (scope, element, attrs) {
                var url = PROJECT_SETTINGS.API_ROOT + MODULE_SETTINGS.PAGES_ENDPOINT;

                var slug = $location.$$path;
                // Remove the first and last / from the path.
                slug = slug.replace(/^\/+|\/+$/g, '');

                url = url + '/' + slug;

                drf.loadItem(url)
                    .then(function (response) {
                        scope.content = page.regions[scope.region];
                    });
            }
        };
    }]);

    pages.run(['$templateCache', function ($templateCache) {
        $templateCache.put('templates/feincms/pages/detail.html',
            '
{{ response|json }}
'
        );
        $templateCache.put('templates/feincms/pages/region.html',
            '

'
        );
    }]);
}());
<commit_msg>Remove trailing whitespace<commit_after>(function () {
    'use strict';

    var pages = angular.module('feincms.pages', [
        'ngRoute',
        'project_settings',
        'djangularRestFramework'
    ]);

    pages.constant('FEINCMS_PAGES', {
        // API endpoints
        PAGES_ENDPOINT: '/pages',
        // Angular routes
        PAGES: '/pages/'
    });

    pages.config(['$routeProvider', 'FEINCMS_PAGES', 'PROJECT_SETTINGS', function ($routeProvider, FEINCMS_PAGES, PROJECT_SETTINGS) {
        var MODULE_SETTINGS = angular.extend({}, FEINCMS_PAGES, PROJECT_SETTINGS.FEINCMS_PAGES);

        $routeProvider
            .when(MODULE_SETTINGS.PAGES + ':slug/', {
                templateUrl: 'templates/feincms/pages/detail.html',
                controller: 'PagesDetailCtrl'
            });
    }]);

    pages.controller('PagesDetailCtrl', ['$scope', '$routeParams', 'drf', 'FEINCMS_PAGES', 'PROJECT_SETTINGS', function ($scope, $routeParams, drf, FEINCMS_PAGES, PROJECT_SETTINGS) {
        var MODULE_SETTINGS = angular.extend({}, FEINCMS_PAGES, PROJECT_SETTINGS.FEINCMS_PAGES);

        var url = PROJECT_SETTINGS.API_ROOT + MODULE_SETTINGS.PAGES_ENDPOINT;
        url = url + '/' + $routeParams.slug;

        drf.loadItem(url)
            .then(function (response) {
                $scope.response = response;
            });
    }]);

    pages.directive('pageGroup', ['drf', 'FEINCMS_PAGES', 'PROJECT_SETTINGS', function (drf, FEINCMS_PAGES, PROJECT_SETTINGS) {
        var MODULE_SETTINGS = angular.extend({}, FEINCMS_PAGES, PROJECT_SETTINGS.FEINCMS_PAGES);

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                drf.loadList(PROJECT_SETTINGS.API_ROOT + MODULE_SETTINGS.PAGES_ENDPOINT + '?group=' + encodeURI(attrs.pageGroup))
                    .then(function (response) {
                        scope.pages = response;
                    });
            }
        };
    }]);

    pages.directive('feincmsPageRegion', ['$location', 'drf', 'FEINCMS_PAGES', 'PROJECT_SETTINGS', function ($location, drf, FEINCMS_PAGES, PROJECT_SETTINGS) {
        var MODULE_SETTINGS = angular.extend({}, FEINCMS_PAGES, PROJECT_SETTINGS.FEINCMS_PAGES);

        return {
            restrict: 'A',
            scope: {
                region: '@'
            },
            replace: true,
            templateUrl: 'templates/feincms/pages/region.html',
            link: function (scope, element, attrs) {
                var url = PROJECT_SETTINGS.API_ROOT + MODULE_SETTINGS.PAGES_ENDPOINT;

                var slug = $location.$$path;
                // Remove the first and last / from the path.
                slug = slug.replace(/^\/+|\/+$/g, '');

                url = url + '/' + slug;

                drf.loadItem(url)
                    .then(function (response) {
                        scope.content = page.regions[scope.region];
                    });
            }
        };
    }]);

    pages.run(['$templateCache', function ($templateCache) {
        $templateCache.put('templates/feincms/pages/detail.html',
            '
{{ response|json }}
'
        );
        $templateCache.put('templates/feincms/pages/region.html',
            '

'
        );
    }]);
}());
<|endoftext|>


<commit_before>var auth = require('./auth.js');
var config = require('./config.js');
var httpHelpers = require('./http-helpers.js');
var release = require('./release.js');
var files = require('./files.js');
var fs = require('fs');
var path = require('path');
var Future = require('fibers/future');
var _ = require('underscore');

var getLoadedPackages = _.once(function () {
  var unipackage = require('./unipackage.js');
  return unipackage.load({
    library: release.current.library,
    packages: [ 'meteor', 'livedata', 'minimongo', 'mongo-livedata' ],
    release: release.current.name
  });
});

var openPackageServerConnection = function () {
  var DDP = getLoadedPackages().livedata.DDP;
  return DDP.connect(config.getPackageServerUrl(), {
    headers: { 'User-Agent': httpHelpers.getUserAgent() }
  });
};

var loadLocalPackageData = function () {
  // XXX pretty error handling
  try {
    var data = fs.readFileSync(config.getPackageStorage(), 'utf8');
  } catch (e) {
    if (e.code !== 'ENOENT')
      throw e;
    // Default: no data, send us everything.
    return {
      // XXX have a better sync token for "all"
      syncToken: {time: 'Sun, 01 Jan 2012 00:00:00 GMT'},
      collections: null
    };
  }
  return JSON.parse(data);
};

var loadRemotePackageData = function (syncToken) {
  var conn = openPackageServerConnection();
  var collectionData = conn.call('syncNewPackageData', syncToken);
  conn.close();
  return collectionData;
};

// Takes in two javascript objects of the form:
//  { collectionName : arrayOfRecords }
// and converts them to a javascript object of the form
//  { collectionName : miniMongoCollection }
// where the miniMongo collection contains all of the records from
// both objects and the updateCollection overrides the first.
var createCollections = function (sources) {
  var finalCollections = {};
  // Start collections. Insert records.
  var meteorServer = getLoadedPackages()['meteor'];

  _.each(sources, function (source) {
    _.each(source, function (records, key) {
      if (!_.has(finalCollections, key)) {
        finalCollections[key] = new (meteorServer.Meteor.Collection)(null);
      }
      _.each(records, function (record) {
        finalCollections[key].remove(record._id);
        finalCollections[key].insert(record);
      });
    });
  });

  return finalCollections;
};

var writePackagesToDisk = function (syncToken, collectionData) {
  var finalWrite = {};
  finalWrite.syncToken = syncToken;
  finalWrite.formatVersion = "1.0";
  finalWrite.collections = {};
  _.forEach(collectionData, function(coll, name) {
    finalWrite.collections[name] = coll.find().fetch();
  });
  var filename = config.getPackageStorage();
  // XXX think about permissions?
  files.mkdir_p(path.dirname(filename));
  files.writeFileAtomically(filename, JSON.stringify(finalWrite, null, 2));
};

loadPackageData = function() {
  //XXX: We can consider optimizing this with concurrency or something.
  var sources = [];

  var localData = loadLocalPackageData();
  if (localData.collections)
    sources.push(localData.collections);
  var syncToken = localData.syncToken;

  // XXX support offline use too
  var remoteData = loadRemotePackageData(syncToken);
  sources.push(remoteData.collections);

  var allPackageData = createCollections(sources);
  writePackagesToDisk(remoteData.syncToken, allPackageData);
  return allPackageData;
};

// XXX onReconnect
// Returns a logged-in DDP connection to the package server, or null if
// we cannot log in.
// XXX needs a timeout
exports.loggedInPackagesConnection = function () {
  // Make sure that we are logged in with Meteor Accounts so that we can
  // do an OAuth flow.
  if (! auth.isLoggedIn()) {
    auth.doUsernamePasswordLogin({ retry: true });
  }

  var conn = openPackageServerConnection();

  var setUpOnReconnect = function () {
    conn.onReconnect = function () {
      conn.apply('login', [{
        resume: auth.getSessionToken(config.getPackageServerDomain())
      }], { wait: true }, function () { });
    };
  };

  // Subscribe to the package server's service configurations so that we
  // can get the OAuth client ID to kick off the OAuth flow.
  var serviceConfigurations = new (getLoadedPackages().meteor.Meteor.Collection)(
    'meteor_accounts_loginServiceConfiguration',
    { connection: conn }
  );
  var serviceConfigurationsSub = conn.
        _subscribeAndWait('meteor.loginServiceConfiguration');

  var accountsConfiguration = serviceConfigurations.findOne({
    service: 'meteor-developer'
  });

  var cleanUp = function () {
    serviceConfigurationsSub.stop();
    conn.close();
  };

  if (! accountsConfiguration || ! accountsConfiguration.clientId) {
    cleanUp();
    return null;
  }

  var clientId = accountsConfiguration.clientId;
  var loginResult;

  // Try to log in with an existing login token, if we have one.
  var existingToken = auth.getSessionToken(config.getPackageServerDomain());
  if (existingToken) {
    loginResult = conn.apply('login', [{
      resume: existingToken
    }], { wait: true });

    if (loginResult && loginResult.token && loginResult.id) {
      // Success!
      setUpOnReconnect();
      return conn;
    }
  }

  // Either we didn't have an existing token, or it didn't work. Do an
  // OAuth flow to log in.
  var redirectUri = config.getPackageServerUrl() +
        '/_oauth/meteor-developer?close';
  loginResult = auth.oauthFlow(conn, {
    clientId: clientId,
    redirectUri: redirectUri,
    domain: config.getPackageServerDomain(),
    sessionType: 'package-server'
  });

  if (loginResult && ! loginResult.error) {
    setUpOnReconnect();
    return conn;
  } else {
    process.stderr.write('Error logging in to package server: ' +
                         loginResult.error + '\n');
    cleanUp();
    return null;
  }
};

var hashTarball = function (tarball) {
  var crypto = require('crypto');
  var hash = crypto.createHash('sha256');
  hash.setEncoding('base64');
  var rs = fs.createReadStream(tarball);
  var fut = new Future();
  rs.on('end', function () {
    fut.return(hash.digest('base64'));
  });
  rs.pipe(hash, { end: false });
  var tarballHash = fut.wait();
  rs.close();
  return tarballHash;
};

exports.bundleSource = function (pkg, packageDir) {
  var name = pkg.name;
  var version = pkg.metadata.version;

  var tempDir = files.mkdtemp('build-source-package-');
  var packageTarName = name + '-' + version + '-source';
  var dirToTar = path.join(tempDir, 'source', packageTarName);
  var sourcePackageDir = path.join(
    dirToTar,
    name
  );
  if (! files.mkdir_p(sourcePackageDir)) {
    process.stderr.write('Failed to create temporary source directory: ' +
                         sourcePackageDir);
    return null;
  }

  // We copy source files into a temp directory and then tar up the temp
  // directory. It would be great if we could avoid the copy, but as far
  // as we can tell, this is the only way to get a tarball with the
  // directory structure that we want (<package name>-<version-source/
  // at the top level).
  files.cp_r(packageDir, sourcePackageDir, {
    include: pkg.sources
  });

  // We put this inside the temp dir because mkdtemp makes sure that the
  // temp dir gets cleaned up on process exit, so we don't have to worry
  // about cleaning up our tarball (or our copied source files)
  // ourselves.
  var sourceTarball = path.join(tempDir, packageTarName + '.tgz');
  files.createTarball(dirToTar, sourceTarball);

  var tarballHash = hashTarball(sourceTarball);

  return {
    sourceTarball: sourceTarball,
    tarballHash: tarballHash
  };
};

exports.uploadTarball = function (putUrl, tarball) {
  var size = fs.statSync(tarball).size;
  var rs = fs.createReadStream(tarball);
  httpHelpers.request({
    method: 'PUT',
    url: putUrl,
    headers: {
      'content-length': size,
      'content-type': 'application/octet-stream',
      'x-amz-acl': 'public-read'
    },
    bodyStream: rs
  });
  rs.close();
};

exports.bundleBuild = function (pkg, packageDir) {
  var tempDir = files.mkdtemp('build-package-');
  var packageTarName = pkg.name + '-' + pkg.metadata.version + '-' +
        pkg.architectures().join(',');

  files.cp_r(path.join(packageDir, '.build'),
             path.join(tempDir, packageTarName));

  var buildTarball = path.join(tempDir, packageTarName + '.tgz');
  files.createTarball(path.join(tempDir, packageTarName), buildTarball);

  var tarballHash = hashTarball(buildTarball);

  return {
    buildTarball: buildTarball,
    tarballHash: tarballHash
  };
};
<commit_msg>change another comma to plus<commit_after>var auth = require('./auth.js');
var config = require('./config.js');
var httpHelpers = require('./http-helpers.js');
var release = require('./release.js');
var files = require('./files.js');
var fs = require('fs');
var path = require('path');
var Future = require('fibers/future');
var _ = require('underscore');

var getLoadedPackages = _.once(function () {
  var unipackage = require('./unipackage.js');
  return unipackage.load({
    library: release.current.library,
    packages: [ 'meteor', 'livedata', 'minimongo', 'mongo-livedata' ],
    release: release.current.name
  });
});

var openPackageServerConnection = function () {
  var DDP = getLoadedPackages().livedata.DDP;
  return DDP.connect(config.getPackageServerUrl(), {
    headers: { 'User-Agent': httpHelpers.getUserAgent() }
  });
};

var loadLocalPackageData = function () {
  // XXX pretty error handling
  try {
    var data = fs.readFileSync(config.getPackageStorage(), 'utf8');
  } catch (e) {
    if (e.code !== 'ENOENT')
      throw e;
    // Default: no data, send us everything.
    return {
      // XXX have a better sync token for "all"
      syncToken: {time: 'Sun, 01 Jan 2012 00:00:00 GMT'},
      collections: null
    };
  }
  return JSON.parse(data);
};

var loadRemotePackageData = function (syncToken) {
  var conn = openPackageServerConnection();
  var collectionData = conn.call('syncNewPackageData', syncToken);
  conn.close();
  return collectionData;
};

// Takes in two javascript objects of the form:
//  { collectionName : arrayOfRecords }
// and converts them to a javascript object of the form
//  { collectionName : miniMongoCollection }
// where the miniMongo collection contains all of the records from
// both objects and the updateCollection overrides the first.
var createCollections = function (sources) {
  var finalCollections = {};
  // Start collections. Insert records.
  var meteorServer = getLoadedPackages()['meteor'];

  _.each(sources, function (source) {
    _.each(source, function (records, key) {
      if (!_.has(finalCollections, key)) {
        finalCollections[key] = new (meteorServer.Meteor.Collection)(null);
      }
      _.each(records, function (record) {
        finalCollections[key].remove(record._id);
        finalCollections[key].insert(record);
      });
    });
  });

  return finalCollections;
};

var writePackagesToDisk = function (syncToken, collectionData) {
  var finalWrite = {};
  finalWrite.syncToken = syncToken;
  finalWrite.formatVersion = "1.0";
  finalWrite.collections = {};
  _.forEach(collectionData, function(coll, name) {
    finalWrite.collections[name] = coll.find().fetch();
  });
  var filename = config.getPackageStorage();
  // XXX think about permissions?
  files.mkdir_p(path.dirname(filename));
  files.writeFileAtomically(filename, JSON.stringify(finalWrite, null, 2));
};

loadPackageData = function() {
  //XXX: We can consider optimizing this with concurrency or something.
  var sources = [];

  var localData = loadLocalPackageData();
  if (localData.collections)
    sources.push(localData.collections);
  var syncToken = localData.syncToken;

  // XXX support offline use too
  var remoteData = loadRemotePackageData(syncToken);
  sources.push(remoteData.collections);

  var allPackageData = createCollections(sources);
  writePackagesToDisk(remoteData.syncToken, allPackageData);
  return allPackageData;
};

// XXX onReconnect
// Returns a logged-in DDP connection to the package server, or null if
// we cannot log in.
// XXX needs a timeout
exports.loggedInPackagesConnection = function () {
  // Make sure that we are logged in with Meteor Accounts so that we can
  // do an OAuth flow.
  if (! auth.isLoggedIn()) {
    auth.doUsernamePasswordLogin({ retry: true });
  }

  var conn = openPackageServerConnection();

  var setUpOnReconnect = function () {
    conn.onReconnect = function () {
      conn.apply('login', [{
        resume: auth.getSessionToken(config.getPackageServerDomain())
      }], { wait: true }, function () { });
    };
  };

  // Subscribe to the package server's service configurations so that we
  // can get the OAuth client ID to kick off the OAuth flow.
  var serviceConfigurations = new (getLoadedPackages().meteor.Meteor.Collection)(
    'meteor_accounts_loginServiceConfiguration',
    { connection: conn }
  );
  var serviceConfigurationsSub = conn.
        _subscribeAndWait('meteor.loginServiceConfiguration');

  var accountsConfiguration = serviceConfigurations.findOne({
    service: 'meteor-developer'
  });

  var cleanUp = function () {
    serviceConfigurationsSub.stop();
    conn.close();
  };

  if (! accountsConfiguration || ! accountsConfiguration.clientId) {
    cleanUp();
    return null;
  }

  var clientId = accountsConfiguration.clientId;
  var loginResult;

  // Try to log in with an existing login token, if we have one.
  var existingToken = auth.getSessionToken(config.getPackageServerDomain());
  if (existingToken) {
    loginResult = conn.apply('login', [{
      resume: existingToken
    }], { wait: true });

    if (loginResult && loginResult.token && loginResult.id) {
      // Success!
      setUpOnReconnect();
      return conn;
    }
  }

  // Either we didn't have an existing token, or it didn't work. Do an
  // OAuth flow to log in.
  var redirectUri = config.getPackageServerUrl() +
        '/_oauth/meteor-developer?close';
  loginResult = auth.oauthFlow(conn, {
    clientId: clientId,
    redirectUri: redirectUri,
    domain: config.getPackageServerDomain(),
    sessionType: 'package-server'
  });

  if (loginResult && ! loginResult.error) {
    setUpOnReconnect();
    return conn;
  } else {
    process.stderr.write('Error logging in to package server: ' +
                         loginResult.error + '\n');
    cleanUp();
    return null;
  }
};

var hashTarball = function (tarball) {
  var crypto = require('crypto');
  var hash = crypto.createHash('sha256');
  hash.setEncoding('base64');
  var rs = fs.createReadStream(tarball);
  var fut = new Future();
  rs.on('end', function () {
    fut.return(hash.digest('base64'));
  });
  rs.pipe(hash, { end: false });
  var tarballHash = fut.wait();
  rs.close();
  return tarballHash;
};

exports.bundleSource = function (pkg, packageDir) {
  var name = pkg.name;
  var version = pkg.metadata.version;

  var tempDir = files.mkdtemp('build-source-package-');
  var packageTarName = name + '-' + version + '-source';
  var dirToTar = path.join(tempDir, 'source', packageTarName);
  var sourcePackageDir = path.join(
    dirToTar,
    name
  );
  if (! files.mkdir_p(sourcePackageDir)) {
    process.stderr.write('Failed to create temporary source directory: ' +
                         sourcePackageDir);
    return null;
  }

  // We copy source files into a temp directory and then tar up the temp
  // directory. It would be great if we could avoid the copy, but as far
  // as we can tell, this is the only way to get a tarball with the
  // directory structure that we want (<package name>-<version-source/
  // at the top level).
  files.cp_r(packageDir, sourcePackageDir, {
    include: pkg.sources
  });

  // We put this inside the temp dir because mkdtemp makes sure that the
  // temp dir gets cleaned up on process exit, so we don't have to worry
  // about cleaning up our tarball (or our copied source files)
  // ourselves.
  var sourceTarball = path.join(tempDir, packageTarName + '.tgz');
  files.createTarball(dirToTar, sourceTarball);

  var tarballHash = hashTarball(sourceTarball);

  return {
    sourceTarball: sourceTarball,
    tarballHash: tarballHash
  };
};

exports.uploadTarball = function (putUrl, tarball) {
  var size = fs.statSync(tarball).size;
  var rs = fs.createReadStream(tarball);
  httpHelpers.request({
    method: 'PUT',
    url: putUrl,
    headers: {
      'content-length': size,
      'content-type': 'application/octet-stream',
      'x-amz-acl': 'public-read'
    },
    bodyStream: rs
  });
  rs.close();
};

exports.bundleBuild = function (pkg, packageDir) {
  var tempDir = files.mkdtemp('build-package-');
  var packageTarName = pkg.name + '-' + pkg.metadata.version + '-' +
        pkg.architectures().join('+');

  files.cp_r(path.join(packageDir, '.build'),
             path.join(tempDir, packageTarName));

  var buildTarball = path.join(tempDir, packageTarName + '.tgz');
  files.createTarball(path.join(tempDir, packageTarName), buildTarball);

  var tarballHash = hashTarball(buildTarball);

  return {
    buildTarball: buildTarball,
    tarballHash: tarballHash
  };
};
<|endoftext|>


<commit_before>var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var createTextLabelsTabPane = require('../components/tab-pane/create-text-labels-tab-pane');
var AddWidgetsView = require('../components/modals/add-widgets/add-widgets-view');
var AddLayerView = require('../components/modals/add-layer/add-layer-view');
var AddLayerModel = require('../components/modals/add-layer/add-layer-model');
var StackLayoutView = require('../components/stack-layout/stack-layout-view');
var PrivacyView = require('../components/modals/privacy/privacy-view');
var CreatePrivacyOptions = require('../components/modals/privacy/create-privacy-options');
var PrivacyCollection = require('../components/modals/privacy/privacy-collection');
var CreateShareOptions = require('../components/modals/share/create-share-options');
var ShareCollection = require('../components/modals/share/share-collection');
var Header = require('./editor-header.js');
var EditorTabPaneTemplate = require('./editor-tab-pane.tpl');
var EditorWidgetsView = require('./widgets/widgets-view');
var LayersView = require('./layers/layers-view');
var ScrollView = require('../components/scroll/scroll-view');
var PanelWithOptionsView = require('./components/view-options/panel-with-options-view');
var ShareView = require('../components/modals/share/share-view');
var ShareButtonView = require('./layers/share-button-view');

module.exports = CoreView.extend({
  events: {
    'click .js-add': '_addItem'
  },

  initialize: function (opts) {
    if (!opts.analysisDefinitionNodesCollection) throw new Error('analysisDefinitionNodesCollection is required');
    if (!opts.layerDefinitionsCollection) throw new Error('layerDefinitionsCollection is required');
    if (!opts.widgetDefinitionsCollection) throw new Error('widgetDefinitionsCollection is required');
    if (!opts.visDefinitionModel) throw new Error('visDefinitionModel is required');
    if (!opts.analysis) throw new Error('analysis is required');
    if (!opts.modals) throw new Error('modals is required');
    if (!opts.mapStackLayoutModel) throw new Error('mapStackLayoutModel is required');
    if (!opts.userModel) throw new Error('userModel is required');
    if (!opts.configModel) throw new Error('configModel is required');
    if (!opts.editorModel) throw new Error('editorModel is required');
    if (!opts.pollingModel) throw new Error('pollingModel is required');

    this._analysis = opts.analysis;
    this._modals = opts.modals;
    this._configModel = opts.configModel;
    this._userModel = opts.userModel;
    this._editorModel = opts.editorModel;
    this._pollingModel = opts.pollingModel;
    this._analysisDefinitionNodesCollection = opts.analysisDefinitionNodesCollection;
    this._layerDefinitionsCollection = opts.layerDefinitionsCollection;
    this._widgetDefinitionsCollection = opts.widgetDefinitionsCollection;
    this._visDefinitionModel = opts.visDefinitionModel;
    this._mapStackLayoutModel = opts.mapStackLayoutModel;

    var privacyOptions = CreatePrivacyOptions(this._visDefinitionModel, this._userModel);
    this._privacyCollection = new PrivacyCollection(privacyOptions);

    var shareOptions = CreateShareOptions(this._visDefinitionModel);
    this._shareCollection = new ShareCollection(shareOptions);

    this._layerDefinitionsCollection.on('reset remove add', this._updateAddButtonState, this);
    this._widgetDefinitionsCollection.on('reset remove add', this._updateAddButtonState, this);
    this._editorModel.on('change:edition', this._changeStyle, this);
    this.add_related_model(this._editorModel);
  },

  render: function () {
    var self = this;

    var tabPaneTabs = [{
      name: 'layers',
      label: _t('editor.tab-pane.layers.title-label'),
      selected: this.options.selectedTabItem === 'layers',
      createContentView: function () {
        var layersStackViewCollection = new Backbone.Collection([{
          createStackView: function (stackLayoutModel, opts) {
            return new PanelWithOptionsView({
              className: 'Editor-content',
              editorModel: self._editorModel,
              createContentView: function () {
                return new ScrollView({
                  createContentView: function () {
                    return new LayersView({
                      userModel: self._userModel,
                      editorModel: self._editorModel,
                      configModel: self._configModel,
                      layerDefinitionsCollection: self._layerDefinitionsCollection,
                      analysisDefinitionNodesCollection: self._analysisDefinitionNodesCollection,
                      analysis: self._analysis,
                      stackLayoutModel: self._mapStackLayoutModel
                    });
                  }
                });
              },
              createActionView: function () {
                return new ShareButtonView({
                  onClickAction: self._share.bind(self)
                });
              }
            });
          }

        }]);

        return new StackLayoutView({
          className: 'Editor-content',
          collection: layersStackViewCollection
        });
      }
    }, {
      name: 'elements',
      label: _t('editor.tab-pane.elements.title-label'),
      selected: this.options.selectedTabItem === 'elements',
      createContentView: function () {
        return new CoreView();
      }
    }, {
      name: 'widgets',
      label: _t('editor.tab-pane.widgets.title-label'),
      selected: this.options.selectedTabItem === 'widgets',
      createContentView: function () {
        var widgetsStackViewCollection = new Backbone.Collection([{
          createStackView: function (stackLayoutModel, opts) {
            return new ScrollView({
              createContentView: function () {
                return new EditorWidgetsView({
                  modals: self._modals,
                  configModel: self._configModel,
                  layerDefinitionsCollection: self._layerDefinitionsCollection,
                  widgetDefinitionsCollection: self._widgetDefinitionsCollection,
                  stackLayoutModel: self._mapStackLayoutModel
                });
              }
            });
          }
        }]);

        return new StackLayoutView({
          className: 'Editor-content',
          collection: widgetsStackViewCollection
        });
      }
    }];

    var header = new Header({
      editorModel: self._editorModel,
      visDefinitionModel: self._visDefinitionModel,
      privacyCollection: self._privacyCollection,
      onClickPrivacy: self._changePrivacy.bind(self)
    });

    this.$el.append(header.render().$el);
    this.addView(header);

    var tabPaneOptions = {
      tabPaneOptions: {
        template: EditorTabPaneTemplate,
        tabPaneItemOptions: {
          tagName: 'li',
          className: 'CDB-NavMenu-item'
        }
      },
      tabPaneItemLabelOptions: {
        tagName: 'button',
        className: 'CDB-NavMenu-link u-upperCase'
      }
    };

    this._mapTabPaneView = createTextLabelsTabPane(tabPaneTabs, tabPaneOptions);
    this._mapTabPaneView.collection.bind('change:selected', this._updateAddButtonState, this);

    this.$el.append(this._mapTabPaneView.render().$el);
    this.addView(this._mapTabPaneView);

    this._updateAddButtonState();

    return this;
  },

  _hideAddButton: function () {
    this.$('.js-add').addClass('is-hidden');
  },

  _showAddButton: function () {
    this.$('.js-add').removeClass('is-hidden');
  },

  _updateAddButtonState: function () {
    this._hideAddButton();

    switch (this._mapTabPaneView.getSelectedTabPaneName()) {
      case 'widgets':
        if (this._widgetDefinitionsCollection.size()) {
          this._showAddButton();
        }
        break;
      case 'layers':
        if (this._layerDefinitionsCollection.size()) {
          this._showAddButton();
        }
        break;
      case 'elements':
        // TODO: trigger element creation
        break;
    }
  },

  _addItem: function () {
    switch (this._mapTabPaneView.getSelectedTabPaneName()) {
      case 'widgets': this._addWidget();
        break;
      case 'layers': this._addLayer();
        break;
      case 'elements':
        // TODO: trigger element creation
        break;
    }
  },

  _addLayer: function () {
    var self = this;
    var modal = this._modals.create(function (modalModel) {
      var addLayerModel = new AddLayerModel({}, {
        userModel: self._userModel,
        layerDefinitionsCollection: self._layerDefinitionsCollection,
        configModel: self._configModel,
        pollingModel: self._pollingModel
      });

      return new AddLayerView({
        modalModel: modalModel,
        configModel: self._configModel,
        userModel: self._userModel,
        createModel: addLayerModel,
        pollingModel: self._pollingModel
      });
    });
    modal.show();
  },

  _addWidget: function () {
    var self = this;

    this._modals.create(function (modalModel) {
      return new AddWidgetsView({
        modalModel: modalModel,
        configModel: self._configModel,
        layerDefinitionsCollection: self._layerDefinitionsCollection,
        widgetDefinitionsCollection: self._widgetDefinitionsCollection
      });
    });
  },

  _share: function () {
    var self = this;

    this._modals.create(function (modalModel) {
      return new ShareView({
        collection: self._shareCollection,
        modalModel: modalModel,
        configModel: self._configModel,
        visDefinitionModel: self._visDefinitionModel,
        userModel: self._userModel,
        onChangePrivacy: self._changePrivacy.bind(self)
      });
    });
  },

  _changePrivacy: function () {
    var self = this;

    this._modals.create(function (modalModel) {
      return new PrivacyView({
        modalModel: modalModel,
        configModel: self._configModel,
        userModel: self._userModel,
        visDefinitionModel: self._visDefinitionModel,
        privacyCollection: self._privacyCollection
      });
    });
  },

  _changeStyle: function (m) {
    this.$el.toggleClass('is-dark');
    this._mapTabPaneView.changeStyleMenu(m);
  }
});
<commit_msg>Fix merge.<commit_after>var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var createTextLabelsTabPane = require('../components/tab-pane/create-text-labels-tab-pane');
var AddWidgetsView = require('../components/modals/add-widgets/add-widgets-view');
var AddLayerView = require('../components/modals/add-layer/add-layer-view');
var AddLayerModel = require('../components/modals/add-layer/add-layer-model');
var StackLayoutView = require('../components/stack-layout/stack-layout-view');
var PrivacyView = require('../components/modals/privacy/privacy-view');
var CreatePrivacyOptions = require('../components/modals/privacy/create-privacy-options');
var PrivacyCollection = require('../components/modals/privacy/privacy-collection');
var CreateShareOptions = require('../components/modals/share/create-share-options');
var ShareCollection = require('../components/modals/share/share-collection');
var Header = require('./editor-header.js');
var EditorTabPaneTemplate = require('./editor-tab-pane.tpl');
var EditorWidgetsView = require('./widgets/widgets-view');
var LayersView = require('./layers/layers-view');
var ScrollView = require('../components/scroll/scroll-view');
var PanelWithOptionsView = require('./components/view-options/panel-with-options-view');
var ShareView = require('../components/modals/share/share-view');
var ShareButtonView = require('./layers/share-button-view');

module.exports = CoreView.extend({
  events: {
    'click .js-add': '_addItem'
  },

  initialize: function (opts) {
    if (!opts.analysisDefinitionNodesCollection) throw new Error('analysisDefinitionNodesCollection is required');
    if (!opts.layerDefinitionsCollection) throw new Error('layerDefinitionsCollection is required');
    if (!opts.widgetDefinitionsCollection) throw new Error('widgetDefinitionsCollection is required');
    if (!opts.visDefinitionModel) throw new Error('visDefinitionModel is required');
    if (!opts.analysis) throw new Error('analysis is required');
    if (!opts.modals) throw new Error('modals is required');
    if (!opts.mapStackLayoutModel) throw new Error('mapStackLayoutModel is required');
    if (!opts.userModel) throw new Error('userModel is required');
    if (!opts.configModel) throw new Error('configModel is required');
    if (!opts.editorModel) throw new Error('editorModel is required');
    if (!opts.pollingModel) throw new Error('pollingModel is required');

    this._analysis = opts.analysis;
    this._modals = opts.modals;
    this._configModel = opts.configModel;
    this._userModel = opts.userModel;
    this._editorModel = opts.editorModel;
    this._pollingModel = opts.pollingModel;
    this._analysisDefinitionNodesCollection = opts.analysisDefinitionNodesCollection;
    this._layerDefinitionsCollection = opts.layerDefinitionsCollection;
    this._widgetDefinitionsCollection = opts.widgetDefinitionsCollection;
    this._visDefinitionModel = opts.visDefinitionModel;
    this._mapStackLayoutModel = opts.mapStackLayoutModel;

    var privacyOptions = CreatePrivacyOptions(this._visDefinitionModel, this._userModel);
    this._privacyCollection = new PrivacyCollection(privacyOptions);

    var shareOptions = CreateShareOptions(this._visDefinitionModel);
    this._shareCollection = new ShareCollection(shareOptions);

    this._layerDefinitionsCollection.on('reset remove add', this._updateAddButtonState, this);
    this._widgetDefinitionsCollection.on('reset remove add', this._updateAddButtonState, this);
    this._editorModel.on('change:edition', this._changeStyle, this);
    this.add_related_model(this._editorModel);
  },

  render: function () {
    var self = this;

    var tabPaneTabs = [{
      name: 'layers',
      label: _t('editor.tab-pane.layers.title-label'),
      selected: this.options.selectedTabItem === 'layers',
      createContentView: function () {
        var layersStackViewCollection = new Backbone.Collection([{
          createStackView: function (stackLayoutModel, opts) {
            return new PanelWithOptionsView({
              className: 'Editor-content',
              editorModel: self._editorModel,
              createContentView: function () {
                return new ScrollView({
                  createContentView: function () {
                    return new LayersView({
                      modals: self._modals,
                      userModel: self._userModel,
                      editorModel: self._editorModel,
                      configModel: self._configModel,
                      layerDefinitionsCollection: self._layerDefinitionsCollection,
                      analysisDefinitionNodesCollection: self._analysisDefinitionNodesCollection,
                      analysis: self._analysis,
                      stackLayoutModel: self._mapStackLayoutModel
                    });
                  }
                });
              },
              createActionView: function () {
                return new ShareButtonView({
                  onClickAction: self._share.bind(self)
                });
              }
            });
          }

        }]);

        return new StackLayoutView({
          className: 'Editor-content',
          collection: layersStackViewCollection
        });
      }
    }, {
      name: 'elements',
      label: _t('editor.tab-pane.elements.title-label'),
      selected: this.options.selectedTabItem === 'elements',
      createContentView: function () {
        return new CoreView();
      }
    }, {
      name: 'widgets',
      label: _t('editor.tab-pane.widgets.title-label'),
      selected: this.options.selectedTabItem === 'widgets',
      createContentView: function () {
        var widgetsStackViewCollection = new Backbone.Collection([{
          createStackView: function (stackLayoutModel, opts) {
            return new ScrollView({
              createContentView: function () {
                return new EditorWidgetsView({
                  modals: self._modals,
                  configModel: self._configModel,
                  layerDefinitionsCollection: self._layerDefinitionsCollection,
                  widgetDefinitionsCollection: self._widgetDefinitionsCollection,
                  stackLayoutModel: self._mapStackLayoutModel
                });
              }
            });
          }
        }]);

        return new StackLayoutView({
          className: 'Editor-content',
          collection: widgetsStackViewCollection
        });
      }
    }];

    var header = new Header({
      editorModel: self._editorModel,
      visDefinitionModel: self._visDefinitionModel,
      privacyCollection: self._privacyCollection,
      onClickPrivacy: self._changePrivacy.bind(self)
    });

    this.$el.append(header.render().$el);
    this.addView(header);

    var tabPaneOptions = {
      tabPaneOptions: {
        template: EditorTabPaneTemplate,
        tabPaneItemOptions: {
          tagName: 'li',
          className: 'CDB-NavMenu-item'
        }
      },
      tabPaneItemLabelOptions: {
        tagName: 'button',
        className: 'CDB-NavMenu-link u-upperCase'
      }
    };

    this._mapTabPaneView = createTextLabelsTabPane(tabPaneTabs, tabPaneOptions);
    this._mapTabPaneView.collection.bind('change:selected', this._updateAddButtonState, this);

    this.$el.append(this._mapTabPaneView.render().$el);
    this.addView(this._mapTabPaneView);

    this._updateAddButtonState();

    return this;
  },

  _hideAddButton: function () {
    this.$('.js-add').addClass('is-hidden');
  },

  _showAddButton: function () {
    this.$('.js-add').removeClass('is-hidden');
  },

  _updateAddButtonState: function () {
    this._hideAddButton();

    switch (this._mapTabPaneView.getSelectedTabPaneName()) {
      case 'widgets':
        if (this._widgetDefinitionsCollection.size()) {
          this._showAddButton();
        }
        break;
      case 'layers':
        if (this._layerDefinitionsCollection.size()) {
          this._showAddButton();
        }
        break;
      case 'elements':
        // TODO: trigger element creation
        break;
    }
  },

  _addItem: function () {
    switch (this._mapTabPaneView.getSelectedTabPaneName()) {
      case 'widgets': this._addWidget();
        break;
      case 'layers': this._addLayer();
        break;
      case 'elements':
        // TODO: trigger element creation
        break;
    }
  },

  _addLayer: function () {
    var self = this;
    var modal = this._modals.create(function (modalModel) {
      var addLayerModel = new AddLayerModel({}, {
        userModel: self._userModel,
        layerDefinitionsCollection: self._layerDefinitionsCollection,
        configModel: self._configModel,
        pollingModel: self._pollingModel
      });

      return new AddLayerView({
        modalModel: modalModel,
        configModel: self._configModel,
        userModel: self._userModel,
        createModel: addLayerModel,
        pollingModel: self._pollingModel
      });
    });
    modal.show();
  },

  _addWidget: function () {
    var self = this;

    this._modals.create(function (modalModel) {
      return new AddWidgetsView({
        modalModel: modalModel,
        configModel: self._configModel,
        layerDefinitionsCollection: self._layerDefinitionsCollection,
        widgetDefinitionsCollection: self._widgetDefinitionsCollection
      });
    });
  },

  _share: function () {
    var self = this;

    this._modals.create(function (modalModel) {
      return new ShareView({
        collection: self._shareCollection,
        modalModel: modalModel,
        configModel: self._configModel,
        visDefinitionModel: self._visDefinitionModel,
        userModel: self._userModel,
        onChangePrivacy: self._changePrivacy.bind(self)
      });
    });
  },

  _changePrivacy: function () {
    var self = this;

    this._modals.create(function (modalModel) {
      return new PrivacyView({
        modalModel: modalModel,
        configModel: self._configModel,
        userModel: self._userModel,
        visDefinitionModel: self._visDefinitionModel,
        privacyCollection: self._privacyCollection
      });
    });
  },

  _changeStyle: function (m) {
    this.$el.toggleClass('is-dark');
    this._mapTabPaneView.changeStyleMenu(m);
  }
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'

import Loading from './loading'
import NarrativeItineraries from './narrative-itineraries'
import NarrativeProfileOptions from './narrative-profile-options'

import { getActiveSearch } from '../../util/state'

class NarrativeRoutingResults extends Component {
  static propTypes = {
    customIcons: PropTypes.object,
    itineraryClass: PropTypes.object,
    routingType: PropTypes.string
  }

  render () {
    const { customIcons, itineraryClass, pending, routingType } = this.props
    if (pending) return <Loading />

    return (
      routingType === 'ITINERARY'
        ? <NarrativeItineraries itineraryClass={itineraryClass} />
        : <NarrativeProfileOptions
          itineraryClass={itineraryClass}
          customIcons={customIcons}
        />
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  const activeSearch = getActiveSearch(state.otp)

  return {
    pending: activeSearch && activeSearch.pending,
    routingType: activeSearch && activeSearch.query.routingType
  }
}

const mapDispatchToProps = (dispatch, ownProps) => { }

export default connect(mapStateToProps, mapDispatchToProps)(NarrativeRoutingResults)
<commit_msg>fix(narrative): silence react warnings<commit_after>import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'

import Loading from './loading'
import NarrativeItineraries from './narrative-itineraries'
import NarrativeProfileOptions from './narrative-profile-options'

import { getActiveSearch } from '../../util/state'

class NarrativeRoutingResults extends Component {
  static propTypes = {
    customIcons: PropTypes.object,
    itineraryClass: PropTypes.func,
    routingType: PropTypes.string
  }

  render () {
    const { customIcons, itineraryClass, pending, routingType } = this.props
    if (pending) return <Loading />

    return (
      routingType === 'ITINERARY'
        ? <NarrativeItineraries itineraryClass={itineraryClass} />
        : <NarrativeProfileOptions
          itineraryClass={itineraryClass}
          customIcons={customIcons}
        />
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  const activeSearch = getActiveSearch(state.otp)

  return {
    pending: activeSearch && activeSearch.pending,
    routingType: activeSearch && activeSearch.query.routingType
  }
}

const mapDispatchToProps = { }

export default connect(mapStateToProps, mapDispatchToProps)(NarrativeRoutingResults)
<|endoftext|>