<commit_before>function setDimension(type, name, id) {
    if ($('#'+type).siblings('input').val() != id) {
        $('#'+type).html(name);
        $('#dimensions input[name='+type+']').val(id).trigger('change');
    }
}

dataviva.requireAttrs(['datasets', 'bra', 'cnae', 'cbo'], function() {
    dataviva.attrs.datasets
    setDimension(type, name, id)
});

var selectorGraphs = Selector()
    .callback(function(d){
        setDimension(selectorGraphs.type(), d.name, d.id)
        $('#modal-selector').modal('hide');
    });

function select_dimension(id) {
    d3.select("#modal-selector-content").call(selectorGraphs.type(id));
    $('#modal-selector').modal('show');
}

var selectorCompare = Selector()
    .callback(function(d){
        if ($('#compare_with').siblings('input').val() != d.id) {
            $('#compare_with').html(d.name);
            $('#compare-location input[name=compare_with]').val(d.id).trigger('change');
            BuildGraph.compare = d.id;
        }
        BuildGraph.setCompare();
        $('#modal-selector').modal('hide');
    });

function select_compare() {
    d3.select("#modal-selector-content").call(selectorCompare.type('bra'));
    $('#modal-selector').modal('show');
}

function clean_selection(id) {
    if ($(id).siblings('input').val() != 'all') {
        $(id).html(dataviva.dictionary['select']);
        $(id).siblings('input').val('all').trigger('change');
    }
}

var BuildGraph = (function () {

    return {
        dataset: dataset,
        views: views,
        selectedView: selectedView,
        selectedGraph: selectedGraph,
        setCompare: setCompare,
        init: init,
        fillForm: fillForm
    }

    var selectedGraph, selectedView, dataset, views;

    function changeDataSet() {
        $('#datasets #dataset-empty-option').remove();
        BuildGraph.dataset = this.value;
        setDimensions(dataviva.datasets[this.value].dimensions);
        updateViews();
    }

    function setDimensions(dimensions) {
        $('#dimensions').empty();
        dimensions.forEach(function(dimension, index) {
            var div = $('

').addClass('form-group'),
                filter = $('<input></input>').attr('type', 'hidden').attr('name', dimension.id).attr('id', 'filter'+index).val('all'),
                label = $('').attr('for', dimension.id).addClass('control-label'),
                selector = $('<button></button>').attr('id', dimension.id).addClass('btn btn-block btn-outline btn-primary')
                                        .html(dataviva.dictionary['select'])
                                        .attr('onclick', 'select_dimension(id);'),
                cleaner = $('<button></button>').attr('for', dimension.id).addClass('btn btn-xs btn-link pull-right')
                                        .html(dataviva.dictionary['clean_selection'])
                                        .attr('onclick', 'clean_selection('+dimension.id+')');

            label.html(dataviva.dictionary[dimension.id]);
            filter.change(updateViews);

            if (dimension.name == 'School') {
                div.append(filter);
            } else {
                div.append(filter).append(label).append(selector).append(cleaner);
            }

            $('#dimensions').append(div);
        });
    }

    function updateViews() {
        $.ajax({
            method: "GET",
            url: "/" + dataviva.language + "/build_graph/views/" + BuildGraph.dataset +"/" +
                $('#dimensions #filter0').val() +
                ($('#compare-location input[name=compare_with]').val() ? '_' + $('#compare-location input[name=compare_with]').val() : '') + "/" +
                ($('#dimensions #filter1').val() == 'all' ? 'all' : $('#dimensions #filter1')[0].name) + "/" +
                ($('#dimensions #filter2').val() == 'all' ? 'all' : $('#dimensions #filter2')[0].name),
            data: {
                    filter1: $('#dimensions #filter1').val(),
                    filter2: $('#dimensions #filter2').val()
                },
            success: function (result) {
                setViews(result.views);
            }
        });
    }

    function setViews(views) {
        BuildGraph.views = views;
        $('#views').empty()

        var div = $('

').addClass('form-group');
            select = $('<select></select>').addClass('form-control'),
            label = $('').attr('for', 'titles').addClass('control-label'),

        label.html(dataviva.dictionary['views']);

        for(id in views){
            var option = $('<option value="'+id+'">'+views[id].name+'</option>');
            select.append(option);
        }

        select.change(function() {
            BuildGraph.selectedView = this.value;
            setGraphs(BuildGraph.views[this.value].graphs);
        });

        div.append(label).append(select);
        $('#views').append(div);

        // Try to keep the selected view, else keep whatever comes selected
        if ($.inArray(BuildGraph.selectedView, Object.keys(views)) > -1) {
            $('#views select').val(BuildGraph.selectedView);
        } else {
            BuildGraph.selectedView = views[$('#views select').val()].id;
        }

        setGraphs(views[BuildGraph.selectedView].graphs);
    }

    function setGraphs(graphs) {
        $('#graphs').empty()

        var div = $('

').attr('class', 'dropdown dropdown-select form-group');
            graphButton = $('<button data-toggle="dropdown" aria-expanded="true"></button>')
                            .attr('id', 'selected-graph')
                            .attr('class', 'btn btn-outline btn-block dropdown-toggle'),
            dropDownMenu = $('

')
                            .attr('class', 'dropdown-menu'),
            label = $('').attr('for', 'selected-graph').addClass('control-label');

        label.html(dataviva.dictionary['graphs']);

        for(id in graphs){
            var graphLink = $('')
                            .attr('id', id)
                            .attr('class', 'graph-link')
                            .data('url', "/" + dataviva.language + '/embed/' + graphs[id].url)
                            .html('' + graphs[id].name);

            var graphOption = $('

').append(graphLink);

            dropDownMenu.append(graphOption);
        }

        div.on( 'click', '.dropdown-menu li a', function(argument) {
           selectGraph(this);
        });

        div.append(label).append(graphButton).append(dropDownMenu);

        $('#graphs').append(div);

        // Try to keep the selected graph, else select the first graph
        if ($.inArray(BuildGraph.selectedGraph, Object.keys(graphs)) > -1) {
            selectGraph($('#'+BuildGraph.selectedGraph));
        } else {
            BuildGraph.selectedGraph = $('#selected-graph').data('graph');
            selectGraph($('#selected-graph').siblings('.dropdown-menu').find('li a').first());
        }
    }

    function selectGraph(graph) {
        BuildGraph.selectedGraph = $(graph).attr('id');

        var graphName = $(graph).html();

        //Adds active class to selected item
        $(graph).parents('.dropdown-menu').find('li').removeClass('active');
        $(graph).parent('li').addClass('active');

        //Displays selected text on dropdown-toggle button
        $('#selected-graph').data('graph', $(graph).attr('id'));
        $('#selected-graph').html(graphName);

        if (BuildGraph.selectedGraph == 'compare') {
            setCompare();
        } else {
            $('#compare-location').empty();
            delete BuildGraph.compare;
            $('#graph-wrapper').html('');
        }
    }

    function setCompare(){
        if (BuildGraph.compare) {
            $('#graph-wrapper').html('');
        } else {
            $('#compare-location').empty();

            var div = $('

').addClass('form-group'),
                label = $('').attr('for', 'compare_with').addClass('control-label'),
                cleaner = $('<button></button>').attr('for', 'compare_with').addClass('btn btn-xs btn-link pull-right')
                                        .html(dataviva.dictionary['clean_selection'])
                                        .attr('onclick', 'clean_selection('+'compare_with'+')'),
                selector = $('<button></button>').attr('id', 'compare_with').addClass('btn btn-block btn-outline btn-primary')
                                        .html(dataviva.dictionary['select'])
                                        .attr('onclick', 'select_compare();'),
                filter = $('<input></input>').attr('type', 'hidden').attr('name', 'compare_with').attr('id', 'compare_filter').val('all');

            label.html(dataviva.dictionary['compare_with']);
            filter.change(updateViews);

            div.append(filter).append(label).append(selector).append(cleaner);

            $('#compare-location').append(div);
        }
    }

    function init() {
        for (dataset in dataviva.datasets) {
            $('#datasets').append( $('<option value="'+dataset+'">'+dataviva.dictionary[dataset]+'</option>'));
        }

        $('#datasets').change(changeDataSet);
    }

    function fillForm(){
        var url = window.location.href.split('?')[0];
        var urlFilters = url.split('build_graph/')[1].split('/');

        //Fill Dataset
        if (urlFilters[0]){
            var dataset = urlFilters[0];
        }

        $('#datasets').val(dataset);
        BuildGraph.dataset = dataset;
        setDimensions(dataviva.datasets[dataset].dimensions);

        //Fill Dimensions
        var filters = {};

        filters['f0'] = urlFilters[1];
        $('#dimensions #filter0').val(filters['f0']);

        var valueText0 = 'Selected'
        if (filters['f0'] != 'all') valueText0 = dataviva.bra[filters['f0']].name;
        $('#dimensions #bra').text(valueText0)

        filters['f1'] = urlFilters[2];
        $('#dimensions #filter1').val(filters['f1']);

        var filter1 = $('#dimensions div').children('button')[2].id
        var valueText1 = 'Selected';
        if (filters['f1'] != 'all'){
            if (filter1 == 'cnae')
                valueText1 = dataviva.cnae[filters['f1']].name;
            else if (filter1 == 'hs')
                valueText1 = dataviva.hs[filters['f1']].name;
            else if (filter1 == 'course_sc')
                valueText1 = dataviva.course_sc[filters['f1']].name;
            else if (filter1 == 'university')
                valueText1 = dataviva.university[filters['f1']].name;
        }
        $('#dimensions #'+filter1).text(valueText1)

        if (urlFilters[3]){
            filters['f2'] = urlFilters[3];
            $('#dimensions #filter2').val(filters['f2']);

            var filter2 = $('#dimensions div').children('button')[4].id
            var valueText2 = 'Selected';
            if (filters['f2'] != 'all'){
                if (filter2 == 'cbo')
                    valueText2 = dataviva.cbo[filters['f2']].name;
                else if (filter2 == 'wld')
                    valueText2 = dataviva.wld[filters['f2']].name;
                else if (filter2 == 'course_hedu')
                    valueText2 = dataviva.course_hedu[filters['f2']].name;
            }
            $('#dimensions #'+filter2).text(valueText2)
        }

        updateViews();
    }
})();

$(document).ready(function () {
    dataviva.requireAttrs(['datasets'], function() {
        BuildGraph.init();
        BuildGraph.fillForm();
    });
});

<commit_msg>Adds gill parameters in url.<commit_after>function setDimension(type, name, id) {
    if ($('#'+type).siblings('input').val() != id) {
        $('#'+type).html(name);
        $('#dimensions input[name='+type+']').val(id).trigger('change');
    }
}

dataviva.requireAttrs(['datasets', 'bra', 'cnae', 'cbo'], function() {
    dataviva.attrs.datasets
    setDimension(type, name, id)
});

var selectorGraphs = Selector()
    .callback(function(d){
        setDimension(selectorGraphs.type(), d.name, d.id)
        $('#modal-selector').modal('hide');
    });

function select_dimension(id) {
    d3.select("#modal-selector-content").call(selectorGraphs.type(id));
    $('#modal-selector').modal('show');
}

var selectorCompare = Selector()
    .callback(function(d){
        if ($('#compare_with').siblings('input').val() != d.id) {
            $('#compare_with').html(d.name);
            $('#compare-location input[name=compare_with]').val(d.id).trigger('change');
            BuildGraph.compare = d.id;
        }
        BuildGraph.setCompare();
        $('#modal-selector').modal('hide');
    });

function select_compare() {
    d3.select("#modal-selector-content").call(selectorCompare.type('bra'));
    $('#modal-selector').modal('show');
}

function clean_selection(id) {
    if ($(id).siblings('input').val() != 'all') {
        $(id).html(dataviva.dictionary['select']);
        $(id).siblings('input').val('all').trigger('change');
    }
}

var BuildGraph = (function () {

    return {
        dataset: dataset,
        views: views,
        selectedView: selectedView,
        selectedGraph: selectedGraph,
        setCompare: setCompare,
        init: init,
        fillForm: fillForm
    }

    var selectedGraph, selectedView, dataset, views;

    function changeDataSet() {
        $('#datasets #dataset-empty-option').remove();
        BuildGraph.dataset = this.value;
        setDimensions(dataviva.datasets[this.value].dimensions);
        updateViews();
    }

    function setDimensions(dimensions) {
        $('#dimensions').empty();
        dimensions.forEach(function(dimension, index) {
            var div = $('

').addClass('form-group'),
                filter = $('<input></input>').attr('type', 'hidden').attr('name', dimension.id).attr('id', 'filter'+index).val('all'),
                label = $('').attr('for', dimension.id).addClass('control-label'),
                selector = $('<button></button>').attr('id', dimension.id).addClass('btn btn-block btn-outline btn-primary')
                                        .html(dataviva.dictionary['select'])
                                        .attr('onclick', 'select_dimension(id);'),
                cleaner = $('<button></button>').attr('for', dimension.id).addClass('btn btn-xs btn-link pull-right')
                                        .html(dataviva.dictionary['clean_selection'])
                                        .attr('onclick', 'clean_selection('+dimension.id+')');

            label.html(dataviva.dictionary[dimension.id]);
            filter.change(updateViews);

            if (dimension.name == 'School') {
                div.append(filter);
            } else {
                div.append(filter).append(label).append(selector).append(cleaner);
            }

            $('#dimensions').append(div);
        });
    }

    function updateViews() {
        $.ajax({
            method: "GET",
            url: "/" + dataviva.language + "/build_graph/views/" + BuildGraph.dataset +"/" +
                $('#dimensions #filter0').val() +
                ($('#compare-location input[name=compare_with]').val() ? '_' + $('#compare-location input[name=compare_with]').val() : '') + "/" +
                ($('#dimensions #filter1').val() == 'all' ? 'all' : $('#dimensions #filter1')[0].name) + "/" +
                ($('#dimensions #filter2').val() == 'all' ? 'all' : $('#dimensions #filter2')[0].name),
            data: {
                    filter1: $('#dimensions #filter1').val(),
                    filter2: $('#dimensions #filter2').val()
                },
            success: function (result) {
                setViews(result.views);
            }
        });
    }

    function setViews(views) {
        BuildGraph.views = views;
        $('#views').empty()

        var div = $('

').addClass('form-group');
            select = $('<select></select>').addClass('form-control'),
            label = $('').attr('for', 'titles').addClass('control-label'),

        label.html(dataviva.dictionary['views']);

        for(id in views){
            var option = $('<option value="'+id+'">'+views[id].name+'</option>');
            select.append(option);
        }

        select.change(function() {
            BuildGraph.selectedView = this.value;
            setGraphs(BuildGraph.views[this.value].graphs);
        });

        div.append(label).append(select);
        $('#views').append(div);

        // Try to keep the selected view, else keep whatever comes selected
        if ($.inArray(BuildGraph.selectedView, Object.keys(views)) > -1) {
            $('#views select').val(BuildGraph.selectedView);
        } else {
            BuildGraph.selectedView = views[$('#views select').val()].id;
        }

        setGraphs(views[BuildGraph.selectedView].graphs);
    }

    function setGraphs(graphs) {
        $('#graphs').empty()

        var div = $('

').attr('class', 'dropdown dropdown-select form-group');
            graphButton = $('<button data-toggle="dropdown" aria-expanded="true"></button>')
                            .attr('id', 'selected-graph')
                            .attr('class', 'btn btn-outline btn-block dropdown-toggle'),
            dropDownMenu = $('

')
                            .attr('class', 'dropdown-menu'),
            label = $('').attr('for', 'selected-graph').addClass('control-label');

        label.html(dataviva.dictionary['graphs']);

        for(id in graphs){
            var graphLink = $('')
                            .attr('id', id)
                            .attr('class', 'graph-link')
                            .data('url', "/" + dataviva.language + '/embed/' + graphs[id].url)
                            .html('' + graphs[id].name);

            var graphOption = $('

').append(graphLink);

            dropDownMenu.append(graphOption);
        }

        div.on( 'click', '.dropdown-menu li a', function(argument) {
           selectGraph(this);
        });

        div.append(label).append(graphButton).append(dropDownMenu);

        $('#graphs').append(div);

        // Try to keep the selected graph, else select the first graph
        if ($.inArray(BuildGraph.selectedGraph, Object.keys(graphs)) > -1) {
            selectGraph($('#'+BuildGraph.selectedGraph));
        } else {
            BuildGraph.selectedGraph = $('#selected-graph').data('graph');
            selectGraph($('#selected-graph').siblings('.dropdown-menu').find('li a').first());
        }
    }

    function selectGraph(graph) {
        BuildGraph.selectedGraph = $(graph).attr('id');

        var graphName = $(graph).html();

        //Adds active class to selected item
        $(graph).parents('.dropdown-menu').find('li').removeClass('active');
        $(graph).parent('li').addClass('active');

        //Displays selected text on dropdown-toggle button
        $('#selected-graph').data('graph', $(graph).attr('id'));
        $('#selected-graph').html(graphName);

        if (BuildGraph.selectedGraph == 'compare') {
            setCompare();
        } else {
            $('#compare-location').empty();
            delete BuildGraph.compare;
            $('#graph-wrapper').html('');
        }
    }

    function setCompare(){
        if (BuildGraph.compare) {
            $('#graph-wrapper').html('');
        } else {
            $('#compare-location').empty();

            var div = $('

').addClass('form-group'),
                label = $('').attr('for', 'compare_with').addClass('control-label'),
                cleaner = $('<button></button>').attr('for', 'compare_with').addClass('btn btn-xs btn-link pull-right')
                                        .html(dataviva.dictionary['clean_selection'])
                                        .attr('onclick', 'clean_selection('+'compare_with'+')'),
                selector = $('<button></button>').attr('id', 'compare_with').addClass('btn btn-block btn-outline btn-primary')
                                        .html(dataviva.dictionary['select'])
                                        .attr('onclick', 'select_compare();'),
                filter = $('<input></input>').attr('type', 'hidden').attr('name', 'compare_with').attr('id', 'compare_filter').val('all');

            label.html(dataviva.dictionary['compare_with']);
            filter.change(updateViews);

            div.append(filter).append(label).append(selector).append(cleaner);

            $('#compare-location').append(div);
        }
    }

    function init() {
        for (dataset in dataviva.datasets) {
            $('#datasets').append( $('<option value="'+dataset+'">'+dataviva.dictionary[dataset]+'</option>'));
        }

        $('#datasets').change(changeDataSet);
    }

    function fillForm(){
        var url = window.location.href.split('?')[0];
        var urlFilters = url.split('build_graph/')[1].split('/');

        //Fill Dataset
        if (urlFilters[0]){
            var dataset = urlFilters[0];
        }

        $('#datasets').val(dataset);
        BuildGraph.dataset = dataset;
        setDimensions(dataviva.datasets[dataset].dimensions);

        //Fill Dimensions
        var filters = {};

        filters['f0'] = urlFilters[1];
        $('#dimensions #filter0').val(filters['f0']);

        var valueText0 = 'Selected'
        if (filters['f0'] != 'all') valueText0 = dataviva.bra[filters['f0']].name;
        $('#dimensions #bra').text(valueText0)

        filters['f1'] = urlFilters[2];
        $('#dimensions #filter1').val(filters['f1']);

        var filter1 = $('#dimensions div').children('button')[2].id
        var valueText1 = 'Selected';
        if (filters['f1'] != 'all'){
            if (filter1 == 'cnae')
                valueText1 = dataviva.cnae[filters['f1']].name;
            else if (filter1 == 'hs')
                valueText1 = dataviva.hs[filters['f1']].name;
            else if (filter1 == 'course_sc')
                valueText1 = dataviva.course_sc[filters['f1']].name;
            else if (filter1 == 'university')
                valueText1 = dataviva.university[filters['f1']].name;
        }
        $('#dimensions #'+filter1).text(valueText1)

        if (urlFilters[3]){
            filters['f2'] = urlFilters[3];
            $('#dimensions #filter2').val(filters['f2']);

            var filter2 = $('#dimensions div').children('button')[4].id
            var valueText2 = 'Selected';
            if (filters['f2'] != 'all'){
                if (filter2 == 'cbo')
                    valueText2 = dataviva.cbo[filters['f2']].name;
                else if (filter2 == 'wld')
                    valueText2 = dataviva.wld[filters['f2']].name;
                else if (filter2 == 'course_hedu')
                    valueText2 = dataviva.course_hedu[filters['f2']].name;
            }
            $('#dimensions #'+filter2).text(valueText2)
        }

        //Fill Parameters
        if (window.location.href.split('?')[1]){
            var urlParameters = window.location.href.split('?')[1];
            var parameters = {};
            $.each(urlParameters.split('%26'), function(){
                if(this.split('%3D')[0] == 'views') parameters['views'] = this.split('%3D')[1];
                else if (this.split('%3D')[0] == 'graph') parameters['graph'] = this.split('%3D')[1];
                else if (this.split('%3D')[0] == 'compare') parameters['compare'] = this.split('%3D')[1];
            })
        }

        updateViews();
    }
})();

$(document).ready(function () {
    dataviva.requireAttrs(['datasets'], function() {
        BuildGraph.init();
        BuildGraph.fillForm();
    });
});

<|endoftext|>


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

var emailReader = require('./emailReader.js');

exports.readEmail = function(callWhenDone) {
	emailReader.readEmail(mapEmailDataToRectangles, callWhenDone);
};

// alle 10 Sekunden context.io fragen
// query mit date_after = das letzte Mal als ich gefragt habe

function mapEmailDataToRectangles(messages, callback) {

	// addresses.from.email
	// addresses.from.name

	var messagesToday = _.filter(messages, function(message) {
		return moment().diff(moment(message.date, 'X'), 'days') === 0;
	});
	var messagesYesterday = _.filter(messages, function(message) {
		return moment().diff(moment(message.date, 'X'), 'days') === 1;
	});
	var messagesOld = _.filter(messages, function(message) {
		return moment().diff(moment(message.date, 'X'), 'days') > 1;
	});

	function isFromThoughtworks(message) {
		return message.addresses.from.email.indexOf('thoughtworks') > -1;
	}

	console.log('Got emails from', _.map(messages, function(message) {
		return message.addresses.from.email + ', ' + message.date;
	}));

	var countInternalToday = _.countBy(messagesToday, isFromThoughtworks);
	var countInternalYesterday = _.countBy(messagesYesterday, isFromThoughtworks);
	var countInternalOld = _.countBy(messagesOld, isFromThoughtworks);

	callback(_.compact([
		createNumberOfMessagesRect(countInternalToday.true || 0, "blue", 2),
		createNumberOfMessagesRect(countInternalToday.false || 0, "red", 2),
		createNumberOfMessagesRect(countInternalYesterday.true || 0, "blue", 1),
		createNumberOfMessagesRect(countInternalYesterday.false || 0, "red", 1),
		createNumberOfMessagesRect(countInternalOld.true || 0, "blue", 0),
		createNumberOfMessagesRect(countInternalOld.false || 0, "red", 0) ]));

};

function createNumberOfMessagesRect(count, color, column) {
	if (count === 0) {
		return undefined;
	}
	var rect = { color: color, column: column };
	if(count < 5) {
		rect.size = "small";
	} else if(count < 15) {
		rect.size = "medium";
	} else {
		rect.size = "large";
	}

	return rect;
}
<commit_msg>added fake message for presentation<commit_after>var _ = require('lodash');
var moment = require('moment');
var http = require('http');

var emailReader = require('./emailReader.js');

exports.readEmail = function(callWhenDone) {
	emailReader.readEmail(mapEmailDataToRectangles, callWhenDone);
};

// alle 10 Sekunden context.io fragen
// query mit date_after = das letzte Mal als ich gefragt habe

function mapEmailDataToRectangles(messages, callback) {

	// addresses.from.email
	// addresses.from.name

	var messagesToday = _.filter(messages, function(message) {
		return moment().diff(moment(message.date, 'X'), 'days') === 0;
	});
	var messagesYesterday = _.filter(messages, function(message) {
		return moment().diff(moment(message.date, 'X'), 'days') === 1;
	});
	var messagesOld = _.filter(messages, function(message) {
		return moment().diff(moment(message.date, 'X'), 'days') > 1;
	});

	function isFromThoughtworks(message) {
		return message.addresses.from.email.indexOf('thoughtworks') > -1;
	}

	console.log('Got emails from', _.map(messages, function(message) {
		return message.addresses.from.email + ', ' + message.date;
	}));

	var countInternalToday = _.countBy(messagesToday, isFromThoughtworks);
	var countInternalYesterday = _.countBy(messagesYesterday, isFromThoughtworks);
	var countInternalOld = _.countBy(messagesOld, isFromThoughtworks);

	callback(_.compact([
		createNumberOfMessagesRect(countInternalToday.true || 0, "blue", 2),
		createNumberOfMessagesRect(countInternalToday.false || 0, "red", 2),
		createNumberOfMessagesRect(countInternalYesterday.true || 0, "blue", 1),
		createNumberOfMessagesRect(countInternalYesterday.false || 0, "red", 1),
		//createNumberOfMessagesRect(countInternalOld.true || 0, "blue", 0),
		//createNumberOfMessagesRect(countInternalOld.false || 0, "red", 0)
	    // fake older messages for presentation
	    createNumberOfMessagesRect(3 || 0, "blue", 0),
		createNumberOfMessagesRect(7 || 0, "red", 0) ]));

};

function createNumberOfMessagesRect(count, color, column) {
	if (count === 0) {
		return undefined;
	}
	var rect = { color: color, column: column };
	if(count < 5) {
		rect.size = "small";
	} else if(count < 15) {
		rect.size = "medium";
	} else {
		rect.size = "large";
	}

	return rect;
}
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var util = require('util');
var assert = require('assert');
var Module = require('module');
var _ = require('underscore');

var Plexus = require('..').Plexus;

// Load wrappers
var wrappers = {};
fs.readdirSync(__dirname).forEach(function(name) {
    var match = name.match(/^(.+)\.(prefix|suffix)\.js$/);
    if (match) {
        wrappers[match[1]] = wrappers[match[1]] || {};
        wrappers[match[1]][match[2]] =
            fs.readFileSync(path.join(__dirname, name), 'utf8')
                .split('\n').join('');
    }
});

require.extensions['.plexus'] = function(module, filename) {
    var content = fs.readFileSync(filename, 'utf8');
    var kind = Plexus.singularize(path.basename(path.dirname(filename)));

    wrappers[kind] = wrappers[kind] || {};
    wrappers[kind].prefix = wrappers[kind].prefix || '';
    wrappers[kind].suffix = wrappers[kind].suffix || '';

    content = wrappers[kind].prefix + ';' + content + ';' + wrappers[kind].suffix;
    module.plexus = require('..');
    module._compile(content, filename);
};

function Plugin(dir) {
    this.directory = dir;
    this.controllers = {};
    this.models = {};
    this.routers = {};
    this.templates = {};
    this.views = {};
    this.servers = {};
    this.commands = {};
};

Plugin.prototype.load = function(plugin) {
    if (!plugin) {
        // Load the current directory.
        this.require('controllers');
        this.require('models');
        this.require('routers');
        this.require('templates');
        this.require('views');
        this.require('servers');
        this.require('commands');
    } else {
        _.extend(this.controllers, plugin.controllers);
        _.extend(this.models, plugin.models);
        _.extend(this.routers, plugin.routers);
        _.extend(this.templates, plugin.templates);
        _.extend(this.views, plugin.views);
        _.extend(this.servers, plugin.servers);
        _.extend(this.commands, plugin.commands);
    }
};

Plugin.prototype.require = function(kind) {
    var plugin = this, dir = path.join(plugin.directory, kind);

    try {
        fs.readdirSync(dir).forEach(function(name) {
            var file = path.join(dir, name);
            if (path.extname(file) in require.extensions &&
                path.basename(file)[0] !== '.' &&
                fs.statSync(file).isFile()) {
                var component = require(file);

                if (component) {
                    if (!component.files) component.files = [];
                    component.files.push(file);

                    if (!component.title) {
                        component.title = Plexus.camelize(
                            path.basename(file).replace(/\..+$/, ''));
                    }
                    plugin[kind][component.title] = component;
                }
            }
        });
    } catch(err) {
        if (err.code !== 'ENOENT') throw err;
        return {};
    }
};

Plugin.prototype.start = function() {
    this.argv = require('optimist').argv;

    var command = this.argv._.length ? this.argv._[0] : 'start';
    if (this.argv.help || !(command in this.commands)) {
        this.help();
    } else {
        var command = this.commands[command];
        this.config = this.loadConfig(command);
        new command(this);
    }
};

Plugin.prototype.loadConfig = function(command) {
    var config = {
        verbose: false
    };

    if (this.argv.config) {
        try {
            config = JSON.parse(fs.readFileSync(this.argv.config, 'utf8'));
        } catch(e) {
            console.error(Plexus.colorize('Invalid JSON config file: ' +
                this.argv.config, 'red'));
            process.exit(2);
        }
    }

    for (var key in command.options) {
        if (!(key in config)) {
            config[key] = command.options[key]['default'];
        }
        if (command.options[key]['shortcut'] in this.argv) {
            config[key] = this.argv[command.options[key]['shortcut']];
            delete this.argv[command.options[key]['shortcut']]
        }
        if (key in this.argv) {
            config[key] = this.argv[key];
            delete this.argv[key];
        }
    }

    _.defaults(config, this.argv);

    var showConfig = false;
    for (var key in config) {
        if (key === 'config' || key === '_' || key[0] === '$') {
            delete config[key];
        }
        else if (key === 'show-config') {
            showConfig = config[key];
            delete config[key];
        }
        else {
            if (key !== 'verbose' && !(key in command.options)) {
                if (key in this.argv) {
                    // It was specified on the command line.
                     console.warn(Plexus.colorize('Note: Unknown option "' + key + '".', 'yellow'))
                } else {
                    // It's from the config file.
                    console.warn(Plexus.colorize('Note: Unknown option "' + key + '" in config file.', 'yellow'))
                }
            }
            if (typeof config[key] === 'function') config[key] = config[key](this);
        }
    }

    if (showConfig) {
        console.warn(Plexus.colorize('Using configuration:', 'green'));
        console.warn(JSON.stringify(config, false, 4));
    }

    return config;
};

Plugin.prototype.help = function() {
    var command = this.argv._.length ? this.argv._[0] : false;
    if (command !== false && command in this.commands) {
        // Display information about this command.
        var command = this.commands[command];
        console.log('Usage: %s', Plexus.colorize(this.argv['$0'] + ' ' +
            command.title +
            (command.usage ? ' ' + command.usage : '') +
            ' [options...]', 'green'));

        console.log('%s%s: %s',
            Plexus.colorize(command.title, 'yellow', 'bold'),
            Plexus.colorize(command.usage ? ' ' + command.usage : '', 'yellow'),
            command.description);

        var options = [];
        for (var key in command.options) {
            var option = command.options[key];
            var value = option['default'];
            if (typeof value === 'function') value = value(this);
            options.push([
                option.shortcut ? '-' + option.shortcut : '',
                '--' + (option.title || key),
                (option.description ? option.description + ' ' : '') + '(Default: ' + util.inspect(value) +')'
            ]);
        }
        options.push([ '', '--verbose', 'Be more verbose. (Default: false)' ]);
        options.push([ '', '--config=[path]', 'Path to JSON configuration file.' ]);

        table(options);
    } else {
        // Display information about all available commands.
        console.log('Usage: %s for a list of options.', Plexus.colorize(this.argv['$0'] + ' ' + (command || '[command]') + ' --help', 'green'));
        console.log('Available commands are:');
        var commands = [];
        for (var key in this.commands) {
            commands.push([ this.commands[key].title + ':', this.commands[key].description || ''])
        }
        table(commands);
    }
    process.exit(1);
};

function table(fields) {
    if (!fields[0]) return;
    var lengths = fields[0].map(function(val, i) {
        return Math.max.apply(Math, fields.map(function(field) {
            return field[i].length;
        }));
    });
    fields.forEach(function(field) {
        console.log(
            '  ' + field.map(function(val, i) {
                if (i >= lengths.length - 1) return val;
                return val + Array(lengths[i] - val.length + 1).join(' ');
            }).join('  ')
        );
    });
};

// plexus.plugin(__dirname)
module.exports = function(dir) {
    var plugin = new Plugin(dir);
    plugin.load(require('../core'));
    return plugin;
};
<commit_msg>remove verbose flag<commit_after>var path = require('path');
var fs = require('fs');
var util = require('util');
var assert = require('assert');
var Module = require('module');
var _ = require('underscore');

var Plexus = require('..').Plexus;

// Load wrappers
var wrappers = {};
fs.readdirSync(__dirname).forEach(function(name) {
    var match = name.match(/^(.+)\.(prefix|suffix)\.js$/);
    if (match) {
        wrappers[match[1]] = wrappers[match[1]] || {};
        wrappers[match[1]][match[2]] =
            fs.readFileSync(path.join(__dirname, name), 'utf8')
                .split('\n').join('');
    }
});

require.extensions['.plexus'] = function(module, filename) {
    var content = fs.readFileSync(filename, 'utf8');
    var kind = Plexus.singularize(path.basename(path.dirname(filename)));

    wrappers[kind] = wrappers[kind] || {};
    wrappers[kind].prefix = wrappers[kind].prefix || '';
    wrappers[kind].suffix = wrappers[kind].suffix || '';

    content = wrappers[kind].prefix + ';' + content + ';' + wrappers[kind].suffix;
    module.plexus = require('..');
    module._compile(content, filename);
};

function Plugin(dir) {
    this.directory = dir;
    this.controllers = {};
    this.models = {};
    this.routers = {};
    this.templates = {};
    this.views = {};
    this.servers = {};
    this.commands = {};
};

Plugin.prototype.load = function(plugin) {
    if (!plugin) {
        // Load the current directory.
        this.require('controllers');
        this.require('models');
        this.require('routers');
        this.require('templates');
        this.require('views');
        this.require('servers');
        this.require('commands');
    } else {
        _.extend(this.controllers, plugin.controllers);
        _.extend(this.models, plugin.models);
        _.extend(this.routers, plugin.routers);
        _.extend(this.templates, plugin.templates);
        _.extend(this.views, plugin.views);
        _.extend(this.servers, plugin.servers);
        _.extend(this.commands, plugin.commands);
    }
};

Plugin.prototype.require = function(kind) {
    var plugin = this, dir = path.join(plugin.directory, kind);

    try {
        fs.readdirSync(dir).forEach(function(name) {
            var file = path.join(dir, name);
            if (path.extname(file) in require.extensions &&
                path.basename(file)[0] !== '.' &&
                fs.statSync(file).isFile()) {
                var component = require(file);

                if (component) {
                    if (!component.files) component.files = [];
                    component.files.push(file);

                    if (!component.title) {
                        component.title = Plexus.camelize(
                            path.basename(file).replace(/\..+$/, ''));
                    }
                    plugin[kind][component.title] = component;
                }
            }
        });
    } catch(err) {
        if (err.code !== 'ENOENT') throw err;
        return {};
    }
};

Plugin.prototype.start = function() {
    this.argv = require('optimist').argv;

    var command = this.argv._.length ? this.argv._[0] : 'start';
    if (this.argv.help || !(command in this.commands)) {
        this.help();
    } else {
        var command = this.commands[command];
        this.config = this.loadConfig(command);
        new command(this);
    }
};

Plugin.prototype.loadConfig = function(command) {
    var config = {};

    if (this.argv.config) {
        try {
            config = JSON.parse(fs.readFileSync(this.argv.config, 'utf8'));
        } catch(e) {
            console.error(Plexus.colorize('Invalid JSON config file: ' +
                this.argv.config, 'red'));
            process.exit(2);
        }
    }

    for (var key in command.options) {
        if (!(key in config)) {
            config[key] = command.options[key]['default'];
        }
        if (command.options[key]['shortcut'] in this.argv) {
            config[key] = this.argv[command.options[key]['shortcut']];
            delete this.argv[command.options[key]['shortcut']];
        }
        if (key in this.argv) {
            config[key] = this.argv[key];
            delete this.argv[key];
        }
    }

    _.defaults(config, this.argv);

    var showConfig = false;
    for (var key in config) {
        if (key === 'config' || key === '_' || key[0] === '$') {
            delete config[key];
        }
        else if (key === 'show-config') {
            showConfig = config[key];
            delete config[key];
        }
        else {
            if (!(key in command.options)) {
                if (key in this.argv) {
                    // It was specified on the command line.
                     console.warn(Plexus.colorize('Note: Unknown option "' + key + '".', 'yellow'));
                } else {
                    // It's from the config file.
                    console.warn(Plexus.colorize('Note: Unknown option "' + key + '" in config file.', 'yellow'));
                }
            }
            if (typeof config[key] === 'function') config[key] = config[key](this);
        }
    }

    if (showConfig) {
        console.warn(Plexus.colorize('Using configuration:', 'green'));
        console.warn(JSON.stringify(config, false, 4));
    }

    return config;
};

Plugin.prototype.help = function() {
    var command = this.argv._.length ? this.argv._[0] : false;
    if (command !== false && command in this.commands) {
        // Display information about this command.
        var command = this.commands[command];
        console.log('Usage: %s', Plexus.colorize(this.argv['$0'] + ' ' +
            command.title +
            (command.usage ? ' ' + command.usage : '') +
            ' [options...]', 'green'));

        console.log('%s%s: %s',
            Plexus.colorize(command.title, 'yellow', 'bold'),
            Plexus.colorize(command.usage ? ' ' + command.usage : '', 'yellow'),
            command.description);

        var options = [];
        for (var key in command.options) {
            var option = command.options[key];
            var value = option['default'];
            if (typeof value === 'function') value = value(this);
            options.push([
                option.shortcut ? '-' + option.shortcut : '',
                '--' + (option.title || key),
                (option.description ? option.description + ' ' : '') + '(Default: ' + util.inspect(value) +')'
            ]);
        }
        options.push([ '', '--config=[path]', 'Path to JSON configuration file.' ]);

        table(options);
    } else {
        // Display information about all available commands.
        console.log('Usage: %s for a list of options.', Plexus.colorize(this.argv['$0'] + ' ' + (command || '[command]') + ' --help', 'green'));
        console.log('Available commands are:');
        var commands = [];
        for (var key in this.commands) {
            commands.push([ this.commands[key].title + ':', this.commands[key].description || '']);
        }
        table(commands);
    }
    process.exit(1);
};

function table(fields) {
    if (!fields[0]) return;
    var lengths = fields[0].map(function(val, i) {
        return Math.max.apply(Math, fields.map(function(field) {
            return field[i].length;
        }));
    });
    fields.forEach(function(field) {
        console.log(
            '  ' + field.map(function(val, i) {
                if (i >= lengths.length - 1) return val;
                return val + Array(lengths[i] - val.length + 1).join(' ');
            }).join('  ')
        );
    });
};

// plexus.plugin(__dirname)
module.exports = function(dir) {
    var plugin = new Plugin(dir);
    plugin.load(require('../core'));
    return plugin;
};
<|endoftext|>


<commit_before>// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

import React, {PropTypes, PureComponent} from 'react';
import {
    Image,
    Keyboard,
    Platform,
    StatusBar,
    TouchableWithoutFeedback,
    View
} from 'react-native';

import Button from 'react-native-button';
import ErrorText from 'app/components/error_text';
import FormattedText from 'app/components/formatted_text';
import KeyboardLayout from 'app/components/layout/keyboard_layout';
import Loading from 'app/components/loading';
import TextInputWithLocalizedPlaceholder from 'app/components/text_input_with_localized_placeholder';
import {GlobalStyles} from 'app/styles';
import {isValidUrl, stripTrailingSlashes} from 'app/utils/url';

import logo from 'assets/images/logo.png';

import {RequestStatus} from 'mattermost-redux/constants';
import Client from 'mattermost-redux/client';

export default class SelectServer extends PureComponent {
    static propTypes = {
        transition: PropTypes.bool.isRequired,
        serverUrl: PropTypes.string.isRequired,
        pingRequest: PropTypes.object.isRequired,
        configRequest: PropTypes.object.isRequired,
        licenseRequest: PropTypes.object.isRequired,
        actions: PropTypes.shape({
            getPing: PropTypes.func.isRequired,
            resetPing: PropTypes.func.isRequired,
            handleLoginOptions: PropTypes.func.isRequired,
            handleServerUrlChanged: PropTypes.func.isRequired,
            unrenderDrawer: PropTypes.func.isRequired
        }).isRequired
    };

    constructor(props) {
        super(props);

        this.state = {
            error: null
        };
    }

    componentDidMount() {
        this.props.actions.unrenderDrawer();
        if (Platform.OS === 'android') {
            Keyboard.addListener('keyboardDidHide', this.handleAndroidKeyboard);
        }
    }

    componentWillReceiveProps(nextProps) {
        if (!this.props.transition && nextProps.transition) {
            this.props.actions.resetPing().then(() => {
                this.props.actions.handleLoginOptions();
            });
        }
    }

    componentWillUnmount() {
        if (Platform.OS === 'android') {
            Keyboard.removeListener('keyboardDidHide', this.handleAndroidKeyboard);
        }
    }

    handleAndroidKeyboard = () => {
        this.blur();
    };

    onClick = async () => {
        const url = this.props.serverUrl;
        let error = null;

        Keyboard.dismiss();

        if (isValidUrl(url)) {
            Client.setUrl(stripTrailingSlashes(url));
            await this.props.actions.getPing();
        } else {
            error = {
                intl: {
                    id: 'mobile.server_url.invalid_format',
                    defaultMessage: 'URL must start with http:// or https://'
                }
            };
        }

        this.setState({error});
    };

    inputRef = (ref) => {
        this.textInput = ref;
    };

    blur = () => {
        this.textInput.refs.wrappedInstance.blur();
    };

    render() {
        const {serverUrl, pingRequest, configRequest, licenseRequest} = this.props;
        const isLoading = pingRequest.status === RequestStatus.STARTED ||
            configRequest.status === RequestStatus.STARTED ||
            licenseRequest.status === RequestStatus.STARTED;

        if (isLoading) {
            return <Loading/>;
        }

        const error = pingRequest.error || configRequest.error || licenseRequest.error;

        return (
            <KeyboardLayout
                behavior='padding'
                style={{flex: 1}}
                keyboardVerticalOffset={0}
            >
                <StatusBar barStyle='light-content'/>
                <TouchableWithoutFeedback onPress={this.blur}>
                    <View style={[GlobalStyles.container, GlobalStyles.signupContainer]}>
                        <Image
                            source={logo}
                        />
                        <View>
                            <FormattedText
                                style={[GlobalStyles.header, GlobalStyles.label]}
                                id='mobile.components.select_server_view.enterServerUrl'
                                defaultMessage='Enter Server URL'
                            />
                        </View>
                        <TextInputWithLocalizedPlaceholder
                            ref={this.inputRef}
                            value={serverUrl}
                            onChangeText={this.props.actions.handleServerUrlChanged}
                            onSubmitEditing={this.onClick}
                            style={GlobalStyles.inputBox}
                            autoCapitalize='none'
                            autoCorrect={false}
                            keyboardType='url'
                            placeholder={{id: 'mobile.components.select_server_view.siteUrlPlaceholder', defaultMessage: 'https://mattermost.example.com'}}
                            returnKeyType='go'
                            underlineColorAndroid='transparent'
                        />
                        <Button
                            onPress={this.onClick}
                            containerStyle={GlobalStyles.signupButton}
                        >
                            <FormattedText
                                style={GlobalStyles.signupButtonText}
                                id='mobile.components.select_server_view.proceed'
                                defaultMessage='Proceed'
                            />
                        </Button>
                        <ErrorText error={this.state.error || error}/>
                    </View>
                </TouchableWithoutFeedback>
            </KeyboardLayout>
        );
    }
}
<commit_msg>fix android crash on server url (#400)<commit_after>// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

import React, {PropTypes, PureComponent} from 'react';
import {
    Image,
    Keyboard,
    Platform,
    StatusBar,
    TouchableWithoutFeedback,
    View
} from 'react-native';

import Button from 'react-native-button';
import ErrorText from 'app/components/error_text';
import FormattedText from 'app/components/formatted_text';
import KeyboardLayout from 'app/components/layout/keyboard_layout';
import Loading from 'app/components/loading';
import TextInputWithLocalizedPlaceholder from 'app/components/text_input_with_localized_placeholder';
import {GlobalStyles} from 'app/styles';
import {isValidUrl, stripTrailingSlashes} from 'app/utils/url';

import logo from 'assets/images/logo.png';

import {RequestStatus} from 'mattermost-redux/constants';
import Client from 'mattermost-redux/client';

export default class SelectServer extends PureComponent {
    static propTypes = {
        transition: PropTypes.bool.isRequired,
        serverUrl: PropTypes.string.isRequired,
        pingRequest: PropTypes.object.isRequired,
        configRequest: PropTypes.object.isRequired,
        licenseRequest: PropTypes.object.isRequired,
        actions: PropTypes.shape({
            getPing: PropTypes.func.isRequired,
            resetPing: PropTypes.func.isRequired,
            handleLoginOptions: PropTypes.func.isRequired,
            handleServerUrlChanged: PropTypes.func.isRequired,
            unrenderDrawer: PropTypes.func.isRequired
        }).isRequired
    };

    constructor(props) {
        super(props);

        this.state = {
            error: null
        };
    }

    componentDidMount() {
        this.props.actions.unrenderDrawer();
        if (Platform.OS === 'android') {
            Keyboard.addListener('keyboardDidHide', this.handleAndroidKeyboard);
        }
    }

    componentWillReceiveProps(nextProps) {
        if (!this.props.transition && nextProps.transition) {
            this.props.actions.resetPing().then(() => {
                this.props.actions.handleLoginOptions();
            });
        }
    }

    componentWillUnmount() {
        if (Platform.OS === 'android') {
            Keyboard.removeListener('keyboardDidHide', this.handleAndroidKeyboard);
        }
    }

    handleAndroidKeyboard = () => {
        this.blur();
    };

    onClick = async () => {
        const url = this.props.serverUrl;
        let error = null;

        Keyboard.dismiss();

        if (isValidUrl(url)) {
            Client.setUrl(stripTrailingSlashes(url));
            await this.props.actions.getPing();
        } else {
            error = {
                intl: {
                    id: 'mobile.server_url.invalid_format',
                    defaultMessage: 'URL must start with http:// or https://'
                }
            };
        }

        this.setState({error});
    };

    inputRef = (ref) => {
        this.textInput = ref;
    };

    blur = () => {
        if (this.textInput) {
            this.textInput.refs.wrappedInstance.blur();
        }
    };

    render() {
        const {serverUrl, pingRequest, configRequest, licenseRequest} = this.props;
        const isLoading = pingRequest.status === RequestStatus.STARTED ||
            configRequest.status === RequestStatus.STARTED ||
            licenseRequest.status === RequestStatus.STARTED;

        if (isLoading) {
            return <Loading/>;
        }

        const error = pingRequest.error || configRequest.error || licenseRequest.error;

        return (
            <KeyboardLayout
                behavior='padding'
                style={{flex: 1}}
                keyboardVerticalOffset={0}
            >
                <StatusBar barStyle='light-content'/>
                <TouchableWithoutFeedback onPress={this.blur}>
                    <View style={[GlobalStyles.container, GlobalStyles.signupContainer]}>
                        <Image
                            source={logo}
                        />
                        <View>
                            <FormattedText
                                style={[GlobalStyles.header, GlobalStyles.label]}
                                id='mobile.components.select_server_view.enterServerUrl'
                                defaultMessage='Enter Server URL'
                            />
                        </View>
                        <TextInputWithLocalizedPlaceholder
                            ref={this.inputRef}
                            value={serverUrl}
                            onChangeText={this.props.actions.handleServerUrlChanged}
                            onSubmitEditing={this.onClick}
                            style={GlobalStyles.inputBox}
                            autoCapitalize='none'
                            autoCorrect={false}
                            keyboardType='url'
                            placeholder={{id: 'mobile.components.select_server_view.siteUrlPlaceholder', defaultMessage: 'https://mattermost.example.com'}}
                            returnKeyType='go'
                            underlineColorAndroid='transparent'
                        />
                        <Button
                            onPress={this.onClick}
                            containerStyle={GlobalStyles.signupButton}
                        >
                            <FormattedText
                                style={GlobalStyles.signupButtonText}
                                id='mobile.components.select_server_view.proceed'
                                defaultMessage='Proceed'
                            />
                        </Button>
                        <ErrorText error={this.state.error || error}/>
                    </View>
                </TouchableWithoutFeedback>
            </KeyboardLayout>
        );
    }
}
<|endoftext|>


<commit_before>var BaseRouter, ServerRouter, ExpressRouter, sanitize, _;

_ = require('underscore');
BaseRouter = require('../shared/base/router');
ExpressRouter = require('express').Router;
sanitize = require('validator').sanitize;

module.exports = ServerRouter;

function ServerRouter() {
  this._expressRouter = new ExpressRouter();
  this.routesByPath = {};
  this.on('route:add', this.addExpressRoute, this);

  BaseRouter.apply(this, arguments);
}

/**
 * Set up inheritance.
 */
ServerRouter.prototype = Object.create(BaseRouter.prototype);
ServerRouter.prototype.constructor = ServerRouter;

ServerRouter.prototype.escapeParams = function(params) {
  var escaped = {};
  _.each(params, function(value, key) {
    escaped[sanitize(key).xss()] = sanitize(value).xss();
  });
  return escaped;
};

ServerRouter.prototype.getParams = function(req) {
  var params = _.clone(req.query || {});

  if (req.route.regexp)
  {
    params = req.route.params;
  }
  else
  {
    req.route.keys.forEach(function(routeKey) {
      params[routeKey.name] = req.params[routeKey.name];
    });
  }

  params = this.escapeParams(params);
  return params;
};

/**
 * This is the method that renders the request. It returns an Express
 * middleware function.
 */
ServerRouter.prototype.getHandler = function(action, pattern, route) {
  var router = this;

  return function(req, res, next) {
    var app, context, params, redirect;

    params = router.getParams(req);
    redirect = router.getRedirect(route, params);
    /**
     * If `redirect` is present, then do a redirect and return.
     */
    if (redirect != null) {
      res.redirect(route.status || 301, redirect);
      return;
    }

    app = req.rendrApp;
    context = {
      currentRoute: route,
      app: app,
      redirectTo: function(uri, options) {
        if (options !== undefined && options.status) {
          res.redirect(options.status, uri);
        }
        else {
          res.redirect(uri);
        }
      }
    };

    action.call(context, params, function(err, viewPath, locals) {
      if (err) return next(err);

      var defaults = router.defaultHandlerParams(viewPath, locals, route);
      viewPath = defaults[0], locals = defaults[1];

      var viewData = {
        locals: locals || {},
        app: app,
        req: req
      };

      res.render(viewPath, viewData, function(err, html) {
        if (err) return next(err);
        res.set(router.getHeadersForRoute(route));
        res.type('html').end(html);
      });
    });
  };
};

ServerRouter.prototype.addExpressRoute = function(routeObj) {
  var path = routeObj[0];

  this.routesByPath[path] = routeObj;
  this._expressRouter.route('get', path, []);
};

ServerRouter.prototype.getHeadersForRoute = function(definition) {
  var headers = {};
  if (definition.maxAge != null) {
    headers['Cache-Control'] = "public, max-age=" + definition.maxAge;
  }
  return headers;
};

/**
 * Return the route definition based on a URL, according to the routes file.
 * This should match the way Express matches routes on the server, and our
 * ClientRouter matches routes on the client.
 */
ServerRouter.prototype.match = function(pathToMatch) {
  var matchedRoute;

  if (~pathToMatch.indexOf('://')) {
    throw new Error('Cannot match full URL: "' + pathToMatch + '". Use pathname instead.');
  }

  // Ensure leading slash
  if (pathToMatch[0] !== '/') {
    pathToMatch = '/' + pathToMatch;
  }

  matchedRoute = this._expressRouter.match('get', pathToMatch);
  return matchedRoute ? this.routesByPath[matchedRoute.path] : null;
};
<commit_msg>style and extend<commit_after>var BaseRouter, ServerRouter, ExpressRouter, sanitize, _;

_ = require('underscore');
BaseRouter = require('../shared/base/router');
ExpressRouter = require('express').Router;
sanitize = require('validator').sanitize;

module.exports = ServerRouter;

function ServerRouter() {
  this._expressRouter = new ExpressRouter();
  this.routesByPath = {};
  this.on('route:add', this.addExpressRoute, this);

  BaseRouter.apply(this, arguments);
}

/**
 * Set up inheritance.
 */
ServerRouter.prototype = Object.create(BaseRouter.prototype);
ServerRouter.prototype.constructor = ServerRouter;

ServerRouter.prototype.escapeParams = function(params) {
  var escaped = {};
  _.each(params, function(value, key) {
    escaped[sanitize(key).xss()] = sanitize(value).xss();
  });
  return escaped;
};

ServerRouter.prototype.getParams = function(req) {
  var params = _.clone(req.query || {});

  if (req.route.regexp) {
    _.extend(params, req.route.params);
  } else {
    req.route.keys.forEach(function(routeKey) {
      params[routeKey.name] = req.params[routeKey.name];
    });
  }

  params = this.escapeParams(params);
  return params;
};

/**
 * This is the method that renders the request. It returns an Express
 * middleware function.
 */
ServerRouter.prototype.getHandler = function(action, pattern, route) {
  var router = this;

  return function(req, res, next) {
    var app, context, params, redirect;

    params = router.getParams(req);
    redirect = router.getRedirect(route, params);
    /**
     * If `redirect` is present, then do a redirect and return.
     */
    if (redirect != null) {
      res.redirect(route.status || 301, redirect);
      return;
    }

    app = req.rendrApp;
    context = {
      currentRoute: route,
      app: app,
      redirectTo: function(uri, options) {
        if (options !== undefined && options.status) {
          res.redirect(options.status, uri);
        }
        else {
          res.redirect(uri);
        }
      }
    };

    action.call(context, params, function(err, viewPath, locals) {
      if (err) return next(err);

      var defaults = router.defaultHandlerParams(viewPath, locals, route);
      viewPath = defaults[0], locals = defaults[1];

      var viewData = {
        locals: locals || {},
        app: app,
        req: req
      };

      res.render(viewPath, viewData, function(err, html) {
        if (err) return next(err);
        res.set(router.getHeadersForRoute(route));
        res.type('html').end(html);
      });
    });
  };
};

ServerRouter.prototype.addExpressRoute = function(routeObj) {
  var path = routeObj[0];

  this.routesByPath[path] = routeObj;
  this._expressRouter.route('get', path, []);
};

ServerRouter.prototype.getHeadersForRoute = function(definition) {
  var headers = {};
  if (definition.maxAge != null) {
    headers['Cache-Control'] = "public, max-age=" + definition.maxAge;
  }
  return headers;
};

/**
 * Return the route definition based on a URL, according to the routes file.
 * This should match the way Express matches routes on the server, and our
 * ClientRouter matches routes on the client.
 */
ServerRouter.prototype.match = function(pathToMatch) {
  var matchedRoute;

  if (~pathToMatch.indexOf('://')) {
    throw new Error('Cannot match full URL: "' + pathToMatch + '". Use pathname instead.');
  }

  // Ensure leading slash
  if (pathToMatch[0] !== '/') {
    pathToMatch = '/' + pathToMatch;
  }

  matchedRoute = this._expressRouter.match('get', pathToMatch);
  return matchedRoute ? this.routesByPath[matchedRoute.path] : null;
};
<|endoftext|>


<commit_before>define(['backbone', 'backbone.pageable.collection', 'config', 'models/marker'],
  function(Backbone, PageableCollection, Config, ResultModel) {

    var DelvingResultModel = ResultModel.extend({
      parse: function(fields) {

        var f = {
          title: fields['dc:title'],
          description: fields['dc:description']
          //latitude: fields['dcterms:spactial:']delving_locationLat,
          //longitude: fields.delving_locationLong
        };

        // Image
        var img;
        if (fields['dc:type'] == "Foto" && _.isArray(fields['edm:object'])) {
          img = fields['edm:object'][0];
        }
        if (img) f.image = img;

        return f;
      }
    });

    return PageableCollection.extend({
      hasPrevious: function() {
        return this.hasPreviousPage();
      },
      hasNext: function() {
        return this.hasNextPage();
      },
      model: DelvingResultModel,
      queryParams: {
        currentPage: null,
        pageSize: null,
        totalPages: null,
        totalRecords: null,
//        maxRecords: function() {
//          return this.state.maxRecords;
//        },
        startRecord: function() {
          return (this.state.currentPage -1) * this.state.pageSize +1;
        },
        query: function() {
          var query = [this.state.terms].concat(this.state.facets);
          return query.join(' AND ');
        }
      },
      parseRecords: function(resp) {
        return resp.result.items;
      },
      parseState: function(resp) {
        return {
          facetConfig: this.getFacetState(resp),
          totalRecords: resp.result.total
        }
      },
      getFacetState: function(resp) {
        var facetConfig = [];

        _.each(resp.result.facets, function(options, name) {
          facetConfig.push({
            name: name,
            options: options
          });
        });

        return facetConfig;
      },
      getFacetConfig: function() {
        return new Backbone.Collection(this.state.facetConfig);
      },
      state: {
        d: 100,
        firstPage: 1,
        pageSize: 10,
        maxRecords: 10,
        terms: "*",
        facets: []
      },
      url: Config.zoek_en_vind.uri + '/search'
    });

  });<commit_msg>Refactor ZEV collection class for readability.<commit_after>define(['backbone', 'backbone.pageable.collection', 'config', 'models/marker'],
  function(Backbone, PageableCollection, Config, ResultModel) {

    var DelvingResultModel = ResultModel.extend({
      parse: function(fields) {

        var f = {
          title: fields['dc:title'],
          description: fields['dc:description']
          //latitude: fields['dcterms:spactial:']delving_locationLat,
          //longitude: fields.delving_locationLong
        };

        // Image
        var img;
        if (fields['dc:type'] == "Foto" && _.isArray(fields['edm:object'])) {
          img = fields['edm:object'][0];
        }
        if (img) f.image = img;

        return f;
      }
    });

    return PageableCollection.extend({

      model: DelvingResultModel,
      queryParams: {
        currentPage: null,
        pageSize: null,
        totalPages: null,
        totalRecords: null,
        maximumRecords: function() {
          return this.state.maxRecords;
        },
        startRecord: function() {
          return (this.state.currentPage -1) * this.state.pageSize +1;
        },
        query: function() {
          var query = [this.state.terms].concat(this.state.facets);
          return query.join(' AND ');
        }
      },
      state: {
        d: 100,
        firstPage: 1,
        pageSize: 10,
        maxRecords: 10,
        terms: "*",
        facets: []
      },
      url: Config.zoek_en_vind.uri + '/search',

      getFacetConfig: function() {
        return new Backbone.Collection(this.state.facetConfig);
      },
      getFacetState: function(resp) {
        var facetConfig = [];

        _.each(resp.result.facets, function(options, name) {
          facetConfig.push({
            name: name,
            options: options
          });
        });

        return facetConfig;
      },
      hasNext: function() {
        return this.hasNextPage();
      },
      hasPrevious: function() {
        return this.hasPreviousPage();
      },
      parseRecords: function(resp) {
        return resp.result.items;
      },
      parseState: function(resp) {
        return {
          facetConfig: this.getFacetState(resp),
          totalRecords: resp.result.total
        }
      }

    });

  });<|endoftext|>


<commit_before>var mongo = require('mongodb');
var _ = require("underscore");

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure,
    BANDS = 'bands',
    MEMBERS = 'members',
    ALBUMS = 'albums';

var bandApp = {};

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('banddb', server);

db.open(function(err, db) {
  if (!err) {
    console.log("Connected to 'banddb' database");
    db.collection(BANDS, {strict: true}, function(err, collection) {
      if (err) {
        console.log("The collection does not exist, creating a new one");
        populateDB();
      }
    });
  }
});

bandApp.findAll = function(collectionName, req, res) {
  console.log('Find all', collectionName);
  db.collection(collectionName, function(err, collection) {
    collection.find().toArray(function(err, items) {
      res.send(items);
    });
  });
};

bandApp.findById = function(collectionName, req, res) {
  var id = req.params.id;
  console.log('Find by id', collectionName, id);
  db.collection(collectionName, function(err, collection) {
    collection.findOne({'_id': new BSON.ObjectID(id)}, function(err, item) {
      res.send(item);
    });
  });
};

bandApp.createItem = function(collectionName, req, res) {
  var item = req.body;
  console.log('Adding item', collectionName, JSON.stringify(item));
  db.collection(collectionName, function(err, collection) {
    collection.insert(item, {safe: true}, function(err, result) {
      if (err) {
        res.send({'error': 'An error has occurred'});
      } else {
        console.log('Success: ' + JSON.stringify(result[0]));
        res.send(result[0]);
      }
    });
  });
};

bandApp.updateItem = function(collectionName, req, res) {
  var id = req.params.id;
  var item = req.body;
  console.log('Updating item', collectionName, id);
  console.log(JSON.stringify(item));
  db.collection(collectionName, function(err, collection) {
    collection.update({'_id': new BSON.ObjectID(id)}, item, {safe: true}, function(err, result) {
      if (err) {
        console.log('Error updating item: ' + err);
        res.send({'error': 'An error has occurred'});
      } else {
        console.log('' + result + ' document(s) updated');
        res.send(item);
      }
    });
  });
};

bandApp.deleteItem = function(collectionName, req, res) {
  var id = req.params.id;
  console.log('Deleting item', collectionName, id);
  db.collection(collectionName, function(err, collection) {
    collection.remove({'_id': new BSON.ObjectID(id)}, {safe: true}, function(err, result) {
      if (err) {
        res.send({'error': 'An error has occurred - ' + err});
      } else {
        console.log('' + result + ' document(s) deleted');
        res.send(req.body);
      }
    });
  });
};

// Find all.
exports.findAllBands = _.partial(bandApp.findAll, BANDS);
exports.findAllAlbums = _.partial(bandApp.findAll, ALBUMS);
exports.findAllMembers = _.partial(bandApp.findAll, MEMBERS);

// Find by id.
exports.findBandById = _.partial(bandApp.findById, BANDS);
exports.findAlbumById = _.partial(bandApp.findById, ALBUMS);
exports.findMemberById = _.partial(bandApp.findById, MEMBERS);

// Create
exports.createBand = _.partial(bandApp.createItem, BANDS);
exports.createAlbum = _.partial(bandApp.createItem, ALBUMS);
exports.createMember = _.partial(bandApp.createItem, MEMBERS);

// Update
exports.updateBand = _.partial(bandApp.updateItem, BANDS);
exports.updateAlbum = _.partial(bandApp.updateItem, ALBUMS);
exports.updateMember = _.partial(bandApp.updateItem, MEMBERS);

// Delete
exports.deleteBand = _.partial(bandApp.deleteItem, BANDS);
exports.deleteAlbum = _.partial(bandApp.deleteItem, ALBUMS);
exports.deleteMember = _.partial(bandApp.deleteItem, MEMBERS);

var populateDB = function() {
  var bands = [
    {
      name: 'Wu-Tang Clan',
      albums: [],
      members: []
    }
  ];

  var members = [
    {
      name: 'Method Man'
    },
    {
      name: 'Ghostface Killah'
    }
  ];

  var albums = [
      {
        name: 'Synchronicity'
      }
  ];

  db.collection(BANDS, function(err, collection) {
    collection.insert(bands, {safe:true}, function(err, result) {});
  });
  db.collection(ALBUMS, function(err, collection) {
    collection.insert(albums, {safe:true}, function(err, result) {});
  });
  db.collection(MEMBERS, function(err, collection) {
    collection.insert(members, {safe:true}, function(err, result) {});
  });
};
<commit_msg>Add timeout to make the server slow<commit_after>var mongo = require('mongodb');
var _ = require("underscore");

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure,
    BANDS = 'bands',
    MEMBERS = 'members',
    ALBUMS = 'albums';

var bandApp = {};

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('banddb', server);

db.open(function(err, db) {
  if (!err) {
    console.log("Connected to 'banddb' database");
    db.collection(BANDS, {strict: true}, function(err, collection) {
      if (err) {
        console.log("The collection does not exist, creating a new one");
        populateDB();
      }
    });
  }
});

bandApp.findAll = function(collectionName, req, res) {
  console.log('Find all', collectionName);
  setTimeout(function() {
    db.collection(collectionName, function(err, collection) {
      collection.find().toArray(function(err, items) {
        res.send(items);
      });
    });
  }, 2000);
};

bandApp.findById = function(collectionName, req, res) {
  var id = req.params.id;
  console.log('Find by id', collectionName, id);
  setTimeout(function() {
    db.collection(collectionName, function(err, collection) {
      collection.findOne({'_id': new BSON.ObjectID(id)}, function(err, item) {
        res.send(item);
      });
    });
  }, 1000);
};

bandApp.createItem = function(collectionName, req, res) {
  var item = req.body;
  console.log('Adding item', collectionName, JSON.stringify(item));
  db.collection(collectionName, function(err, collection) {
    collection.insert(item, {safe: true}, function(err, result) {
      if (err) {
        res.send({'error': 'An error has occurred'});
      } else {
        console.log('Success: ' + JSON.stringify(result[0]));
        res.send(result[0]);
      }
    });
  });
};

bandApp.updateItem = function(collectionName, req, res) {
  var id = req.params.id;
  var item = req.body;
  console.log('Updating item', collectionName, id);
  console.log(JSON.stringify(item));
  db.collection(collectionName, function(err, collection) {
    collection.update({'_id': new BSON.ObjectID(id)}, item, {safe: true}, function(err, result) {
      if (err) {
        console.log('Error updating item: ' + err);
        res.send({'error': 'An error has occurred'});
      } else {
        console.log('' + result + ' document(s) updated');
        res.send(item);
      }
    });
  });
};

bandApp.deleteItem = function(collectionName, req, res) {
  var id = req.params.id;
  console.log('Deleting item', collectionName, id);
  db.collection(collectionName, function(err, collection) {
    collection.remove({'_id': new BSON.ObjectID(id)}, {safe: true}, function(err, result) {
      if (err) {
        res.send({'error': 'An error has occurred - ' + err});
      } else {
        console.log('' + result + ' document(s) deleted');
        res.send(req.body);
      }
    });
  });
};

// Find all.
exports.findAllBands = _.partial(bandApp.findAll, BANDS);
exports.findAllAlbums = _.partial(bandApp.findAll, ALBUMS);
exports.findAllMembers = _.partial(bandApp.findAll, MEMBERS);

// Find by id.
exports.findBandById = _.partial(bandApp.findById, BANDS);
exports.findAlbumById = _.partial(bandApp.findById, ALBUMS);
exports.findMemberById = _.partial(bandApp.findById, MEMBERS);

// Create
exports.createBand = _.partial(bandApp.createItem, BANDS);
exports.createAlbum = _.partial(bandApp.createItem, ALBUMS);
exports.createMember = _.partial(bandApp.createItem, MEMBERS);

// Update
exports.updateBand = _.partial(bandApp.updateItem, BANDS);
exports.updateAlbum = _.partial(bandApp.updateItem, ALBUMS);
exports.updateMember = _.partial(bandApp.updateItem, MEMBERS);

// Delete
exports.deleteBand = _.partial(bandApp.deleteItem, BANDS);
exports.deleteAlbum = _.partial(bandApp.deleteItem, ALBUMS);
exports.deleteMember = _.partial(bandApp.deleteItem, MEMBERS);

var populateDB = function() {
  var bands = [
    {
      name: 'Wu-Tang Clan',
      albums: [],
      members: []
    }
  ];

  var members = [
    {
      name: 'Method Man'
    },
    {
      name: 'Ghostface Killah'
    }
  ];

  var albums = [
      {
        name: 'Synchronicity'
      }
  ];

  db.collection(BANDS, function(err, collection) {
    collection.insert(bands, {safe:true}, function(err, result) {});
  });
  db.collection(ALBUMS, function(err, collection) {
    collection.insert(albums, {safe:true}, function(err, result) {});
  });
  db.collection(MEMBERS, function(err, collection) {
    collection.insert(members, {safe:true}, function(err, result) {});
  });
};
<|endoftext|>


<commit_before>/**
 * Main application routes
 */

'use strict';

var errors = require('./components/errors');

module.exports = function(app) {

  // Insert routes below
  app.use('/api/things', require('./api/thing'));
  app.use('/api/players', require('./api/player'));
  app.use('/api/teams', require('./api/team'));
  app.use('/api/maps', require('./api/map'));

  // All undefined asset or api routes should return a 404
  // app.route('/:url(api|auth|components|app|bower_components|assets)/*')
  //  .get(errors[404]);

  // All other routes should redirect to the index.html
  app.route('/*').get(function(req, res) {
      res.sendFile('index.html', {root: __dirname + '/../' + app.get('appPath')});
    });
};
<commit_msg>fixing refresh issue in prod env<commit_after>/**
 * Main application routes
 */

'use strict';

var errors = require('./components/errors');

module.exports = function (app) {

  // Insert routes below
  app.use('/api/things', require('./api/thing'));
  app.use('/api/players', require('./api/player'));
  app.use('/api/teams', require('./api/team'));
  app.use('/api/maps', require('./api/map'));

  // All undefined asset or api routes should return a 404
  // app.route('/:url(api|auth|components|app|bower_components|assets)/*')
  //  .get(errors[404]);

  // All other routes should redirect to the index.html
  app.route('/*').get(function (req, res) {
    res.sendfile(app.get('appPath') + '/index.html');
  });
};
<|endoftext|>


<commit_before>
import React from 'react';
import {
  PDFViewer
} from '../../components';

const ResumePDF = () => (
  <PDFViewer
    url="https://s3.amazonaws.com/accredible-profile-uploads/udacity/resumes/1468378609166"
  />
);

export default ResumePDF;
<commit_msg>Feat: add new resume pdf link<commit_after>
import React from 'react';
import {
  PDFViewer
} from '../../components';

const ResumePDF = () => (
  <PDFViewer
    url="https://s3.amazonaws.com/accredible-profile-uploads/udacity/resumes/1468948504753"
  />
);

export default ResumePDF;
<|endoftext|>