<commit_before>(function(){

var facility_map_obj = false;

$(function(){
    new Backbone.Router({
        routes: {
            '': index,
            ':unique_lga/lga_overview': view(LGAView, 'overview'),
            ':unique_lga/lga_health': view(LGAView, 'health'),
            ':unique_lga/lga_education': view(LGAView, 'education'),
            ':unique_lga/lga_water': view(LGAView, 'water'),
            ':unique_lga/map_overview': view(MapView, 'overview'),
            ':unique_lga/map_health': view(MapView, 'health'),
            ':unique_lga/map_education': view(MapView, 'education'),
            ':unique_lga/map_water': view(MapView, 'water'),
            ':unique_lga/table_overview': view(TableView, 'overview'),
            ':unique_lga/table_health': view(TableView, 'health'),
            ':unique_lga/table_education': view(TableView, 'education'),
            ':unique_lga/table_water': view(TableView, 'water')
        }
    });
    Backbone.history.start();
});

// Helper Functions
// =================
function view(viewObj, sector){
    // Wrapper for LGA based views. Fetches the appropriate
    // LGA JSON data before calling the render() function of a view.

    if (viewObj.init) viewObj.init();

    function render(lga, sector){
        $('.facility_map').hide();
        $(window).scrollTop(0);
        viewObj.render(lga, sector);
    }

    return function(unique_lga){
        var lga = NMIS.lgas[unique_lga];
        if (lga){
            render(lga, sector);
        } else {
            var url = '/static/data/lgas/' + unique_lga + '.json';
            $.getJSON(url, function(lga){
                NMIS.lgas[unique_lga] = lga;
                render(lga, sector);
            });
        }
    }
}

function render_nav(lga, active_view, sector){
    // Renders the LGA navigation bar
    var template = $('#lga_nav_template').html();
    var html = _.template(template, {
        lga: lga,
        active_view: active_view,
        sector: sector
    });
    $('.lga_nav').html(html).show();
}

function render(template_id, context){
    // Renders an underscore template to the dom
    var template = $(template_id).html();
    context.NMIS = NMIS;
    context.format_value = format_value;
    context.indicator_name = indicator_name;
    var html = _.template(template, context);
    $('#content .content').html(html);
}

function format_value(value){
    // Formats indicator values for use in tables
    if (typeof value === 'undefined' ||
        value === null) return '-';
    if (value === true) return 'Yes';
    if (value === false) return 'No';
    if (_.isNumber(value) && value % 1 !== 0)
        return value.toFixed(2);
    if (_.isString(value))
        return value[0].toUpperCase() + value.substr(1);
    return value;
}

function indicator_name(slug){
    var indicator = NMIS.indicators[slug];
    return indicator ? indicator.name : slug;
}

// Views
// ============
function index(){
    $('.lga_nav').hide();
    render('#index_template', {zones: NMIS.zones});
    $('#zone-navigation .state-link').click(function(){
        $(this).next('.lga-list').toggle();
        return false;
    });
};

var LGAView = {};
LGAView.render = function(lga, sector){
    render_nav(lga, 'lga', sector);

    if (sector === 'overview'){
        render('#lga_overview_template', {
            lga: lga,
            lga_overview: NMIS.lga_overview
        });
        this.overview_map(lga);
    } else {
        render('#lga_view_template', {
            lga: lga,
            lga_view: NMIS.lga_view,
            sector: sector
        });
    }
};
LGAView.overview_map = function(lga){
    var map_div = $('.map')[0];
    var lat_lng = new L.LatLng(lga.latitude, lga.longitude);
    var map_zoom = 9;
    var summary_map = L.map(map_div, {scrollWheelZoom: false})
            .setView(lat_lng, map_zoom);
    var tile_server = 'http://{s}.tiles.mapbox.com/v3/' +
        'modilabs.nigeria_base/{z}/{x}/{y}.png';
    L.tileLayer(tile_server, {
        minZoom: 6,
        maxZoom: 11
    }).addTo(summary_map);
};

var MapView = {};
MapView.init = function(){
    $('.map_view_legend').on('click', '.close', function(){
        $(this).parent().hide();
        return false;
    });
};

MapView.render = function(lga, sector){
    var self = this;
    render_nav(lga, 'map', sector);
    render('#map_view_template', {
        lga: lga,
        sector: sector,
        chart_indicators: this.chart_indicators(lga.facilities, sector)
    });

    $('.map_view_legend').hide();

    this.facility_map(lga, sector);

    $('.pie_chart_selector').change(function(){
        if (this.value){
            $('.map_view_legend').show();
            self.map_legend(lga, sector, this.value);
        } else {
            $('.map_view_legend').hide();
        }
        self.facility_map(lga, sector, this.value);
    });
};

MapView.facility_map = function(lga, sector, indicator) {
    var lat_lng = new L.LatLng(lga.latitude, lga.longitude);
    var map_div = $('.facility_map').show()[0];
    var map = map_div._facility_map;

    if (!map){
        // Initialize Leaflet
        map = new L.Map(map_div, {scrollWheelZoom: false})
            .setView(lat_lng, 10);
        var lga_layer = new L.TileLayer(
            'http://{s}.tiles.mapbox.com/v3/modilabs.nigeria_overlays_white/{z}/{x}/{y}.png', {
                minZoom: 6,
                maxZoom: 10
            });
        var google_layer = new L.TileLayer(
            'http://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
                maxZoom: 18,
                minZoom: 3
            });
        google_layer.addTo(map);
        lga_layer.addTo(map);
        map_div._facility_map = map;
        map._unique_lga = lga.unique_lga;
    }

    if (map._facility_layer)
        map.removeLayer(map._facility_layer);

    if (map._unique_lga !== lga.unique_lga){
        map._unique_lga = lga.unique_lga;
        map.setView(lat_lng, 10);
    }
    map._facility_layer = this.facility_layer(lga.facilities, sector, indicator);
    map._facility_layer.addTo(map);
};

MapView.facility_layer = function(facilities, sector, indicator) {
    var that = this;
    var marker_group = new L.LayerGroup();
    _.each(facilities, function(fac){
        if (fac.sector === sector || sector === 'overview') {
            var lat_lng = fac.gps.split(' ').slice(0,2);
            var icon_url;
            if (indicator) {
                if (fac[indicator] === true ||
                    fac[indicator] === false) {
                    icon_url = 'static/images/icons_f/' +
                        fac[indicator] +'.png';
                } else {
                    icon_url = 'static/images/icons_f/' +
                        'undefined.png';
                }
            } else {
                icon_url = 'static/images/icons_f/normal_' +
                    fac.sector + '.png';
            }
            var icon = new L.Icon({iconUrl: icon_url});
            var mark = new L.Marker(lat_lng, {icon: icon});
            var popup = new L.Popup({closeButton: false})
                .setContent(fac.facility_name)
                .setLatLng(lat_lng);
            mark.on('click', function(){
                that.facility_modal(fac);
            });
            mark.on('mouseover', mark.openPopup.bind(mark))
                .on('mouseout', mark.closePopup.bind(mark))
                .bindPopup(popup);
            marker_group.addLayer(mark);
        }
    });
    return marker_group;
};

MapView.chart_indicators = function(facilities, sector){
    // Iterates through facilities within a sector to find
    // indicators which contain boolean values.
    // Returns a list of [indicator, indicator_name]
    var indicators = {};
    for (var i=0, facility; facility=facilities[i]; i++){
        if (facility.sector === sector){
            for (var indicator in facility){
                if (facility.hasOwnProperty(indicator)){
                    var value = facility[indicator];
                    if (value === false || value === true)
                        indicators[indicator] = 1;
                }
            }
        }
    }
    var chart_indicators = [];
    _.each(_.keys(indicators), function(indicator){
        chart_indicators.push([
            indicator, indicator_name(indicator)
        ]);
    });
    chart_indicators.sort(function(a,b){
        if (a[1] > b[1]) return 1;
        else if (a[1] < b[1]) return -1;
        return 0;
    });
    return chart_indicators;
};

MapView.facility_modal = function(facility){
    var that = this;
    var template = $('#facility_modal_template').html();
    var html = _.template(template, {
        NMIS: NMIS,
        facility: facility,
        tables: NMIS.table_view[facility.sector]
    });
    $('#facility_modal').remove();
    $('#content').append(html);
    $('#facility_modal').modal();
    $('.facility_table_selector').change(function(){
        var index = parseInt(this.value);
        that.facility_table(facility, index);
    });
    this.facility_table(facility, 0);
};

MapView.facility_table = function(facility, index){
    var aoColumns = [{sTitle: 'Indicator'}, {sTitle: 'Value'}];
    var table = NMIS.table_view[facility.sector][index];
    var aaData = [];

    _.each(table.indicators, function(indicator){
        aaData.push([
            indicator_name(indicator),
            format_value(facility[indicator])
        ]);
    });

    $('.facility_table')
        .dataTable({
            aaData: aaData,
            aoColumns: aoColumns,
            bFilter: false,
            bPaginate: false,
            bDestroy: true
        })
        .width('100%');
};

MapView.map_legend = function(lga, sector, indicator){
    var ctx = $('.map_view_legend canvas')[0].getContext('2d');
    var trues = 0;
    var falses = 0;
    var unknowns = 0;
    _.each(lga.facilities, function(facility){
        if (facility.sector === sector){
            var value = facility[indicator];
            if (value) trues++;
            else if (value === false) falses++;
            else unknowns++;
        }
    });
    var total = trues + falses + unknowns;
    var data = [{
        value: trues / total * 100,
        color: 'rgb(68, 167, 0)'
    }, {
        value : falses / total * 100,
        color : 'rgb(193, 71, 71)'
    }, {
        value : unknowns / total * 100,
        color : '#ddd'
    }];
    new Chart(ctx).Pie(data, {
        animationEasing: 'easeOutQuart',
        animationSteps: 15
    });
    var html = '
' + indicator_name(indicator) + '
';
    html += NMIS.indicators[indicator].description;
    html += '
' + trues + ' Yes / ' + falses + ' No';
    if (unknowns)
        html += ' / ' + unknowns + ' Unknown';
    html += '
';
    $('.map_view_legend .info').html(html);
};

var TableView = {};
TableView.render = function(lga, sector){
    render_nav(lga, 'table', sector);
    render('#table_view_template', {
        lga: lga,
        sector: sector,
        tables: NMIS.table_view[sector]
    });

    var that = this;
    $('.facilities_table_selector').change(function(){
        var index = parseInt(this.value, 10);
        that.show_table(sector, index, lga.facilities);
    });
    this.show_table(sector, 0, lga.facilities);
};

TableView.show_table = function(sector, table_index, facilities){
    var aoColumns = [];
    var table = NMIS.table_view[sector][table_index];

    _.each(table.indicators, function(indicator){
        aoColumns.push({
            sTitle: indicator_name(indicator)
        });
    });

    var aaData = [];
    _.each(facilities, function(facility){
        if (facility.sector === sector || sector === 'overview'){
            var facility_data = [];
            _.each(table.indicators, function(indicator){
                var value = facility[indicator];
                if (!value && facility.sector === 'water')
                    value = 'Water Point';
                value = format_value(value);
                facility_data.push(value);
            });
            aaData.push(facility_data);
        }
    });

    $('#facilities_data_table')
        .find('thead')
        .html('') // http://stackoverflow.com/questions/16290987/how-to-clear-all-column-headers-using-datatables
        .end()
        .dataTable({
            aaData: aaData,
            aoColumns: aoColumns,
            bPaginate: false,
            bDestroy: true,
            bFilter: false
        })
        .width('100%');
};

})();

<commit_msg>Remove unused variable<commit_after>(function(){

$(function(){
    new Backbone.Router({
        routes: {
            '': index,
            ':unique_lga/lga_overview': view(LGAView, 'overview'),
            ':unique_lga/lga_health': view(LGAView, 'health'),
            ':unique_lga/lga_education': view(LGAView, 'education'),
            ':unique_lga/lga_water': view(LGAView, 'water'),
            ':unique_lga/map_overview': view(MapView, 'overview'),
            ':unique_lga/map_health': view(MapView, 'health'),
            ':unique_lga/map_education': view(MapView, 'education'),
            ':unique_lga/map_water': view(MapView, 'water'),
            ':unique_lga/table_overview': view(TableView, 'overview'),
            ':unique_lga/table_health': view(TableView, 'health'),
            ':unique_lga/table_education': view(TableView, 'education'),
            ':unique_lga/table_water': view(TableView, 'water')
        }
    });
    Backbone.history.start();
});

// Helper Functions
// =================
function view(viewObj, sector){
    // Wrapper for LGA based views. Fetches the appropriate
    // LGA JSON data before calling the render() function of a view.

    if (viewObj.init) viewObj.init();

    function render(lga, sector){
        $('.facility_map').hide();
        $(window).scrollTop(0);
        viewObj.render(lga, sector);
    }

    return function(unique_lga){
        var lga = NMIS.lgas[unique_lga];
        if (lga){
            render(lga, sector);
        } else {
            var url = '/static/data/lgas/' + unique_lga + '.json';
            $.getJSON(url, function(lga){
                NMIS.lgas[unique_lga] = lga;
                render(lga, sector);
            });
        }
    }
}

function render_nav(lga, active_view, sector){
    // Renders the LGA navigation bar
    var template = $('#lga_nav_template').html();
    var html = _.template(template, {
        lga: lga,
        active_view: active_view,
        sector: sector
    });
    $('.lga_nav').html(html).show();
}

function render(template_id, context){
    // Renders an underscore template to the dom
    var template = $(template_id).html();
    context.NMIS = NMIS;
    context.format_value = format_value;
    context.indicator_name = indicator_name;
    var html = _.template(template, context);
    $('#content .content').html(html);
}

function format_value(value){
    // Formats indicator values for use in tables
    if (typeof value === 'undefined' ||
        value === null) return '-';
    if (value === true) return 'Yes';
    if (value === false) return 'No';
    if (_.isNumber(value) && value % 1 !== 0)
        return value.toFixed(2);
    if (_.isString(value))
        return value[0].toUpperCase() + value.substr(1);
    return value;
}

function indicator_name(slug){
    var indicator = NMIS.indicators[slug];
    return indicator ? indicator.name : slug;
}

// Views
// ============
function index(){
    $('.lga_nav').hide();
    render('#index_template', {zones: NMIS.zones});
    $('#zone-navigation .state-link').click(function(){
        $(this).next('.lga-list').toggle();
        return false;
    });
};

var LGAView = {};
LGAView.render = function(lga, sector){
    render_nav(lga, 'lga', sector);

    if (sector === 'overview'){
        render('#lga_overview_template', {
            lga: lga,
            lga_overview: NMIS.lga_overview
        });
        this.overview_map(lga);
    } else {
        render('#lga_view_template', {
            lga: lga,
            lga_view: NMIS.lga_view,
            sector: sector
        });
    }
};
LGAView.overview_map = function(lga){
    var map_div = $('.map')[0];
    var lat_lng = new L.LatLng(lga.latitude, lga.longitude);
    var map_zoom = 9;
    var summary_map = L.map(map_div, {scrollWheelZoom: false})
            .setView(lat_lng, map_zoom);
    var tile_server = 'http://{s}.tiles.mapbox.com/v3/' +
        'modilabs.nigeria_base/{z}/{x}/{y}.png';
    L.tileLayer(tile_server, {
        minZoom: 6,
        maxZoom: 11
    }).addTo(summary_map);
};

var MapView = {};
MapView.init = function(){
    $('.map_view_legend').on('click', '.close', function(){
        $(this).parent().hide();
        return false;
    });
};

MapView.render = function(lga, sector){
    var self = this;
    render_nav(lga, 'map', sector);
    render('#map_view_template', {
        lga: lga,
        sector: sector,
        chart_indicators: this.chart_indicators(lga.facilities, sector)
    });

    $('.map_view_legend').hide();

    this.facility_map(lga, sector);

    $('.pie_chart_selector').change(function(){
        if (this.value){
            $('.map_view_legend').show();
            self.map_legend(lga, sector, this.value);
        } else {
            $('.map_view_legend').hide();
        }
        self.facility_map(lga, sector, this.value);
    });
};

MapView.facility_map = function(lga, sector, indicator) {
    var lat_lng = new L.LatLng(lga.latitude, lga.longitude);
    var map_div = $('.facility_map').show()[0];
    var map = map_div._facility_map;

    if (!map){
        // Initialize Leaflet
        map = new L.Map(map_div, {scrollWheelZoom: false})
            .setView(lat_lng, 10);
        var lga_layer = new L.TileLayer(
            'http://{s}.tiles.mapbox.com/v3/modilabs.nigeria_overlays_white/{z}/{x}/{y}.png', {
                minZoom: 6,
                maxZoom: 10
            });
        var google_layer = new L.TileLayer(
            'http://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
                maxZoom: 18,
                minZoom: 3
            });
        google_layer.addTo(map);
        lga_layer.addTo(map);
        map_div._facility_map = map;
        map._unique_lga = lga.unique_lga;
    }

    if (map._facility_layer)
        map.removeLayer(map._facility_layer);

    if (map._unique_lga !== lga.unique_lga){
        map._unique_lga = lga.unique_lga;
        map.setView(lat_lng, 10);
    }
    map._facility_layer = this.facility_layer(lga.facilities, sector, indicator);
    map._facility_layer.addTo(map);
};

MapView.facility_layer = function(facilities, sector, indicator) {
    var that = this;
    var marker_group = new L.LayerGroup();
    _.each(facilities, function(fac){
        if (fac.sector === sector || sector === 'overview') {
            var lat_lng = fac.gps.split(' ').slice(0,2);
            var icon_url;
            if (indicator) {
                if (fac[indicator] === true ||
                    fac[indicator] === false) {
                    icon_url = 'static/images/icons_f/' +
                        fac[indicator] +'.png';
                } else {
                    icon_url = 'static/images/icons_f/' +
                        'undefined.png';
                }
            } else {
                icon_url = 'static/images/icons_f/normal_' +
                    fac.sector + '.png';
            }
            var icon = new L.Icon({iconUrl: icon_url});
            var mark = new L.Marker(lat_lng, {icon: icon});
            var popup = new L.Popup({closeButton: false})
                .setContent(fac.facility_name)
                .setLatLng(lat_lng);
            mark.on('click', function(){
                that.facility_modal(fac);
            });
            mark.on('mouseover', mark.openPopup.bind(mark))
                .on('mouseout', mark.closePopup.bind(mark))
                .bindPopup(popup);
            marker_group.addLayer(mark);
        }
    });
    return marker_group;
};

MapView.chart_indicators = function(facilities, sector){
    // Iterates through facilities within a sector to find
    // indicators which contain boolean values.
    // Returns a list of [indicator, indicator_name]
    var indicators = {};
    for (var i=0, facility; facility=facilities[i]; i++){
        if (facility.sector === sector){
            for (var indicator in facility){
                if (facility.hasOwnProperty(indicator)){
                    var value = facility[indicator];
                    if (value === false || value === true)
                        indicators[indicator] = 1;
                }
            }
        }
    }
    var chart_indicators = [];
    _.each(_.keys(indicators), function(indicator){
        chart_indicators.push([
            indicator, indicator_name(indicator)
        ]);
    });
    chart_indicators.sort(function(a,b){
        if (a[1] > b[1]) return 1;
        else if (a[1] < b[1]) return -1;
        return 0;
    });
    return chart_indicators;
};

MapView.facility_modal = function(facility){
    var that = this;
    var template = $('#facility_modal_template').html();
    var html = _.template(template, {
        NMIS: NMIS,
        facility: facility,
        tables: NMIS.table_view[facility.sector]
    });
    $('#facility_modal').remove();
    $('#content').append(html);
    $('#facility_modal').modal();
    $('.facility_table_selector').change(function(){
        var index = parseInt(this.value);
        that.facility_table(facility, index);
    });
    this.facility_table(facility, 0);
};

MapView.facility_table = function(facility, index){
    var aoColumns = [{sTitle: 'Indicator'}, {sTitle: 'Value'}];
    var table = NMIS.table_view[facility.sector][index];
    var aaData = [];

    _.each(table.indicators, function(indicator){
        aaData.push([
            indicator_name(indicator),
            format_value(facility[indicator])
        ]);
    });

    $('.facility_table')
        .dataTable({
            aaData: aaData,
            aoColumns: aoColumns,
            bFilter: false,
            bPaginate: false,
            bDestroy: true
        })
        .width('100%');
};

MapView.map_legend = function(lga, sector, indicator){
    var ctx = $('.map_view_legend canvas')[0].getContext('2d');
    var trues = 0;
    var falses = 0;
    var unknowns = 0;
    _.each(lga.facilities, function(facility){
        if (facility.sector === sector){
            var value = facility[indicator];
            if (value) trues++;
            else if (value === false) falses++;
            else unknowns++;
        }
    });
    var total = trues + falses + unknowns;
    var data = [{
        value: trues / total * 100,
        color: 'rgb(68, 167, 0)'
    }, {
        value : falses / total * 100,
        color : 'rgb(193, 71, 71)'
    }, {
        value : unknowns / total * 100,
        color : '#ddd'
    }];
    new Chart(ctx).Pie(data, {
        animationEasing: 'easeOutQuart',
        animationSteps: 15
    });
    var html = '
' + indicator_name(indicator) + '
';
    html += NMIS.indicators[indicator].description;
    html += '
' + trues + ' Yes / ' + falses + ' No';
    if (unknowns)
        html += ' / ' + unknowns + ' Unknown';
    html += '
';
    $('.map_view_legend .info').html(html);
};

var TableView = {};
TableView.render = function(lga, sector){
    render_nav(lga, 'table', sector);
    render('#table_view_template', {
        lga: lga,
        sector: sector,
        tables: NMIS.table_view[sector]
    });

    var that = this;
    $('.facilities_table_selector').change(function(){
        var index = parseInt(this.value, 10);
        that.show_table(sector, index, lga.facilities);
    });
    this.show_table(sector, 0, lga.facilities);
};

TableView.show_table = function(sector, table_index, facilities){
    var aoColumns = [];
    var table = NMIS.table_view[sector][table_index];

    _.each(table.indicators, function(indicator){
        aoColumns.push({
            sTitle: indicator_name(indicator)
        });
    });

    var aaData = [];
    _.each(facilities, function(facility){
        if (facility.sector === sector || sector === 'overview'){
            var facility_data = [];
            _.each(table.indicators, function(indicator){
                var value = facility[indicator];
                if (!value && facility.sector === 'water')
                    value = 'Water Point';
                value = format_value(value);
                facility_data.push(value);
            });
            aaData.push(facility_data);
        }
    });

    $('#facilities_data_table')
        .find('thead')
        .html('') // http://stackoverflow.com/questions/16290987/how-to-clear-all-column-headers-using-datatables
        .end()
        .dataTable({
            aaData: aaData,
            aoColumns: aoColumns,
            bPaginate: false,
            bDestroy: true,
            bFilter: false
        })
        .width('100%');
};

})();

<|endoftext|>


<commit_before>ngapp.controller('automateModalController', function($scope, $rootScope, $timeout, modalService, automationService, hotkeyService) {
    // helper functions
    let compare = function(a, b) {
        if (a < b) return -1;
        if (a > b) return 1;
        return 0;
    };

    let getNewScriptPath = function() {
        let filePath = `scripts\\New Script.js`,
            counter = 2;
        while (fh.jetpack.exists(filePath)) {
            filePath = `scripts\\New Script ${counter++}.js`;
        }
        return filePath;
    };

    let sortScripts = () => $scope.scripts.sort($scope.sortMode.compare);

    let createScriptIfNone = function() {
        if ($scope.scripts.length === 0) $scope.newScript();
    };

    // scope variables
    $scope.sortModes = [{
        label: 'Sort by Recent',
        compare: (a, b) => { return compare(a.lastRun, b.lastRun); }
    }, {
        label: 'Sort by Filename',
        compare: (a, b) => {
            return compare(a.filename.toUpperCase(), b.filename.toUpperCase());
        }
    }];

    // inherited functions
    hotkeyService.buildOnKeyDown($scope, 'onModalKeyDown', 'automateModal');

    // scope functions
    $scope.setSortMode = (sortMode) => $scope.sortMode = sortMode;

    $scope.saveScript = function() {
        let script = $scope.selectedScript,
            originalFilename = script.filePath.split('\\').last();
        if (originalFilename !== script.filename) {
            let newFilePath = `scripts\\${script.filename}`;
            if (fh.jetpack.exists(script.filePath)) {
                fh.jetpack.move(script.filePath, newFilePath);
            }
            script.filePath = newFilePath;
        }
        fh.saveTextFile(script.filePath, $scope.scriptContents);
    };

    $scope.deleteScript = function() {
        fh.jetpack.remove($scope.selectedScript.filePath);
        $scope.scripts.remove($scope.selectedScript);
        createScriptIfNone();
        $scope.selectScript($scope.scripts[0]);
    };

    $scope.closeModal = function() {
        $scope.saveScript();
        $scope.$emit('closeModal');
    };

    $scope.handleF2 = () => $scope.$broadcast('focusScriptFileName');

    $scope.runScript = function() {
        let scriptFilename = $scope.selectedScript.filename,
            scriptCode = $scope.scriptContents,
            targetScope = $scope.modalOptions.targetScope;
        $scope.closeModal();
        automationService.runScript(targetScope, scriptCode, scriptFilename);
    };

    $scope.selectScript = function(item) {
        $scope.selectedScript = item;
        $scope.scriptContents = fh.loadTextFile(item.filePath);
    };

    $scope.loadScripts = function() {
        fh.jetpack.dir('scripts');
        let scripts = fh.jetpack.find('scripts', { matching: '*.js'}),
            scriptHistory = fh.loadJsonFile('scripts\\history.json') || {};
        $scope.scripts = scripts.map(function(filePath) {
            let filename = filePath.split('\\').last();
            return {
                filePath: filePath,
                filename: filename,
                lastRun: scriptHistory[filename] || new Date(0)
            }
        });
    };

    $scope.newScript = function() {
        let filePath = getNewScriptPath();
        $scope.scripts.unshift({
            filePath: filePath,
            filename: filePath.split('\\').last(),
            lastRun: new Date()
        });
        $scope.selectScript($scope.scripts[0]);
    };

    // event handlers
    $scope.$watch('sortMode', sortScripts);

    // initialization
    $scope.loadScripts();
    createScriptIfNone();
    $scope.setSortMode($scope.sortModes[0]);
    $scope.selectScript($scope.scripts[0]);
});
<commit_msg>script history now gets saved and loaded properly and sorting by recent is ordered properly<commit_after>ngapp.controller('automateModalController', function($scope, $rootScope, $timeout, modalService, automationService, hotkeyService) {
    // helper functions
    let compare = function(a, b) {
        if (a < b) return -1;
        if (a > b) return 1;
        return 0;
    };

    let getNewScriptPath = function() {
        let filePath = `scripts\\New Script.js`,
            counter = 2;
        while (fh.jetpack.exists(filePath)) {
            filePath = `scripts\\New Script ${counter++}.js`;
        }
        return filePath;
    };

    let sortScripts = () => $scope.scripts.sort($scope.sortMode.compare);

    let createScriptIfNone = function() {
        if ($scope.scripts.length === 0) $scope.newScript();
    };

    let loadScripts = function() {
        fh.jetpack.dir('scripts');
        let scripts = fh.jetpack.find('scripts', { matching: '*.js'});
        $scope.scriptHistory = fh.loadJsonFile('scripts\\history.json') || {};
        $scope.scripts = scripts.map(function(filePath) {
            let filename = filePath.split('\\').last();
            return {
                filePath: filePath,
                filename: filename,
                lastRun: new Date($scope.scriptHistory[filename] || 0)
            }
        });
    };

    let saveHistory = function() {
        fh.saveJsonFile('scripts\\history.json', $scope.scriptHistory);
    };

    // scope variables
    $scope.sortModes = [{
        label: 'Sort by Recent',
        compare: (a, b) => { return b.lastRun - a.lastRun }
    }, {
        label: 'Sort by Filename',
        compare: (a, b) => {
            return compare(a.filename.toUpperCase(), b.filename.toUpperCase());
        }
    }];

    // inherited functions
    hotkeyService.buildOnKeyDown($scope, 'onModalKeyDown', 'automateModal');

    // scope functions
    $scope.setSortMode = function(sortMode) {
        $scope.sortMode = sortMode;
        sortScripts();
    };

    $scope.saveScript = function() {
        let script = $scope.selectedScript,
            originalFilename = script.filePath.split('\\').last();
        if (originalFilename !== script.filename) {
            let newFilePath = `scripts\\${script.filename}`;
            if (fh.jetpack.exists(script.filePath)) {
                fh.jetpack.move(script.filePath, newFilePath);
            }
            script.filePath = newFilePath;
        }
        fh.saveTextFile(script.filePath, $scope.scriptContents);
    };

    $scope.deleteScript = function() {
        fh.jetpack.remove($scope.selectedScript.filePath);
        $scope.scripts.remove($scope.selectedScript);
        createScriptIfNone();
        $scope.selectScript($scope.scripts[0]);
    };

    $scope.closeModal = function() {
        saveHistory();
        $scope.saveScript();
        $scope.$emit('closeModal');
    };

    $scope.handleF2 = () => $scope.$broadcast('focusScriptFileName');

    $scope.runScript = function() {
        let scriptFilename = $scope.selectedScript.filename,
            scriptCode = $scope.scriptContents,
            targetScope = $scope.modalOptions.targetScope;
        $scope.scriptHistory[scriptFilename] = new Date();
        $scope.closeModal();
        automationService.runScript(targetScope, scriptCode, scriptFilename);
    };

    $scope.selectScript = function(item) {
        $scope.selectedScript = item;
        $scope.scriptContents = fh.loadTextFile(item.filePath);
    };

    $scope.newScript = function() {
        let filePath = getNewScriptPath();
        $scope.scripts.shift({
            filePath: filePath,
            filename: filePath.split('\\').last(),
            lastRun: new Date()
        });
        $scope.selectScript($scope.scripts[0]);
    };

    // initialization
    loadScripts();
    createScriptIfNone();
    $scope.setSortMode($scope.sortModes[0]);
    $scope.selectScript($scope.scripts[0]);
});
<|endoftext|>


<commit_before>'use strict'

import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import EventListItem from '../../components/event-list-item'
// import Pagination from '../../components/pagination/index'

const Page = ({ events }) => (

Próximos Eventos

      {events.map((props, index) => (
        <EventListItem key={index} {...props} />
      ))}
      {/* <Pagination /> */}

)

Page.propTypes = {
  events: PropTypes.array.isRequired
}

const mapStateToProps = (state) => ({
  events: state.events.events.filter((_, index) => index >= 5)
})

export default connect(mapStateToProps)(Page)
<commit_msg>Update page to show just filtered events<commit_after>'use strict'

import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import EventListItem from '../../components/event-list-item'
// import Pagination from '../../components/pagination/index'

const Page = ({ events }) => (

Próximos Eventos

      {events.map((props, index) => (
        <EventListItem key={index} {...props} />
      ))}
      {/* <Pagination /> */}

)

Page.propTypes = {
  events: PropTypes.array.isRequired
}

const mapStateToProps = (state) => {
  const { filter } = state
  const monthsFilter = filter.months
  const stateFilter = filter.state
  return {
    events: state.events.events
      .filter((event) => {
        if (monthsFilter.selected && stateFilter.selected) {
          console.log('selecionou os dois!')
          return event.shouldShowByMonth !== false &&
            event.shouldShowByState !== false
        }

        if (monthsFilter.selected && !stateFilter.selected) {
          console.log('selecinou só mês!')
          return event.shouldShowByMonth !== false
        }

        if (!monthsFilter.selected && stateFilter.selected) {
          console.log('selecionou só estado!')
          return event.shouldShowByState !== false
        }

        console.log('sem seleção!')
        return event
      })
  }
}

export default connect(mapStateToProps)(Page)
<|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.controllers').controller('rateAppController', function($scope, $state, $stateParams, lodash, externalLinkService, configService, gettextCatalog, platformInfo, feedbackService, ongoingProcess, popupService) {
  $scope.score = parseInt($stateParams.score);
  var isAndroid = platformInfo.isAndroid;
  var isIOS = platformInfo.isIOS;
  var isWP = platformInfo.isWP;
  var config = configService.getSync();

  $scope.skip = function() {

    var dataSrc = {
      "Email": lodash.values(config.emailFor)[0] || ' ',
      "Feedback": ' ',
      "Score": $stateParams.score
    };

    ongoingProcess.set('sendingFeedback', true);
    feedbackService.send(dataSrc, function(err) {
      ongoingProcess.set('sendingFeedback', false);
      if (err) {
        popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Could not send feedback'));
        return;
      }
      $state.go('tabs.rate.complete', {
        score: $stateParams.score,
        skipped: true
      });
    });
  };

  $scope.sendFeedback = function() {
    $state.go('tabs.rate.send', {
      score: $scope.score
    });
  };

  $scope.goAppStore = function() {
    var defaults = configService.getDefaults();
    var url;
    if (isAndroid) url = defaults.rateApp.android;
    if (isIOS) url = defaults.rateApp.ios;
    // if (isWP) url = defaults.rateApp.windows; // TODO
    externalLinkService.open(url);
  };
});
<commit_msg>add new parameters<commit_after>'use strict';

angular.module('copayApp.controllers').controller('rateAppController', function($scope, $state, $stateParams, $window, lodash, externalLinkService, configService, gettextCatalog, platformInfo, feedbackService, ongoingProcess, popupService) {
  $scope.score = parseInt($stateParams.score);
  var isAndroid = platformInfo.isAndroid;
  var isIOS = platformInfo.isIOS;
  var isWP = platformInfo.isWP;
  var config = configService.getSync();

  $scope.skip = function() {

    var dataSrc = {
      "Email": lodash.values(config.emailFor)[0] || ' ',
      "Feedback": ' ',
      "Score": $stateParams.score,
      "AppVersion": $window.version,
      "Platform": ionic.Platform.platform(),
      "DeviceVersion": ionic.Platform.version()
    };

    ongoingProcess.set('sendingFeedback', true);
    feedbackService.send(dataSrc, function(err) {
      ongoingProcess.set('sendingFeedback', false);
      if (err) {
        popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Could not send feedback'));
        return;
      }
      $state.go('tabs.rate.complete', {
        score: $stateParams.score,
        skipped: true
      });
    });
  };

  $scope.sendFeedback = function() {
    $state.go('tabs.rate.send', {
      score: $scope.score
    });
  };

  $scope.goAppStore = function() {
    var defaults = configService.getDefaults();
    var url;
    if (isAndroid) url = defaults.rateApp.android;
    if (isIOS) url = defaults.rateApp.ios;
    // if (isWP) url = defaults.rateApp.windows; // TODO
    externalLinkService.open(url);
  };
});
<|endoftext|>


<commit_before>//import {BarChart} from 'react-d3-components';
import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
//import { BarChart } from 'react-d3-basic';
import ReactHighcharts from 'react-highcharts'
import Dropdown from 'react-toolbox/lib/dropdown'
import {Button, IconButton} from 'react-toolbox/lib/button'

class Analytics extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      camp: null,
      demographic: 'age',
      people: null,
      showChart: false
    }
  }

  campChange(value){
    this.setState({
      camp: value
    });
    console.log('camp change', this.state)
  }

  demographicChange(value){
    this.setState({
      demographic: value
    });
    console.log('demo change', this.state)
  }

  getData() {
    console.log('this state', this.state)
    axios.get(`/analytics/${this.state.camp}/${this.state.demographic}`)
      .then(function(response) {
        console.log('response all', response)
        console.log('response getdata', response.data);
        var people = response.data
        let demographic = this.state.demographic
        var dataObj = {}
        console.log('people -----------', people)
        people.forEach(person => {
          if(!dataObj.hasOwnProperty(person[demographic])) {
            dataObj[person[demographic]] = 1;
          } else {
            dataObj[person[demographic]] += 1;
          }
        }) //dataObj now has the count for each property - for example the number of politically centrist responders to a commonground
        console.log('dataObj -----------', dataObj)
        console.log('dataobj keys keys', Object.keys(dataObj))
        var dataArr = []
        for(var demo in dataObj) {
          let tuple = []
          tuple[0] = parseInt(demo)
          tuple[1] = dataObj[demo]
          dataArr.push(tuple)
        }
        console.log('data arr ~~~~~~~~~~~~~~~', dataArr)
        this.setState({
          people: dataArr,
          showChart: true
        })
        console.log('this this', this)
      }.bind(this))
  }

  render() {
    var commongrounds = this.props.campList.map(camp => {
      return {value: camp.input, label: camp.input}
    })
    var demographics = [
      {value:'age', label: 'age'},
      {value: 'hometown', label:'hometown'},
      {value: 'gender', label:'gender'},
      {value: 'race', label:'race'},
      {value: 'industry', label:'industry'},
      {value: 'politicalleaning', label:'politicalleaning'},
      {value: 'religion', label:'religion'},
      {value: 'yearlyincome', label:'yearlyincome'}
    ];
    var chartData = this.state.people;
    console.log('this props analytics', this.props)
    var politicalleaning = ['','Conservative', 'Authoritarian', 'Centrist', 'Libertarian', 'Progressive']
    var gender = ['', 'Male', 'Female', 'Other']
    var race = ['', 'White Hispanic', 'White Non-Hispanic', 'Black or African American', 'American Indian or Alaska Native',
    'Asian', 'Native Hawaiian or Other Pacific Islander', 'Other']
    var industry = ['',
      'Aerospace, defence & security',
      'Asset & wealth management',
      'Automotive',
      'Banking & capital markets',
      'Capital projects & infrastructure',
      'Chemicals',
      'Communications',
      'Energy, utilities & mining',
      'Engineering & construction',
      'Entertainment & media',
      'Financial services',
      'Forest, paper & packaging',
      'Government & public services',
      'Healthcare',
      'Hospitality & leisure',
      'Industrial manufacturing',
      'Insurance',
      'Metals',
      'Pharmaceuticals & life sciences',
      'Private equity',
      'Retail & consumer',
      'Sovereign investment funds',
      'Technology',
      'Transportation & logistics',
      'Other'
    ]
    var religion = ['', 'Protestant', 'Catholic', 'Mormon', 'Other Christian', 'Judaism', 'Islam',
    'Buddhism', 'Hinduism', 'Agnostic', 'Atheist', 'Other']
    var income = ['', 'Under $35,000 / year', '$35,000 - $50,000', '$50,000 - $65,000', '$65,000 - $80,000',
    '$80,000 - $95,000', '$95,000 - $120,000', 'Over $120,000']
    var categories = [];
    if(this.state.demographic === 'politicalleaning') {
      categories = politicalleaning;
    } else if(this.state.demographic === 'gender') {
      categories = gender
    } else if(this.state.demographic === 'race') {
      categories = race
    } else if(this.state.demographic === 'industry') {
      categories = industry
    } else if(this.state.demographic === 'religion') {
      categories = religion
    } else if(this.state.demographic === 'yearlyincome') {
      categories = income
    }
    console.log('categories =============', categories, this.state)
    let camp = this.state.camp
    console.log('camp', camp)
    var config = {
      chart: {
        type: 'column'
      },
      title: {
        text: `Statistics for ${camp}`
      },
      plotOptions: {
        column: {
          pointPadding: 0,
          borderWidth: 0,
          groupPadding: 0,
          shadow: false
        }
      },
      xAxis: {
        categories: categories
      },
      series: [{
        data: this.state.people
      }]
    }
    return (

      <Dropdown label='Select a CommonGround' ref="campSelect" onChange={(value)=> this.campChange(value)} source={commongrounds} value={this.state.camp} />
      <Dropdown label='Select a Demographic Property' ref="demographicSelect" onChange={(value)=> this.demographicChange(value)} source={demographics} value={this.state.demographic} />
      <Button onClick={() => this.getData()} label='Get Data' raised primary />
      {this.state.showChart && <ReactHighcharts config={config} />}

    )
  }
}

const mapStateToProps = (state) => {
  return {
    campList: state.campGet.commongrounds
  }
}

export default connect(mapStateToProps)(Analytics)

    // var barchartData = [{
    //   label: 'somethingA',
    //   values: [{x: 'SomethingA', y: 10}, {x: 'SomethingB', y: 4}, {x: 'SomethingC', y: 3}]
    // }];
    // if(this.state.ages !== null) {
    //   barchartData = [{
    //     label: 'Discussion users by Age-Group',
    //     values: [{x: '0-10', y: this.state.ages.kids}, {x: '11 - 20', y: this.state.ages.teens}, {x: '21 - 30', y: this.state.ages.twenties}, {x: '31 - 40', y: this.state.ages.thirties}, {x: '41 - 50', y: this.state.ages.forties}, {x: '51 - 60', y: this.state.ages.fifties}, {x: '61 - 70', y: this.state.ages.sixties}, {x: '71 - 80', y: this.state.ages.seventies}]
    //   }]
      // }
      // //var BarChart = ReactD3.BarChart
      // <BarChart data={barchartData} width={800} height={400}
      //   margin={{top: 10, bottom: 50, left: 50, right: 10}} />
        // <button onClick={()=>this.getAges()}>Get ages of commenters</button>
    // var width = 700,
    // height = 300,
    // margins = {left: 100, right: 100, top: 50, bottom: 50},
    // title = "User sample",
    // chartSeries = [
    //   {
    //     field: 'politicalleaning',
    //     name: 'Political Leaning',
    //     color: '#ff7f0e'
    //   }
    // ],
    // // your x accessor
    // counter = 0,
    // x = function(d) {
    //   var index = Object.keys(d)

    //   return index
    // },
    // xScale = 'identity',
      // {this.state.people && <BarChart
      //   title={title}
      //   data={chartData}
      //   width={width}
      //   height={height}
      //   chartSeries={chartSeries}
      //   x={x}
      //   xScale={xScale}
      // />}

        //       {this.props.campList.map((camp, index) => {
        //   return <option>{camp.input}</option>
        // })}
      // </select>

      //         {demographics.map(demographicOption => {
      //     return <option>{demographicOption}</option>
      //   })}
      // </select><commit_msg>graphs show separate series for commenters, upvoters, and downvoters<commit_after>//import {BarChart} from 'react-d3-components';
import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
//import { BarChart } from 'react-d3-basic';
import ReactHighcharts from 'react-highcharts'
import Dropdown from 'react-toolbox/lib/dropdown'
import {Button, IconButton} from 'react-toolbox/lib/button'

class Analytics extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      camp: null,
      demographic: 'age',
      commenters: null,
      upvoters: null,
      downvoters: null,
      showChart: false
    }
  }

  campChange(value){
    this.setState({
      camp: value
    });
    console.log('camp change', this.state)
  }

  demographicChange(value){
    this.setState({
      demographic: value
    });
    console.log('demo change', this.state)
  }

  getData() {
    console.log('this state', this.state)
    axios.get(`/analytics/${this.state.camp}/${this.state.demographic}`)
      .then(function(response) {
        console.log('response all', response)
        console.log('response getdata', response.data);
        var people = response.data
        let demographic = this.state.demographic
        var commentDataObj = {}
        var upvoteDataObj = {}
        var downvoteDataObj = {}
        console.log('people -----------', people)
        people.forEach(person => {
          if(person.input){
            console.log('person input', person.input)

          }
          if(!commentDataObj.hasOwnProperty(person[demographic]) && !person.hasOwnProperty('input')) {
            commentDataObj[person[demographic]] = 1;
          } else if(commentDataObj.hasOwnProperty(person[demographic]) && !person.hasOwnProperty('input')) {
            commentDataObj[person[demographic]] += 1;
          } else if(!downvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 0) {
            downvoteDataObj[person[demographic]] = 1;
          } else if(downvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 0) {
            downvoteDataObj[person[demographic]] += 1;
          } else if(!upvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 1) {
            upvoteDataObj[person[demographic]] = 1;
          } else if(upvoteDataObj.hasOwnProperty(person[demographic]) && person.input === 1) {
            upvoteDataObj[person[demographic]] += 1;
          }
        }) //dataObj now has the count for each property - for example the number of politically centrist responders to a commonground
        console.log('dataObj -----------', commentDataObj)
        console.log('commentdataobj keys keys', Object.keys(commentDataObj))
        console.log('upvotedataObj -----------', upvoteDataObj)
        console.log('upvoteDataobj keys keys', Object.keys(upvoteDataObj))
        console.log('downvotedataObj -----------', downvoteDataObj)
        console.log('downvoteDataobj keys keys', Object.keys(downvoteDataObj))
        var commentDataArr = []
        for(let demo in commentDataObj) {
          let tuple = []
          tuple[0] = parseInt(demo)
          tuple[1] = commentDataObj[demo]
          commentDataArr.push(tuple)
        }
        var upvoteDataArr = []
        for(let demo in upvoteDataObj) {
          let tuple = []
          tuple[0] = parseInt(demo)
          tuple[1] = upvoteDataObj[demo]
          upvoteDataArr.push(tuple)
        }
        var downvoteDataArr = []
        for(let demo in downvoteDataObj) {
          let tuple = []
          tuple[0] = parseInt(demo)
          tuple[1] = downvoteDataObj[demo]
          downvoteDataArr.push(tuple)
        }
        console.log('comment arr ~~~~~~~~~~~~~~~', commentDataArr)
        console.log('updata arr ~~~~~~~~~~~~~~~', upvoteDataArr)
        console.log('downdata arr ~~~~~~~~~~~~~~~', downvoteDataArr)
        this.setState({
          commenters: commentDataArr,
          upvoters: upvoteDataArr,
          downvoters: downvoteDataArr,
          showChart: true
        })
        console.log('this this', this)
      }.bind(this))
  }

  render() {
    var commongrounds = this.props.campList.map(camp => {
      return {value: camp.input, label: camp.input}
    })
    var demographics = [
      {value:'age', label: 'age'},
      {value: 'hometown', label:'hometown'},
      {value: 'gender', label:'gender'},
      {value: 'race', label:'race'},
      {value: 'industry', label:'industry'},
      {value: 'politicalleaning', label:'politicalleaning'},
      {value: 'religion', label:'religion'},
      {value: 'yearlyincome', label:'yearlyincome'}
    ];
    //var chartData = this.state.people;
    console.log('this props analytics', this.props)
    var politicalleaning = ['','Conservative', 'Authoritarian', 'Centrist', 'Libertarian', 'Progressive']
    var gender = ['', 'Male', 'Female', 'Other']
    var race = ['', 'White Hispanic', 'White Non-Hispanic', 'Black or African American', 'American Indian or Alaska Native',
    'Asian', 'Native Hawaiian or Other Pacific Islander', 'Other']
    var industry = ['',
      'Aerospace, defence & security',
      'Asset & wealth management',
      'Automotive',
      'Banking & capital markets',
      'Capital projects & infrastructure',
      'Chemicals',
      'Communications',
      'Energy, utilities & mining',
      'Engineering & construction',
      'Entertainment & media',
      'Financial services',
      'Forest, paper & packaging',
      'Government & public services',
      'Healthcare',
      'Hospitality & leisure',
      'Industrial manufacturing',
      'Insurance',
      'Metals',
      'Pharmaceuticals & life sciences',
      'Private equity',
      'Retail & consumer',
      'Sovereign investment funds',
      'Technology',
      'Transportation & logistics',
      'Other'
    ]
    var religion = ['', 'Protestant', 'Catholic', 'Mormon', 'Other Christian', 'Judaism', 'Islam',
    'Buddhism', 'Hinduism', 'Agnostic', 'Atheist', 'Other']
    var income = ['', 'Under $35,000 / year', '$35,000 - $50,000', '$50,000 - $65,000', '$65,000 - $80,000',
    '$80,000 - $95,000', '$95,000 - $120,000', 'Over $120,000']
    var categories = [];
    if(this.state.demographic === 'politicalleaning') {
      categories = politicalleaning;
    } else if(this.state.demographic === 'gender') {
      categories = gender
    } else if(this.state.demographic === 'race') {
      categories = race
    } else if(this.state.demographic === 'industry') {
      categories = industry
    } else if(this.state.demographic === 'religion') {
      categories = religion
    } else if(this.state.demographic === 'yearlyincome') {
      categories = income
    }
    console.log('categories =============', categories, this.state)
    let camp = this.state.camp
    console.log('camp', camp)
    var config = {
      chart: {
        type: 'column'
      },
      title: {
        text: `Statistics for ${camp}`
      },
      plotOptions: {
        column: {
          pointPadding: 0,
          borderWidth: 0,
          groupPadding: 0,
          shadow: false
        }
      },
      xAxis: {
        categories: categories
      },
      series: [{
        name: 'Commenters',
        data: this.state.commenters
      },
      {
        name: 'Upvoters',
        data: this.state.upvoters
      },
      {
        name: 'Downvoters',
        data: this.state.downvoters
      }]
    }
    return (

      <Dropdown label='Select a CommonGround' ref="campSelect" onChange={(value)=> this.campChange(value)} source={commongrounds} value={this.state.camp} />
      <Dropdown label='Select a Demographic Property' ref="demographicSelect" onChange={(value)=> this.demographicChange(value)} source={demographics} value={this.state.demographic} />
      <Button onClick={() => this.getData()} label='Get Data' raised primary />
      {this.state.showChart && <ReactHighcharts config={config} />}

    )
  }
}

const mapStateToProps = (state) => {
  return {
    campList: state.campGet.commongrounds
  }
}

export default connect(mapStateToProps)(Analytics)

    // var barchartData = [{
    //   label: 'somethingA',
    //   values: [{x: 'SomethingA', y: 10}, {x: 'SomethingB', y: 4}, {x: 'SomethingC', y: 3}]
    // }];
    // if(this.state.ages !== null) {
    //   barchartData = [{
    //     label: 'Discussion users by Age-Group',
    //     values: [{x: '0-10', y: this.state.ages.kids}, {x: '11 - 20', y: this.state.ages.teens}, {x: '21 - 30', y: this.state.ages.twenties}, {x: '31 - 40', y: this.state.ages.thirties}, {x: '41 - 50', y: this.state.ages.forties}, {x: '51 - 60', y: this.state.ages.fifties}, {x: '61 - 70', y: this.state.ages.sixties}, {x: '71 - 80', y: this.state.ages.seventies}]
    //   }]
      // }
      // //var BarChart = ReactD3.BarChart
      // <BarChart data={barchartData} width={800} height={400}
      //   margin={{top: 10, bottom: 50, left: 50, right: 10}} />
        // <button onClick={()=>this.getAges()}>Get ages of commenters</button>
    // var width = 700,
    // height = 300,
    // margins = {left: 100, right: 100, top: 50, bottom: 50},
    // title = "User sample",
    // chartSeries = [
    //   {
    //     field: 'politicalleaning',
    //     name: 'Political Leaning',
    //     color: '#ff7f0e'
    //   }
    // ],
    // // your x accessor
    // counter = 0,
    // x = function(d) {
    //   var index = Object.keys(d)

    //   return index
    // },
    // xScale = 'identity',
      // {this.state.people && <BarChart
      //   title={title}
      //   data={chartData}
      //   width={width}
      //   height={height}
      //   chartSeries={chartSeries}
      //   x={x}
      //   xScale={xScale}
      // />}

        //       {this.props.campList.map((camp, index) => {
        //   return <option>{camp.input}</option>
        // })}
      // </select>

      //         {demographics.map(demographicOption => {
      //     return <option>{demographicOption}</option>
      //   })}
      // </select><|endoftext|>


<commit_before>var Card = (function() {
    function Card(card_el) {
        this.card = card_el;
        this.output = card_el.find('.cell_output');
        this.card_name = this.output.data('card-name');

        if (typeof this.card_name === "undefined") {
            return;
        }

        this.result = $("<div/>");
        this.output.append(this.result);
        this.variable = encodeURIComponent(this.output.data('variable'));
        this.expr = encodeURIComponent(this.output.data('expr'));
        this.parameters = this.output.data('parameters');
        this.parameterValues = {};

        if (this.parameters.indexOf('digits') !== -1) {
            var moreDigits =
                $('<button>More Digits</button>').addClass('card_options_toggle');
            this.parameter('digits', 15);
            this.output.parent().append(
                $("<div/>").addClass('card_options').append(moreDigits)
            );
            moreDigits.click($.proxy(function() {
                var delta = 10;
                if (this.parameter('digits') <= 15) {
                    delta = 35;
                }
                this.parameter('digits', this.parameter('digits') + delta);
                this.evaluate();
            }, this));
        }

        if (this.card_name === 'integral') {
            var seeSteps =
                $('<button>See Steps</button>').addClass('card_options_toggle');
            this.output.parent().append(
                $("<div/>").addClass('card_options').append(seeSteps)
            );

            seeSteps.click($.proxy(function() {
                window.location = window.location.origin + '/input/?i=' + 'integrate(' + this.expr + ')';
            }, this));
        }
    }

    Card.prototype.parameter = function(key, val) {
        if (val != null) {
            this.parameterValues[key] = val;
        }
        return this.parameterValues[key];
    };

    // TODO use Deferred to replace parameters
    Card.prototype.evaluate = function(finished, error) {
        if (finished == null) {
            finished = $.proxy(this.evaluateFinished, this);
        }
        if (error == null) {
            error = $.proxy(this.evaluateError, this);
        }
        if (typeof this.card_name !== "undefined") {
            var url = '/card/' + this.card_name;
            var parms = {
                variable: this.variable,
                expression: this.expr
            };
            $.extend(parms, this.parameterValues);
            var deferred = $.getJSON(url, parms, finished);
            deferred.error(error);
            return deferred;
        }
        var result = new $.Deferred();
        result.reject();
        return result;
    };

    Card.prototype.evaluateFinished = function(data) {
        if (typeof data.output !== "undefined") {
            this.result.html(data.output);

            MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
        }
        else {
            var error = $("<div/>")
                .addClass('cell_output_plain')
                .html(data.error);
            this.output.append(error);
            this.card.addClass('result_card_error');
        }
        this.output.children('.loader').fadeOut(500);
    };

    Card.prototype.evaluateError = function() {
        this.output.append($("<div/>").html("Error occurred"));
        this.output.children('.loader').fadeOut(500);
    };

    return Card;
})();
<commit_msg>Reduce code duplication<commit_after>var Card = (function() {
    function Card(card_el) {
        this.card = card_el;
        this.output = card_el.find('.cell_output');
        this.card_name = this.output.data('card-name');

        if (typeof this.card_name === "undefined") {
            return;
        }

        this.result = $("<div/>");
        this.output.append(this.result);
        this.variable = encodeURIComponent(this.output.data('variable'));
        this.expr = encodeURIComponent(this.output.data('expr'));
        this.parameters = this.output.data('parameters');
        this.parameterValues = {};

        if (this.parameters.indexOf('digits') !== -1) {
            this.addOptionsSection();
            var moreDigits = this.addOptionsButton('More Digits');

            this.parameter('digits', 15);
            moreDigits.click($.proxy(function() {
                var delta = 10;
                if (this.parameter('digits') <= 15) {
                    delta = 35;
                }
                this.parameter('digits', this.parameter('digits') + delta);
                this.evaluate();
            }, this));
        }

        if (this.card_name === 'integral') {
            this.addOptionsSection();
            var seeSteps = this.addOptionsButton('See Steps');

            seeSteps.click($.proxy(function() {
                window.location = window.location.origin + '/input/?i=' + 'integrate(' + this.expr + ')';
            }, this));
        }

        else if (this.card_name === 'diff') {
            this.addOptionsSection();
            var seeSteps = this.addOptionsButton('See Steps');

            seeSteps.click($.proxy(function() {
                window.location = window.location.origin + '/input/?i=' + 'diff(' + this.expr + ')';
            }, this));
        }
    }

    Card.prototype.parameter = function(key, val) {
        if (val != null) {
            this.parameterValues[key] = val;
        }
        return this.parameterValues[key];
    };

    // TODO use Deferred to replace parameters
    Card.prototype.evaluate = function(finished, error) {
        if (finished == null) {
            finished = $.proxy(this.evaluateFinished, this);
        }
        if (error == null) {
            error = $.proxy(this.evaluateError, this);
        }
        if (typeof this.card_name !== "undefined") {
            var url = '/card/' + this.card_name;
            var parms = {
                variable: this.variable,
                expression: this.expr
            };
            $.extend(parms, this.parameterValues);
            var deferred = $.getJSON(url, parms, finished);
            deferred.error(error);
            return deferred;
        }
        var result = new $.Deferred();
        result.reject();
        return result;
    };

    Card.prototype.evaluateFinished = function(data) {
        if (typeof data.output !== "undefined") {
            this.result.html(data.output);

            MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
        }
        else {
            var error = $("<div/>")
                .addClass('cell_output_plain')
                .html(data.error);
            this.output.append(error);
            this.card.addClass('result_card_error');
        }
        this.output.children('.loader').fadeOut(500);
    };

    Card.prototype.evaluateError = function() {
        this.output.append($("<div/>").html("Error occurred"));
        this.output.children('.loader').fadeOut(500);
    };

    Card.prototype.addOptionsSection = function() {
        this._optionsSection = $("<div/>").addClass('card_options');
        this.output.parent().append(this._optionsSection);
    }

    Card.prototype.addToOptionsSection = function(el) {
        this._optionsSection.append(el);
    }

    Card.prototype.addOptionsButton = function(text) {
        var button = $('<button/>').addClass('card_options_toggle').html(text);
        this.addToOptionsSection(button);
        return button;
    }

    return Card;
})();
<|endoftext|>


<commit_before>'use strict';

define(['./module', 'darkwallet', 'dwutil/currencyformat'], function (controllers, DarkWallet, CurrencyFormat) {
  controllers.controller('CashoutCtrl', ['$scope', '$http', '$timeout', '$location', '$window', 'modals', '_Filter', function($scope, $http, $timeout, $location, $window, modals, _) {
    var identity = DarkWallet.getIdentity();

    $scope.page = "screen1";
    $scope.send = {phone: "", amount: 10, country: "ES", server: identity.settings.cashout_url || ""};
    $scope.status = "";
    $scope.qrcode = "";
    $scope.lastpage = "";
    $scope.terms = '';

    var checkTimeout = null;
    var createTimeout = null;

    $scope.start = function() {
        $scope.page = "screen1";
    }

    $scope.showLegal = function() {
        $window.open($scope.legal, '_blank');
    }

    $scope.getConditions = function(server) {
        $http.get(server+"hello").
            success(function(data, status, headers, config) {
                $scope.btcPrice = data.price;
                $scope.timeout = data.timeout;
                $scope.legal = data.terms;
                $scope.fixedFee = data.fixed_fee;
                $scope.dailyLimit = data.daily_limit;
                $scope.monthlyLimit = data.monthly_limit;
                $scope.variableFee = data.variable_fee;
                $scope.send.connected = true;
                var parser = document.createElement('a');
                parser.href = server;
                $scope.serviceTitle = data.title || parser.hostname;
                identity.settings.cashout_url = server;
                identity.store.save();
            }).
            error(function(data, status, headers, config) {
            });
    }

    /*
     * Get some variables from local storage
     */
    var tickets = {};
    $scope.tickets = tickets;
    $scope.allTickets = [];
    if (identity.settings.cashoutTickets) {
        identity.settings.cashoutTickets.forEach(function(ticket) {
            tickets[ticket.id] = ticket;
            $scope.allTickets.push(ticket.id);
        });
    }

    /*
     * Check an address
     */

    $scope.checkTicket = function() {
        checkTimeout = null;
        $scope.status = "checking";
        $http.get($scope.send.server+"check/"+$scope.txId+"/"+$scope.send.phone).
            success(function(data, status, headers, config) {
                var btcAmount = data.btc;
                var confirmations = data.confirmations;
                tickets[$scope.txId].status = "checked";
                tickets[$scope.txId].confirmations = confirmations;
                $scope.status = "checked";
                if (btcAmount && confirmations >= 0) {
                    tickets[$scope.txId].result = data;
                    tickets[$scope.txId].finished = true;
                    tickets[$scope.txId].status = data.status;
                    tickets[$scope.txId].ticketId = data.ticket;
                    $scope.status = "confirmed";
                } else if (data.expired) {
                    $scope.qrcode = "";
                    tickets[$scope.txId].status = 'expired';
                    $scope.cancel("Expired");
                }
                identity.store.save();
            }).
            error(function(data, status, headers, config) {
                checkTimeout = $timeout($scope.checkTicket, 5000);
            });
    }

    /*
     * Cancel a ticket
     */
    $scope.cancel = function(status) {
       $scope.page = "screen1";
       $scope.send.phone = "";
       if ($scope.txId) {
           tickets[$scope.txId].status = 'cancelled';
       }
       delete $scope.txId;
       delete $scope.currentTicket;
       $scope.status = status || "";
       if (checkTimeout) {
           $timeout.cancel(checkTimeout);
           checkTimeout = null;
       }
    };

    $scope.openTicket = function(ticket) {
        $scope.currentTicket = ticket;
        $scope.page = "screen2";
        $scope.qrcode = "bitcoin:"+ticket.address+"?amount="+ticket.btcamount/100000000+"&message=Cashout";
        $scope.send.amount = ticket.amount;
        $scope.send.phone = ticket.phone;
        $scope.send.country = ticket.country;
        $scope.pin = ticket.pin;
        $scope.txId = ticket.id;
        $scope.send.server = ticket.endpoint || identity.settings.cashout_url;
    };

    /*
     * Keep trying to create a ticket
     */
    var postRetry = function() {
        $http.post($scope.send.server+"send", { country: $scope.send.country,
                          phone_number: $scope.send.phone,
                          amount: $scope.send.amount }).
            success(function(data, status, headers, config) {
              // this callback will be called asynchronously
              // when the response is available
              $scope.status = (data.status === 'ok') ? "" : data.status;
              tickets[data.id] = {timestamp: Date.now(),
                                  type: 'hal',
                                  // server data:
                                  btcamount: data.amount,
                                  amount: $scope.send.amount,
                                  pin: data.pin,
                                  id: data.id,
                                  address: data.address,
                                  status: 'created',
                                  endpoint: $scope.send.server,
                                  confirmations: -1,
                                  // form data:
                                  phone: $scope.send.phone,
                                  country: $scope.send.country};

              // Go to the ticket subpage
              $scope.openTicket(tickets[data.id]);

              // Check once
              checkTimeout = $timeout($scope.checkTicket, 5000);

              // save ticket in cache
              $scope.allTickets.push(data.id);

              if (!identity.settings.cashoutTickets) {
                  identity.settings.cashoutTickets = [];
              }
              identity.settings.cashoutTickets.push(tickets[data.id]);
              identity.store.save();
            }).
            error(function(data, status, headers, config) {
              // called asynchronously if an error occurs
              // or server returns response with an error status.
              $scope.status = "Error querying server";
              createTimeout = $timeout(1000, function() {
                  createTimeout = null;
                  postRetry();
              });
            });
    };

    $scope.payTicket = function() {
        var identity = DarkWallet.getIdentity();
        $scope.forms.send = { mixing: true,
                        sending: false,
                        sendPocket: 0,
                        autoAddEnabled: false,
                        propagated: false,
                        identity: identity.name,
                        fee: CurrencyFormat.asBtc(identity.wallet.fee),
                        advanced: false };

        var amount = CurrencyFormat.asBtc($scope.currentTicket.btcamount);

        $scope.forms.send.recipients = {
            fields: [
                { address: $scope.currentTicket.address, amount: amount.toString() }
            ],
            field_proto: { address: '', amount: '' }
        };
        $location.path('/send');
    };

    /*
     * Go to the paying page
     */
    $scope.nextPage = function() {
        var number = $scope.send.phone;
        if (!number) {
            $scope.status = _("Missing phone");
        } else if (number < 99999999) {
            $scope.status = _("Bad phone");
        /*} else if (!isValid) {
            $scope.status = "Bad Phone Number";*/
        } else if (!$scope.send.amount) {
            $scope.status = _("Missing amount");
        } else if (isNaN(parseInt($scope.send.amount)) || parseInt($scope.send.amount) !== parseFloat($scope.send.amount) || parseInt($scope.send.amount)%10) {
            $scope.status = _("Incorrect amount");
        } else if (parseInt($scope.send.amount) > $scope.dailyLimit) {
            $scope.status = _("Amount too large, max is ") + $scope.dailyLimit + " EUR";
        } else {
            $scope.send.phone = number;
            $scope.status = _("sending");
            postRetry();
        }
    };

    $scope.$on('$destroy', function() {
        if (checkTimeout) {
            $timeout.cancel(checkTimeout);
        }
        if (createTimeout) {
            $timeout.cancel(createTimeout);
        }
    });

    $scope.toggleSettings = function() {
        if ($scope.page === 'settings') {
            $scope.page = $scope.lastPage;
        } else {
            $scope.lastPage = $scope.page;
            $scope.page = 'settings';
        }
    };

    $scope.toggleTickets = function() {
        if ($scope.page === 'tickets') {
            $scope.page = $scope.lastPage;
        } else {
            $scope.lastPage = $scope.page;
            $scope.page = 'tickets';
        }
    };

    $scope.clearServer = function() {
        //$scope.send.server = '';
        $scope.send.connected = false;

        //delete identity.settings.cashout_url;
        //identity.store.save();
    };

    $scope.connectService = function() {
        var serverUrl = $scope.send.server;
        if (serverUrl.indexOf("api/") !== -1) {
            $scope.page = "screen1";
            modals.open('confirm', {message: _('Are you sure?'), detail: _('This will connect to a remote service that can record your interaction with them.')}, function() {
                $scope.getConditions(serverUrl);
            });
        } else {
            $scope.send.connected = false;
        }
    };

    /*
    $scope.$watch('send.server', function(serverUrl) {
        $scope.connectService();
    });*/
}]);

});
<commit_msg>Properly mark tickets as expired.<commit_after>'use strict';

define(['./module', 'darkwallet', 'dwutil/currencyformat'], function (controllers, DarkWallet, CurrencyFormat) {
  controllers.controller('CashoutCtrl', ['$scope', '$http', '$timeout', '$location', '$window', 'modals', '_Filter', function($scope, $http, $timeout, $location, $window, modals, _) {
    var identity = DarkWallet.getIdentity();

    $scope.page = "screen1";
    $scope.send = {phone: "", amount: 10, country: "ES", server: identity.settings.cashout_url || ""};
    $scope.status = "";
    $scope.qrcode = "";
    $scope.lastpage = "";
    $scope.terms = '';

    var checkTimeout = null;
    var createTimeout = null;

    $scope.start = function() {
        $scope.page = "screen1";
    }

    $scope.showLegal = function() {
        $window.open($scope.legal, '_blank');
    }

    $scope.getConditions = function(server) {
        $http.get(server+"hello").
            success(function(data, status, headers, config) {
                $scope.btcPrice = data.price;
                $scope.timeout = data.timeout;
                $scope.legal = data.terms;
                $scope.fixedFee = data.fixed_fee;
                $scope.dailyLimit = data.daily_limit;
                $scope.monthlyLimit = data.monthly_limit;
                $scope.variableFee = data.variable_fee;
                $scope.send.connected = true;
                var parser = document.createElement('a');
                parser.href = server;
                $scope.serviceTitle = data.title || parser.hostname;
                identity.settings.cashout_url = server;
                identity.store.save();
            }).
            error(function(data, status, headers, config) {
            });
    }

    /*
     * Get some variables from local storage
     */
    var tickets = {};
    $scope.tickets = tickets;
    $scope.allTickets = [];
    if (identity.settings.cashoutTickets) {
        identity.settings.cashoutTickets.forEach(function(ticket) {
            tickets[ticket.id] = ticket;
            $scope.allTickets.push(ticket.id);
        });
    }

    /*
     * Check an address
     */

    $scope.checkTicket = function() {
        checkTimeout = null;
        $scope.status = "checking";
        $http.get($scope.send.server+"check/"+$scope.txId+"/"+$scope.send.phone).
            success(function(data, status, headers, config) {
                var btcAmount = data.btc;
                var confirmations = data.confirmations;
                tickets[$scope.txId].status = "checked";
                tickets[$scope.txId].confirmations = confirmations;
                $scope.status = "checked";
                if (btcAmount && confirmations >= 0) {
                    tickets[$scope.txId].result = data;
                    tickets[$scope.txId].finished = true;
                    tickets[$scope.txId].status = data.status;
                    tickets[$scope.txId].ticketId = data.ticket;
                    $scope.status = "confirmed";
                } else if (data.status === 'expired') {
                    $scope.qrcode = "";
                    tickets[$scope.txId].status = 'expired';
                }
                identity.store.save();
            }).
            error(function(data, status, headers, config) {
                checkTimeout = $timeout($scope.checkTicket, 5000);
            });
    }

    /*
     * Cancel a ticket
     */
    $scope.cancel = function(status) {
       $scope.page = "screen1";
       $scope.send.phone = "";
       if ($scope.txId) {
           tickets[$scope.txId].status = 'cancelled';
       }
       delete $scope.txId;
       delete $scope.currentTicket;
       $scope.status = status || "";
       if (checkTimeout) {
           $timeout.cancel(checkTimeout);
           checkTimeout = null;
       }
    };

    $scope.openTicket = function(ticket) {
        $scope.currentTicket = ticket;
        $scope.page = "screen2";
        $scope.qrcode = "bitcoin:"+ticket.address+"?amount="+ticket.btcamount/100000000+"&message=Cashout";
        $scope.send.amount = ticket.amount;
        $scope.send.phone = ticket.phone;
        $scope.send.country = ticket.country;
        $scope.pin = ticket.pin;
        $scope.txId = ticket.id;
        $scope.send.server = ticket.endpoint || identity.settings.cashout_url;
    };

    /*
     * Keep trying to create a ticket
     */
    var postRetry = function() {
        $http.post($scope.send.server+"send", { country: $scope.send.country,
                          phone_number: $scope.send.phone,
                          amount: $scope.send.amount }).
            success(function(data, status, headers, config) {
              // this callback will be called asynchronously
              // when the response is available
              $scope.status = (data.status === 'ok') ? "" : data.status;
              tickets[data.id] = {timestamp: Date.now(),
                                  type: 'hal',
                                  // server data:
                                  btcamount: data.amount,
                                  amount: $scope.send.amount,
                                  pin: data.pin,
                                  id: data.id,
                                  address: data.address,
                                  status: 'created',
                                  endpoint: $scope.send.server,
                                  confirmations: -1,
                                  // form data:
                                  phone: $scope.send.phone,
                                  country: $scope.send.country};

              // Go to the ticket subpage
              $scope.openTicket(tickets[data.id]);

              // Check once
              checkTimeout = $timeout($scope.checkTicket, 5000);

              // save ticket in cache
              $scope.allTickets.push(data.id);

              if (!identity.settings.cashoutTickets) {
                  identity.settings.cashoutTickets = [];
              }
              identity.settings.cashoutTickets.push(tickets[data.id]);
              identity.store.save();
            }).
            error(function(data, status, headers, config) {
              // called asynchronously if an error occurs
              // or server returns response with an error status.
              $scope.status = "Error querying server";
              createTimeout = $timeout(1000, function() {
                  createTimeout = null;
                  postRetry();
              });
            });
    };

    $scope.payTicket = function() {
        var identity = DarkWallet.getIdentity();
        $scope.forms.send = { mixing: true,
                        sending: false,
                        sendPocket: 0,
                        autoAddEnabled: false,
                        propagated: false,
                        identity: identity.name,
                        fee: CurrencyFormat.asBtc(identity.wallet.fee),
                        advanced: false };

        var amount = CurrencyFormat.asBtc($scope.currentTicket.btcamount);

        $scope.forms.send.recipients = {
            fields: [
                { address: $scope.currentTicket.address, amount: amount.toString() }
            ],
            field_proto: { address: '', amount: '' }
        };
        $location.path('/send');
    };

    /*
     * Go to the paying page
     */
    $scope.nextPage = function() {
        var number = $scope.send.phone;
        if (!number) {
            $scope.status = _("Missing phone");
        } else if (number < 99999999) {
            $scope.status = _("Bad phone");
        /*} else if (!isValid) {
            $scope.status = "Bad Phone Number";*/
        } else if (!$scope.send.amount) {
            $scope.status = _("Missing amount");
        } else if (isNaN(parseInt($scope.send.amount)) || parseInt($scope.send.amount) !== parseFloat($scope.send.amount) || parseInt($scope.send.amount)%10) {
            $scope.status = _("Incorrect amount");
        } else if (parseInt($scope.send.amount) > $scope.dailyLimit) {
            $scope.status = _("Amount too large, max is ") + $scope.dailyLimit + " EUR";
        } else {
            $scope.send.phone = number;
            $scope.status = _("sending");
            postRetry();
        }
    };

    $scope.$on('$destroy', function() {
        if (checkTimeout) {
            $timeout.cancel(checkTimeout);
        }
        if (createTimeout) {
            $timeout.cancel(createTimeout);
        }
    });

    $scope.toggleSettings = function() {
        if ($scope.page === 'settings') {
            $scope.page = $scope.lastPage;
        } else {
            $scope.lastPage = $scope.page;
            $scope.page = 'settings';
        }
    };

    $scope.toggleTickets = function() {
        if ($scope.page === 'tickets') {
            $scope.page = $scope.lastPage;
        } else {
            $scope.lastPage = $scope.page;
            $scope.page = 'tickets';
        }
    };

    $scope.clearServer = function() {
        //$scope.send.server = '';
        $scope.send.connected = false;

        //delete identity.settings.cashout_url;
        //identity.store.save();
    };

    $scope.connectService = function() {
        var serverUrl = $scope.send.server;
        if (serverUrl.indexOf("api/") !== -1) {
            $scope.page = "screen1";
            modals.open('confirm', {message: _('Are you sure?'), detail: _('This will connect to a remote service that can record your interaction with them.')}, function() {
                $scope.getConditions(serverUrl);
            });
        } else {
            $scope.send.connected = false;
        }
    };

    /*
    $scope.$watch('send.server', function(serverUrl) {
        $scope.connectService();
    });*/
}]);

});
<|endoftext|>


<commit_before>;(function( _, async, $, App ){

    /// Variables: -------------------------------------------------------------

    var $view;
    var last =          App.Db.last;
    var stationList =   App.StationList();

    /// Exports: ---------------------------------------------------------------

    App.LastPlayed = {
        updateView:     updateView,
        listStations:   listStations,
        updateStation:  updateStation,
    };

    /// Init: ------------------------------------------------------------------

    $( init );

    /// Functions: -------------------------------------------------------------

    function init() {

        $view = $( "#last > .tabpanel" );
        $view.html( "" ).append( stationList.getView() );

        updateView( switchToSearch );

        function switchToSearch( err, results ) {
            console.log( "switchToSearch", err, results && results.length );
            $view.removeClass( "app-loading" );
            ( err || !results || !results.length ) && App.Explorer.show( "search" );
        }
    };

    function updateView( cb ) {

        stationList.anounceUpdate();
        listStations( null, { limit: 10 }, onStations );

        function onStations( err, stations ) {
            console.log( "onStations", err, stations );

            stationList.update( err, stations );
            cb && cb( err, stations );
        };
    };

    function listStations( filter, options, cb ) {

        last.list( null, options, onList );

        function onList( err, results ) {
            if ( err || !results || !results.length ) {
                cb && cb( err, results );
            } else {
                results = _.sortBy( results, "last_time" ).reverse();
                async.mapSeries( results, readStation, cb );
            }
            function readStation( lastRecord, recordCb ) {
                App.Db.stations.read( lastRecord._id, recordCb );
            };
        };
    };

    function updateStation( station, cb ) {

        var info =  station.info || station;
        var _id =   info.name;
        last.read( _id, onRead );

        function onRead( err, record ) {
            record =            record || {};
            record._id =        _id;
            var new_station =   !record.last_time;
            record.last_time =  (new Date()).getTime();
            record.times =      record.times || 0;
            record.times +=     1;
            last.write( _id, record, onWrite );

            function onWrite( err, result ) {
                cb && cb( err, result );
                new_station && updateView();
            };
        };
    };

    function lastFilter( station ) {

        return station.last_played && App.SoundPlayer.isStationSupported( station );
    };

})( window._, window.async, window.$, window.App );
<commit_msg>Turned on autoplay of last played station.<commit_after>;(function( _, async, $, App ){

    /// Variables: -------------------------------------------------------------

    var $view;
    var last =          App.Db.last;
    var stationList =   App.StationList();

    /// Exports: ---------------------------------------------------------------

    App.LastPlayed = {
        updateView:     updateView,
        listStations:   listStations,
        updateStation:  updateStation,
    };

    /// Init: ------------------------------------------------------------------

    $( init );

    /// Functions: -------------------------------------------------------------

    function init() {

        $view = $( "#last > .tabpanel" );
        $view.html( "" ).append( stationList.getView() );

        updateView( onLoad );

        function onLoad( err, results ) {
            App.debug( "switchToSearch", err, results && results.length );

            $view.removeClass( "app-loading" );
            if ( err || !results || !results.length ) {
                App.Explorer.show( "search" );
            } else {
                App.AppController.playStation( App.Station.fromInfo( results[0] ));
            }
        }
    };

    function updateView( cb ) {

        stationList.anounceUpdate();
        listStations( null, { limit: 10 }, onStations );

        function onStations( err, stations ) {
            console.log( "onStations", err, stations );

            stationList.update( err, stations );
            cb && cb( err, stations );
        };
    };

    function listStations( filter, options, cb ) {

        last.list( null, options, onList );

        function onList( err, results ) {
            if ( err || !results || !results.length ) {
                cb && cb( err, results );
            } else {
                results = _.sortBy( results, "last_time" ).reverse();
                async.mapSeries( results, readStation, cb );
            }
            function readStation( lastRecord, recordCb ) {
                App.Db.stations.read( lastRecord._id, recordCb );
            };
        };
    };

    function updateStation( station, cb ) {

        var info =  station.info || station;
        var _id =   info.name;
        last.read( _id, onRead );

        function onRead( err, record ) {
            record =            record || {};
            record._id =        _id;
            var new_station =   !record.last_time;
            record.last_time =  (new Date()).getTime();
            record.times =      record.times || 0;
            record.times +=     1;
            last.write( _id, record, onWrite );

            function onWrite( err, result ) {
                cb && cb( err, result );
                new_station && updateView();
            };
        };
    };

    function lastFilter( station ) {

        return station.last_played && App.SoundPlayer.isStationSupported( station );
    };

})( window._, window.async, window.$, window.App );
<|endoftext|>


<commit_before>import $ from 'jquery'
import utils from 'utils'

'use strict'

const result = (function () {

  class Height {
    constructor () {
      console.log('height constructor() called')
    }
    destroy (removeComponent) {
      console.log('destroy', removeComponent)
    }
    createNode () {
      const $formElem = $("
")
      const $formValue = $("
")
      $formElem.append($("
Height
"))
      $formValue.append($("
"))
      $formValue.append($("<input id='height-spinner'>"))
      $formElem.append($formValue)
      return $formElem
    }
    styleNode () {
      $('#height-slider').slider({
        animate: true,
        range: 'min',
        min: 0,
        max: 100,
        step: 0.01
      }).on('slide', function (event, ui) {
        $('#height-spinner').spinner('value', utils.pow10Slider(ui.value))
      }).on('slidechange', function (event, ui) {
        $('#height-spinner').spinner('value', utils.pow10Slider(ui.value))
      })
      $('#height-spinner').spinner({
        value: 10,
        min: 0,
        max: 1000,
        step: 0.1
      }).on('spin', function (event, ui) {
        $('#height-slider').slider('value', utils.log10Slider(ui.value))
      }).on('spinchange', function () {
        if (this.value.length > 0) {
          $('#height-slider').slider('value', utils.log10Slider(this.value))
        }
      })
    }
    activateNode (feature) {
      const $heightSlider = $('#height-slider')
      const $heightSpinner = $('#height-spinner')
      $('#height-label').removeClass('disabled')
      $heightSpinner.spinner('enable')
      $heightSlider.slider('enable')
      $heightSpinner.spinner('value', feature.get('height') || feature_properties['height'])
    }
    changeFeatureType (feature_type, feature_templates) {
      const feature_properties = feature_templates[feature_type]
      const $heightSlider = $('#height-slider')
      const $heightSpinner = $('#height-spinner')
      if (!($heightSpinner.spinner('option', 'disabled') || feature_properties['height'])) {
        $heightSpinner.spinner('value', 0)
        $heightSlider.slider('value', 0)
        $heightSpinner.spinner('disable')
        $heightSlider.slider('disable')
        $('#height-label').addClass('disabled')
      } else if ($heightSpinner.spinner('option', 'disabled') && feature_properties['height']) {
        $heightSpinner.spinner('value', feature_properties['height'])
        $heightSlider.slider('value', feature_properties['height'])
        $heightSpinner.spinner('enable')
        $heightSlider.slider('enable')
        $('#height-label').removeClass('disabled')
      }
    }
    loadFeature (feature) {
      // feature.set('height', $('#height-spinner').spinner("value"));
      const $heightSpinner = $('#height-spinner')
      if ($heightSpinner.spinner('value')) {
        feature.set('height', $heightSpinner.spinner('value'))
      }
    }
    deactivateNode () {
      const $heightSlider = $('#height-slider')
      const $heightSpinner = $('#height-spinner')
      $heightSpinner.spinner('disable')
      $heightSlider.slider('disable')

      // },
      // registerForEvents: function () {
      //   sandBox.addEventHandlerToElement('measure-units', 'change', this.handleMeasureUnitsChanged)
      // },
      // unregisterFromEvents: function () {
      //   sandBox.removeEventHandlerFromElement('measure-units', 'change', this.handleMeasureUnitsChanged)
      // },
      // handleMeasureUnitsChanged: function (e) {
      //   sandBox.publishCustomEvent({
      //     type: 'measureunits-Changed',
      //     data: this.value
      //   })
      //   e.preventDefault()
      //   e.stopPropagation()
    }
  }
  return Height
})()

export default result
<commit_msg>update pubsub for height.js<commit_after>import $ from 'jquery'
import utils from 'utils'

'use strict'

const result = (function () {

  class Height {
    constructor () {
      console.log('height constructor() called')
    }
    destroy (removeComponent) {
      console.log('destroy', removeComponent)
    }
    createNode () {
      const $formElem = $("
")
      const $formValue = $("
")
      $formElem.append($("
Height
"))
      $formValue.append($("
"))
      $formValue.append($("<input id='height-spinner'>"))
      $formElem.append($formValue)
      return $formElem
    }
    styleNode () {
      $('#height-slider').slider({
        animate: true,
        range: 'min',
        min: 0,
        max: 100,
        step: 0.01
      }).on('slide', function (event, ui) {
        $('#height-spinner').spinner('value', utils.pow10Slider(ui.value))
      }).on('slidechange', function (event, ui) {
        $('#height-spinner').spinner('value', utils.pow10Slider(ui.value))
      })
      $('#height-spinner').spinner({
        value: 10,
        min: 0,
        max: 1000,
        step: 0.1
      }).on('spin', function (event, ui) {
        $('#height-slider').slider('value', utils.log10Slider(ui.value))
      }).on('spinchange', function () {
        if (this.value.length > 0) {
          $('#height-slider').slider('value', utils.log10Slider(this.value))
        }
      })
    }
    activateNode (feature) {
      const $heightSlider = $('#height-slider')
      const $heightSpinner = $('#height-spinner')
      $('#height-label').removeClass('disabled')
      $heightSpinner.spinner('enable')
      $heightSlider.slider('enable')
      $heightSpinner.spinner('value', feature.get('height') || feature_properties['height'])
    }
    changeFeatureType (feature_type, feature_templates) {
      const feature_properties = feature_templates[feature_type]
      const $heightSlider = $('#height-slider')
      const $heightSpinner = $('#height-spinner')
      if (!($heightSpinner.spinner('option', 'disabled') || feature_properties['height'])) {
        $heightSpinner.spinner('value', 0)
        $heightSlider.slider('value', 0)
        $heightSpinner.spinner('disable')
        $heightSlider.slider('disable')
        $('#height-label').addClass('disabled')
      } else if ($heightSpinner.spinner('option', 'disabled') && feature_properties['height']) {
        $heightSpinner.spinner('value', feature_properties['height'])
        $heightSlider.slider('value', feature_properties['height'])
        $heightSpinner.spinner('enable')
        $heightSlider.slider('enable')
        $('#height-label').removeClass('disabled')
      }
    }
    loadFeature (feature) {
      // feature.set('height', $('#height-spinner').spinner("value"));
      const $heightSpinner = $('#height-spinner')
      if ($heightSpinner.spinner('value')) {
        feature.set('height', $heightSpinner.spinner('value'))
      }
    }
    deactivateNode () {
      const $heightSlider = $('#height-slider')
      const $heightSpinner = $('#height-spinner')
      $heightSpinner.spinner('disable')
      $heightSlider.slider('disable')
    }
    // registerForEvents () {
    //   sandBox.addEventHandlerToElement('height-slider', 'slide', this.handleHeightSliderSlide)
    //   sandBox.addEventHandlerToElement('height-slider', 'slidechange', this.handleHeightSliderChange)
    //   sandBox.addEventHandlerToElement('height-spinner', 'spin', this.handleHeightSpinnerSpin)
    //   sandBox.addEventHandlerToElement('height-spinner', 'spinchange', this.handleHeightSpinnerChange)
    // }
    // unregisterFromEvents () {
    //   sandBox.removeEventHandlerFromElement('height-slider', 'slide', this.handleHeightSliderSlide)
    //   sandBox.removeEventHandlerFromElement('height-slider', 'slidechange', this.handleHeightSliderChange)
    //   sandBox.removeEventHandlerFromElement('height-spinner', 'spin', this.handleHeightSpinnerSpin)
    //   sandBox.removeEventHandlerFromElement('height-spinner', 'spinchange', this.handleHeightSpinnerChange)
    // }
    // handleHeightSliderSlide (e) {
    //   sandBox.publishCustomEvent({
    //     type: 'heightslider-Slid',
    //     data: this.value
    //   })
    //   e.preventDefault()
    //   e.stopPropagation()
    // }
    // handleHeightSliderChange (e) {
    //   sandBox.publishCustomEvent({
    //     type: 'heightslider-Changed',
    //     data: this.value
    //   })
    //   e.preventDefault()
    //   e.stopPropagation()
    // }
    // handleHeightSpinnerSpin (e) {
    //   sandBox.publishCustomEvent({
    //     type: 'heightspinner-Spun',
    //     data: this.value
    //   })
    //   e.preventDefault()
    //   e.stopPropagation()
    // }
    // handleHeightSpinnerChange (e) {
    //   sandBox.publishCustomEvent({
    //     type: 'heightspinner-Changed',
    //     data: this.value
    //   })
    //   e.preventDefault()
    //   e.stopPropagation()
    // }
  }
  return Height
})()

export default result
<|endoftext|>