<commit_before>// ANGULAR

var dateMapApp = angular.module('dateMapApp', []).value('$anchorScroll', angular.noop);

dateMapApp.config(function($routeProvider) {
    $routeProvider.
        when('/', {
            action: "yesterday"
        }).
        when('/:date/', {
            action: "date"
        }).
        when('/:date/:serviceSlug/', {
            action: "date.service"
        }).
        otherwise({
            redirectTo: '/'
        });
});

dateMapApp.factory('Data', function () {
    var data = {
    };

    if (!window.chicagoMap) {
        window.chicagoMap = L.map('map',{scrollWheelZoom: false}).setView([41.83, -87.81], 11);

        L.tileLayer('http://{s}.tile.cloudmade.com/{key}/{styleId}/256/{z}/{x}/{y}.png', window.mapOptions)
            .addTo(window.chicagoMap);
        window.chicagoMap.zoomControl.setPosition('bottomright');
    }

    data.setDate = function(date) {
        data.date = date.format(dateFormat);
        data.dateFormatted = date.format('MMM D, YYYY');
        data.pageTitle = data.dateFormatted + ' | Chicago Works For You';
        data.prevDay = moment(date).subtract('day',1);
        data.nextDay = moment(date).add('day',1);
        data.prevDayFormatted = data.prevDay.format('MMM D');
        data.nextDayFormatted = data.nextDay.format('MMM D');
        data.isLatest = data.nextDay.isAfter(window.yesterday);
    };

    return data;
});

dateMapApp.controller("headCtrl", function ($scope, Data) {
    $scope.data = Data;
});

dateMapApp.controller("dateCtrl", function ($scope, Data, $http, $location, $route, $routeParams, $timeout) {
    var wardColors = [
        '#182A35',
        '#244153',
        '#315971',
        '#3C7090',
        '#4888AF',
        '#629CBF'
    ].reverse();

    var urlSuffix = function() {
        return $routeParams && $routeParams.serviceSlug ? Data.serviceObj.slug + '/' : '';
    };

    $scope.goToPrevDay = function() {
        if (Data.prevDay.isBefore(window.earliestDate)) {
            return false;
        }
        $location.path(Data.prevDay.format(dateFormat) + '/' + urlSuffix());
    };

    $scope.goToNextDay = function() {
        if (Data.isLatest) {
            return false;
        }
        $location.path(Data.nextDay.format(dateFormat) + '/' + urlSuffix());
    };

    $scope.serviceClass = function(service) {
        var classes = [];
        if (service.Slug == Data.serviceObj.slug) {
            classes.push('active');
            if (service.Slug == $routeParams.serviceSlug) {
                classes.push('in-url');
            }
        }
        if (service.Slug == Data.maxService.Slug) {
            classes.push('max');
        }
        if (service.Count > service.Average) {
            classes.push('up');
        } else if (service.Count < service.Average) {
            classes.push('down');
        }
        return classes.join(" ");
    };

    var renderMap = function() {
        var serviceObj = _.find(Data.serviceList, function(obj) {
            return obj.Slug == Data.serviceObj.slug;
        });

        var allCounts = _.toArray(serviceObj.Wards);
        var maxCount = _.max(allCounts);
        var hasRanges = maxCount >= wardColors.length;

        var grades = _.range(0, Math.min(wardColors.length, maxCount + 1));
        if (hasRanges) {
            grades = _.map(grades, function (grade) {
                return Math.round(grade * maxCount / (grades.length - 1));
            });
        }

        var allColors = _.map(allCounts, function(count) {
            // Shift the count to be between grades, find the index (which'll never be 0), then move it back one slot.
            var pos = _.sortedIndex(grades, count + 0.1) - 1;
            return wardColors[pos];
        });

        if (window.allWards) {
            window.allWards.clearLayers();
        } else {
            window.allWards = L.layerGroup();
        }

        var wardClick = function(e) {
            document.location = 'ward/' + e.target.options.id + '/#' + $location.path();
        };

        $timeout(function() {
            for (var path in wardPaths) {
                var wardNum = parseInt(path,10) + 1;
                var wardCount = serviceObj.Wards[wardNum];
                var poly = L.polygon(
                    wardPaths[path],
                    {
                        id: wardNum,
                        opacity: 1,
                        weight: 1,
                        dashArray: '3',
                        color: 'white',
                        fillOpacity: 0.8,
                        fillColor: allColors[wardNum-1]
                    }
                )
                .bindLabel('
Ward ' + wardNum + '
' + wardCount + ' request' + window.pluralize(wardCount))
                .on('click', wardClick);
                window.allWards.addLayer(poly);
            }

            if (window.legend) {
                window.legend.removeFrom(window.chicagoMap);
            }
            window.legend = L.control({position: 'topright'});

            window.legend.onAdd = function(map) {
                var div = L.DomUtil.create('div', 'legend');
                var labels = _.map(grades, function (grade, i) {
                    return ' ' + grade + (hasRanges && grade < _.last(grades) ? '+': '') + " request" + (grade == 1 && !hasRanges ? '' : 's');
                });

                div.innerHTML =
                    '
' + Data.serviceObj.name + '
' +
                    labels.join('
');
                return div;
            };

            window.allWards.addTo(window.chicagoMap);
            legend.addTo(window.chicagoMap);
        });
    };

    var changeDate = function() {
        var countsURL = window.apiDomain + 'requests/counts_by_day.json?day=' + Data.date + '&callback=JSON_CALLBACK';

        $http.jsonp(countsURL).
            success(function(response, status, headers, config) {
                Data.reponse = response;

                var serviceCollection = _.map(_.pairs(response), function(pair) {
                    service = _.find(serviceTypesJSON, function(obj) { return obj.code == pair[0]; });
                    return _.extend(pair[1], {
                        "Code": pair[0],
                        "Slug": service.slug,
                        "Name": service.name,
                        "AvgRounded": Math.round(pair[1].Average * 10) / 10,
                        "Percent": Math.min(Math.round((pair[1].Count - pair[1].Average) * 100 / pair[1].Average), 100)
                    });
                });

                Data.serviceList = _.sortBy(serviceCollection, function(obj) {
                    return obj.Slug;
                });

                Data.maxService = _.max(Data.serviceList, function(obj) { return obj.Percent; });
                if (_.isEmpty(Data.serviceObj)) {
                    Data.serviceObj = lookupSlug(Data.maxService.Slug);
                }

                renderMap();
            }
        );
    };

    $scope.data = Data;

    $scope.$on(
        "$routeChangeSuccess",
        function ($e, $currentRoute, $previousRoute) {
            Data.setDate(parseDate($routeParams.date, window.yesterday, $location));
            Data.serviceObj = {};
            Data.action = $route.current.action;
            if ($currentRoute.pathParams.serviceSlug) {
                if (Data.action == 'date.service') {
                    Data.serviceObj = window.lookupSlug($currentRoute.pathParams.serviceSlug);
                }
            }
            Data.currURL = "#/" + Data.date + "/" + urlSuffix();

            if (!$previousRoute) {
                // First load
                changeDate();
            } else if ($currentRoute.pathParams.date != $previousRoute.pathParams.date) {
                // Going from one date to another
                changeDate();
            } else if (!$currentRoute.pathParams.serviceSlug) {
                // Going from defined date and service to the same date, but no service
                changeDate();
            } else if ($currentRoute.pathParams.serviceSlug != $previousRoute.pathParams.serviceSlug) {
                // Going from one service to another, with the same date
                renderMap();
            } else {
                changeDate();
            }
        }
    );
});
<commit_msg>Updated title definition logic to account for default state (i.e. on initial load).<commit_after>// ANGULAR

var dateMapApp = angular.module('dateMapApp', []).value('$anchorScroll', angular.noop);

dateMapApp.config(function($routeProvider) {
    $routeProvider.
        when('/', {
            action: "yesterday"
        }).
        when('/:date/', {
            action: "date"
        }).
        when('/:date/:serviceSlug/', {
            action: "date.service"
        }).
        otherwise({
            redirectTo: '/'
        });
});

dateMapApp.factory('Data', function () {
    var data = {
    };

    if (!window.chicagoMap) {
        window.chicagoMap = L.map('map',{scrollWheelZoom: false}).setView([41.83, -87.81], 11);

        L.tileLayer('http://{s}.tile.cloudmade.com/{key}/{styleId}/256/{z}/{x}/{y}.png', window.mapOptions)
            .addTo(window.chicagoMap);
        window.chicagoMap.zoomControl.setPosition('bottomright');
    }

    data.setDate = function(date) {
        data.date = date.format(dateFormat);
        data.dateFormatted = date.format('MMM D, YYYY');

        data.prevDay = moment(date).subtract('day',1);
        data.nextDay = moment(date).add('day',1);
        data.prevDayFormatted = data.prevDay.format('MMM D');
        data.nextDayFormatted = data.nextDay.format('MMM D');
        data.isLatest = data.nextDay.isAfter(window.yesterday);
    };

    return data;
});

dateMapApp.controller("headCtrl", function ($scope, Data) {
    $scope.data = Data;
});

dateMapApp.controller("dateCtrl", function ($scope, Data, $http, $location, $route, $routeParams, $timeout) {
    var wardColors = [
        '#182A35',
        '#244153',
        '#315971',
        '#3C7090',
        '#4888AF',
        '#629CBF'
    ].reverse();

    var urlSuffix = function() {
        return $routeParams && $routeParams.serviceSlug ? Data.serviceObj.slug + '/' : '';
    };

    $scope.goToPrevDay = function() {
        if (Data.prevDay.isBefore(window.earliestDate)) {
            return false;
        }
        $location.path(Data.prevDay.format(dateFormat) + '/' + urlSuffix());
    };

    $scope.goToNextDay = function() {
        if (Data.isLatest) {
            return false;
        }
        $location.path(Data.nextDay.format(dateFormat) + '/' + urlSuffix());
    };

    $scope.serviceClass = function(service) {
        var classes = [];
        if (service.Slug == Data.serviceObj.slug) {
            classes.push('active');
            if (service.Slug == $routeParams.serviceSlug) {
                classes.push('in-url');
            }
        }
        if (service.Slug == Data.maxService.Slug) {
            classes.push('max');
        }
        if (service.Count > service.Average) {
            classes.push('up');
        } else if (service.Count < service.Average) {
            classes.push('down');
        }
        return classes.join(" ");
    };

    var renderMap = function() {
        var serviceObj = _.find(Data.serviceList, function(obj) {
            return obj.Slug == Data.serviceObj.slug;
        });

        var allCounts = _.toArray(serviceObj.Wards);
        var maxCount = _.max(allCounts);
        var hasRanges = maxCount >= wardColors.length;

        var grades = _.range(0, Math.min(wardColors.length, maxCount + 1));
        if (hasRanges) {
            grades = _.map(grades, function (grade) {
                return Math.round(grade * maxCount / (grades.length - 1));
            });
        }

        var allColors = _.map(allCounts, function(count) {
            // Shift the count to be between grades, find the index (which'll never be 0), then move it back one slot.
            var pos = _.sortedIndex(grades, count + 0.1) - 1;
            return wardColors[pos];
        });

        if (window.allWards) {
            window.allWards.clearLayers();
        } else {
            window.allWards = L.layerGroup();
        }

        var wardClick = function(e) {
            document.location = 'ward/' + e.target.options.id + '/#' + $location.path();
        };

        $timeout(function() {
            for (var path in wardPaths) {
                var wardNum = parseInt(path,10) + 1;
                var wardCount = serviceObj.Wards[wardNum];
                var poly = L.polygon(
                    wardPaths[path],
                    {
                        id: wardNum,
                        opacity: 1,
                        weight: 1,
                        dashArray: '3',
                        color: 'white',
                        fillOpacity: 0.8,
                        fillColor: allColors[wardNum-1]
                    }
                )
                .bindLabel('
Ward ' + wardNum + '
' + wardCount + ' request' + window.pluralize(wardCount))
                .on('click', wardClick);
                window.allWards.addLayer(poly);
            }

            if (window.legend) {
                window.legend.removeFrom(window.chicagoMap);
            }
            window.legend = L.control({position: 'topright'});

            window.legend.onAdd = function(map) {
                var div = L.DomUtil.create('div', 'legend');
                var labels = _.map(grades, function (grade, i) {
                    return ' ' + grade + (hasRanges && grade < _.last(grades) ? '+': '') + " request" + (grade == 1 && !hasRanges ? '' : 's');
                });

                div.innerHTML =
                    '
' + Data.serviceObj.name + '
' +
                    labels.join('
');
                return div;
            };

            window.allWards.addTo(window.chicagoMap);
            legend.addTo(window.chicagoMap);
        });
    };

    var changeDate = function() {
        var countsURL = window.apiDomain + 'requests/counts_by_day.json?day=' + Data.date + '&callback=JSON_CALLBACK';

        $http.jsonp(countsURL).
            success(function(response, status, headers, config) {
                Data.reponse = response;

                var serviceCollection = _.map(_.pairs(response), function(pair) {
                    service = _.find(serviceTypesJSON, function(obj) { return obj.code == pair[0]; });
                    return _.extend(pair[1], {
                        "Code": pair[0],
                        "Slug": service.slug,
                        "Name": service.name,
                        "AvgRounded": Math.round(pair[1].Average * 10) / 10,
                        "Percent": Math.min(Math.round((pair[1].Count - pair[1].Average) * 100 / pair[1].Average), 100)
                    });
                });

                Data.serviceList = _.sortBy(serviceCollection, function(obj) {
                    return obj.Slug;
                });

                Data.maxService = _.max(Data.serviceList, function(obj) { return obj.Percent; });
                if (_.isEmpty(Data.serviceObj)) {
                    Data.serviceObj = lookupSlug(Data.maxService.Slug);
                }

                renderMap();
            }
        );
    };

    $scope.data = Data;

    $scope.$on(
        "$routeChangeSuccess",
        function ($e, $currentRoute, $previousRoute) {
            Data.setDate(parseDate($routeParams.date, window.yesterday, $location));
            Data.serviceObj = {};
            Data.action = $route.current.action;
            if ($currentRoute.pathParams.serviceSlug) {
                if (Data.action == 'date.service') {
                    Data.serviceObj = window.lookupSlug($currentRoute.pathParams.serviceSlug);
                }
            }
            Data.currURL = "#/" + Data.date + "/" + urlSuffix();

            var titleParts = [];
            if (_.isEmpty($currentRoute.pathParams)) {
                titleParts.push('Chicago Works For You');
                titleParts.push('The citywide dashboard with ward-by-ward views of service delivery in Chicago');
            } else {
                titleParts.push(Data.dateFormatted);
                if ($currentRoute.pathParams.serviceSlug) {
                    titleParts.push(Data.serviceObj.name);
                }
                titleParts.push('Chicago Works For You');
            }
            Data.pageTitle = titleParts.join(' | ');

            if (!$previousRoute) {
                // First load
                changeDate();
            } else if ($currentRoute.pathParams.date != $previousRoute.pathParams.date) {
                // Going from one date to another
                changeDate();
            } else if (!$currentRoute.pathParams.serviceSlug) {
                // Going from defined date and service to the same date, but no service
                changeDate();
            } else if ($currentRoute.pathParams.serviceSlug != $previousRoute.pathParams.serviceSlug) {
                // Going from one service to another, with the same date
                renderMap();
            } else {
                changeDate();
            }
        }
    );
});
<|endoftext|>


<commit_before>var m = require('mithril');
var Raven = require('raven-js');
var $osf = require('js/osfHelpers');
var ShareJSDoc = require('js/pages/ShareJSDocFile.js');
require('ace-noconflict');
require('ace-mode-markdown');
require('ace-ext-language_tools');
require('addons/wiki/static/ace-markdown-snippets.js');
var Markdown = require('pagedown-ace-converter');
Markdown.getSanitizingConverter = require('pagedown-ace-sanitizer').getSanitizingConverter;
require('imports?Markdown=pagedown-ace-converter!pagedown-ace-editor');

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

var FileEditor = {
    controller: function(contentUrl, shareWSUrl, editorMeta, observables) {
        var self = this;
        self.url = contentUrl;
        self.loaded = false;
        self.initialText = '';
        self.editor = undefined;
        self.editorMeta = editorMeta;
        self.changed = m.prop(false);

        self.observables = observables;

        $osf.throttle(self.observables.status, 4000, {leading: false});

        self.bindAce = function(element, isInitialized, context) {
            if (isInitialized) return;
            self.editor = ace.edit(element.id);
            self.editor.setValue(self.initialText);
            self.editor.on('change', self.onChanged);
            new ShareJSDoc(shareWSUrl, self.editorMeta, self.editor, self.observables);
        };

        self.reloadFile = function() {
            self.loaded = false;
            $.ajax({
                type: 'GET',
                url: self.url,
                beforeSend: $osf.setXHRAuthorization,
            }).done(function (parsed, status, response) {
                m.startComputation();
                self.loaded = true;
                self.initialText = response.responseText;
                if (self.editor) {
                    self.editor.setValue(self.initialText);
                }
                m.endComputation();
            }).fail(function (xhr, textStatus, error) {
                $osf.growl('Error','The file content could not be loaded.');
                Raven.captureMessage('Could not GET file contents.', {
                    url: self.url,
                    textStatus: textStatus,
                    error: error
                });
            });
        };

        //Really crappy hack, panel and m.component blackbox this module
        //so its not possible, in the alotted time, to bind a function here to
        //buttons ~2 levels up
        $(document).on('fileviewpage:save', function() {
            if(self.changed()) {
                var oldstatus = self.observables.status();
                self.editor.setReadOnly(true);
                self.observables.status('saving');
                m.redraw();
                var request = $.ajax({
                    type: 'PUT',
                    url: self.url,
                    data: self.editor.getValue(),
                    beforeSend: $osf.setXHRAuthorization
                }).done(function () {
                    self.editor.setReadOnly(false);
                    self.observables.status(oldstatus);
                    $(document).trigger('fileviewpage:reload');
                    self.initialText = self.editor.getValue();
                    m.redraw();
                }).fail(function(error) {
                    self.editor.setReadOnly(false);
                    self.observables.status(oldstatus);
                    $(document).trigger('fileviewpage:reload');
                    self.editor.setValue(self.initialText);
                    $osf.growl('Error', 'The file could not be updated.');
                    Raven.captureMessage('Could not PUT file content.', {
                        error: error,
                        url: self.url
                    });
                    m.redraw();
                });
            } else {
                alert('There are no changes to save.');
            }
        });

        //See Above comment
        $(document).on('fileviewpage:revert', function() {
            self.editor.setValue(self.initialText);
        });

        self.onChanged = function(e) {
            //To avoid extra typing
            var file1 = self.initialText;
            var file2 = !self.editor ? '' : self.editor.getValue();

            var clean1 = typeof file1 === 'string' ?
                file1.replace(/(\r\n|\n|\r)/gm, '\n') : '';
            var clean2 = typeof file2 === 'string' ?
                file2.replace(/(\r\n|\n|\r)/gm, '\n') : '';

            self.changed(clean1 !== clean2);
        };

        self.reloadFile();

    },
    view: function(ctrl) {
        if (!ctrl.loaded) return util.Spinner;

        return m('.editor-pane', [
            m('.wiki-connected-users', m('.row', m('.col-md-12', [
                m('.ul.list-inline', {style: {'margin-top': '10px'}}, [
                    ctrl.observables.activeUsers().map(function(user) {
                        return m('li', m('a', {href: user.url}, [
                            m('img', {
                                title: user.name,
                                src: user.gravatar,
                                'data-container': 'body',
                                'data-placement': 'top',
                                'data-toggle': 'tooltip',
                                style: {border: '1px solid black'}
                            })
                        ]));
                    })

                ])
            ]))),
            m('', {style: {'padding-top': '10px'}}, [
                m('.wmd-input.wiki-editor#editor', {config: ctrl.bindAce})
            ]),
        ]);

    }
};

module.exports = FileEditor;
<commit_msg>No more clever things just reload the whole file<commit_after>var m = require('mithril');
var Raven = require('raven-js');
var $osf = require('js/osfHelpers');
var ShareJSDoc = require('js/pages/ShareJSDocFile.js');
require('ace-noconflict');
require('ace-mode-markdown');
require('ace-ext-language_tools');
require('addons/wiki/static/ace-markdown-snippets.js');
var Markdown = require('pagedown-ace-converter');
Markdown.getSanitizingConverter = require('pagedown-ace-sanitizer').getSanitizingConverter;
require('imports?Markdown=pagedown-ace-converter!pagedown-ace-editor');

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

var FileEditor = {
    controller: function(contentUrl, shareWSUrl, editorMeta, observables) {
        var self = this;
        self.url = contentUrl;
        self.loaded = false;
        self.initialText = '';
        self.editor = undefined;
        self.editorMeta = editorMeta;
        self.changed = m.prop(false);

        self.observables = observables;

        $osf.throttle(self.observables.status, 4000, {leading: false});

        self.bindAce = function(element, isInitialized, context) {
            if (isInitialized) return;
            self.editor = ace.edit(element.id);
            self.editor.setValue(self.initialText);
            self.editor.on('change', self.onChanged);
            new ShareJSDoc(shareWSUrl, self.editorMeta, self.editor, self.observables);
        };

        self.reloadFile = function() {
            self.loaded = false;
            $.ajax({
                type: 'GET',
                url: self.url,
                beforeSend: $osf.setXHRAuthorization,
            }).done(function (parsed, status, response) {
                m.startComputation();
                self.loaded = true;
                self.initialText = response.responseText;
                if (self.editor) {
                    self.editor.setValue(self.initialText);
                }
                m.endComputation();
            }).fail(function (xhr, textStatus, error) {
                $osf.growl('Error','The file content could not be loaded.');
                Raven.captureMessage('Could not GET file contents.', {
                    url: self.url,
                    textStatus: textStatus,
                    error: error
                });
            });
        };

        //Really crappy hack, panel and m.component blackbox this module
        //so its not possible, in the alotted time, to bind a function here to
        //buttons ~2 levels up
        $(document).on('fileviewpage:save', function() {
            if(self.changed()) {
                var oldstatus = self.observables.status();
                self.editor.setReadOnly(true);
                self.observables.status('saving');
                m.redraw();
                var request = $.ajax({
                    type: 'PUT',
                    url: self.url,
                    data: self.editor.getValue(),
                    beforeSend: $osf.setXHRAuthorization
                }).done(function () {
                    self.editor.setReadOnly(false);
                    self.observables.status(oldstatus);
                    $(document).trigger('fileviewpage:reload');
                    self.initialText = self.editor.getValue();
                    m.redraw();
                }).fail(function(error) {
                    self.editor.setReadOnly(false);
                    self.observables.status(oldstatus);
                    $(document).trigger('fileviewpage:reload');
                    self.editor.setValue(self.initialText);
                    $osf.growl('Error', 'The file could not be updated.');
                    Raven.captureMessage('Could not PUT file content.', {
                        error: error,
                        url: self.url
                    });
                    m.redraw();
                });
            } else {
                alert('There are no changes to save.');
            }
        });

        //See Above comment
        $(document).on('fileviewpage:revert', function() {
            self.reloadFile();
        });

        self.onChanged = function(e) {
            //To avoid extra typing
            var file1 = self.initialText;
            var file2 = !self.editor ? '' : self.editor.getValue();

            var clean1 = typeof file1 === 'string' ?
                file1.replace(/(\r\n|\n|\r)/gm, '\n') : '';
            var clean2 = typeof file2 === 'string' ?
                file2.replace(/(\r\n|\n|\r)/gm, '\n') : '';

            self.changed(clean1 !== clean2);
        };

        self.reloadFile();

    },
    view: function(ctrl) {
        if (!ctrl.loaded) return util.Spinner;

        return m('.editor-pane', [
            m('.wiki-connected-users', m('.row', m('.col-md-12', [
                m('.ul.list-inline', {style: {'margin-top': '10px'}}, [
                    ctrl.observables.activeUsers().map(function(user) {
                        return m('li', m('a', {href: user.url}, [
                            m('img', {
                                title: user.name,
                                src: user.gravatar,
                                'data-container': 'body',
                                'data-placement': 'top',
                                'data-toggle': 'tooltip',
                                style: {border: '1px solid black'}
                            })
                        ]));
                    })

                ])
            ]))),
            m('', {style: {'padding-top': '10px'}}, [
                m('.wmd-input.wiki-editor#editor', {config: ctrl.bindAce})
            ]),
        ]);

    }
};

module.exports = FileEditor;
<|endoftext|>


<commit_before>var san = require('../../dist/san.ssr');
var swig  = require('swig');
var art = require('art-template');

let App = san.defineComponent({
    template: `<div id='app'><ul><li s-for='item in items'>{{item}}</li></ul></div>`
});

var items = [];
for (var i = 0; i < 10000; i++) {
    items.push(i)
}
var data = {items};

var renderer = san.compileToRenderer(App);
var swigRenderer = swig.compile(`<div id='app'><ul>{% for item in items %}<li>{{item}}</li>{% endfor %}</ul></div>`);
var artRenderer = art.compile(`<div id='app'><ul>{<% for(var i = 0; i < items.length; i++){ %><li><%= items[i] %></li><% } %></ul></div>`)

var now2 = new Date();
for (var i = 0; i < 100; i++) {
    renderer(data);
}
var runtime2 = (new Date) - now2;
console.log(`san: ${runtime2 / 100}ms`);

var now = new Date();
for (var i = 0; i < 100; i++) {
    swigRenderer(data);
}
var runtime = (new Date) - now;
console.log(`swig: ${runtime / 100}ms`);

var now3 = new Date();
for (var i = 0; i < 100; i++) {
    artRenderer(data);
}
var runtime3 = (new Date) - now3;
console.log(`artTpl: ${runtime3 / 100}ms`);

<commit_msg>multi component<commit_after>var san = require('../../dist/san.ssr');
var swig  = require('swig');
var art = require('art-template');

let App = san.defineComponent({
    template: `<div id='app'><ul><li s-for='item in items'>{{item}}</li></ul></div>`
});

let Item = san.defineComponent({
    template: `<li>{{item}}</li>`
});
let App2 = san.defineComponent({
    components: {
        'x-item': Item
    },
    template: `<div id='app'><ul><x-item s-for='item in items' item="{{item}}"/></ul></div>`
});

var items = [];
for (var i = 0; i < 10000; i++) {
    items.push(i)
}
var data = {items};

var renderer = san.compileToRenderer(App);
var renderer2 = san.compileToRenderer(App2);
var swigRenderer = swig.compile(`<div id='app'><ul>{% for item in items %}<li>{{item}}</li>{% endfor %}</ul></div>`);
var artRenderer = art.compile(`<div id='app'><ul>{<% for(var i = 0; i < items.length; i++){ %><li><%= items[i] %></li><% } %></ul></div>`)

var now2 = new Date();
for (var i = 0; i < 100; i++) {
    renderer(data);
}
var runtime2 = (new Date) - now2;
console.log(`san: ${runtime2 / 100}ms`);

var now1 = new Date();
for (var i = 0; i < 100; i++) {
    renderer2(data);
}
var runtime1 = (new Date) - now1;
console.log(`san(item as component): ${runtime1 / 100}ms`);

var now = new Date();
for (var i = 0; i < 100; i++) {
    swigRenderer(data);
}
var runtime = (new Date) - now;
console.log(`swig: ${runtime / 100}ms`);

var now3 = new Date();
for (var i = 0; i < 100; i++) {
    artRenderer(data);
}
var runtime3 = (new Date) - now3;
console.log(`artTpl: ${runtime3 / 100}ms`);

<|endoftext|>


<commit_before>module.exports = function (grunt) {
  'use strict';

  /**
   * read optional JSON from filepath
   * @param {String} filepath
   * @return {Object}
   */
  var readOptionalJSON = function (filepath) {
    var data = {};
    try {
      data = grunt.file.readJSON(filepath);
      // The concatenated file won't pass onevar
      // But our modules can
      delete data.onever;
    } catch (e) { }
    return data;
  };

  var customLaunchers = {
    'SL_IE8': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '8.0',
      platform: 'windows XP'
    },
    'SL_IE9': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '9.0',
      platform: 'windows 7'
    },
    'SL_IE10': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '10.0',
      platform: 'windows 8'
    },
    'SL_IE11': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '11.0',
      platform: 'windows 8.1'
    },
    'SL_CHROME': {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '43',
      platform: 'windows 8'
    },
    'SL_FIREFOX': {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '38',
      platform: 'windows 8'
    },
    'SL_SAFARI': {
      base: 'SauceLabs',
      browserName: 'safari',
      version: '8.0',
      platform: 'OS X 10.10'
    }
  };

  grunt.initConfig({
    // package File
    pkg: grunt.file.readJSON('package.json'),

    // bulid source(grunt-build.js).
    build: {
      all: {
        baseUrl: 'src/js',        // base url
        startFile: 'intro.js',    // intro part
        endFile: 'outro.js',      // outro part
        outFile: 'dist/summernote.js' // out file
      }
    },

    // for javascript convention.
    jshint: {
      all: {
        src: [
          'src/**/*.js',
          'plugin/**/*.js',
          'lang/**/*.js',
          'Gruntfile.js',
          'test/**/*.js',
          '!test/coverage/**/*.js',
          'build/*.js'
        ],
        options: {
          jshintrc: true
        }
      },
      dist: {
        src: 'dist/summernote.js',
        options: readOptionalJSON('.jshintrc')
      }
    },

    // uglify: minify javascript
    uglify: {
      options: {
        banner: '/*! Summernote v<%=pkg.version%> | (c) 2013-2015 Alan Hong and other contributors | MIT license */\n'
      },
      all: {
        files: [
          { 'dist/summernote.min.js': ['dist/summernote.js'] },
          {
            expand: true,
            cwd: 'dist/lang',
            src: '**/*.js',
            dest: 'dist/lang',
            ext: '.min.js'
          }
        ]
      }
    },

    // recess: minify stylesheets
    recess: {
      dist: {
        options: { compile: true, compress: true },
        files: {
          'dist/summernote.css': ['src/less/summernote.less']
        }
      }
    },

    // compress: summernote-{{version}}-dist.zip
    compress: {
      main: {
        options: {
          archive: function () {
            return 'dist/summernote-{{version}}-dist.zip'.replace(
              '{{version}}',
              grunt.config('pkg.version')
            );
          }
        },
        files: [{
          expand: true,
          src: [
            'dist/*.js',
            'dist/*.css'
          ]
        }, {
          src: ['plugin/**/*.js', 'lang/**/*.js'],
          dest: 'dist/'
        }]
      }
    },

    // connect configuration.
    connect: {
      all: {
        options: {
          port: 3000
        }
      }
    },

    // watch source code change
    watch: {
      all: {
        files: ['src/less/*.less', 'src/js/**/*.js'],
        tasks: ['recess', 'jshint'],
        options: {
          livereload: true
        }
      }
    },

    // Meteor commands to test and publish package
    exec: {
      'meteor-test': {
        command: 'meteor/runtests.sh'
      },
      'meteor-publish': {
        command: 'meteor/publish.sh'
      }
    },

    karma: {
      options: {
        configFile: './test/karma.conf.js'
      },
      all: {
        // Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS, IE
        browsers: ['PhantomJS'],
        reporters: ['progress']
      },
      dist: {
        singleRun: true,
        browsers: ['PhantomJS']
      },
      travis: {
        singleRun: true,
        browsers: ['PhantomJS'],
        reporters: ['progress', 'coverage']
      },
      saucelabs: {
        reporters: ['saucelabs'],
        sauceLabs: {
          testName: 'unit tests for summernote',
          build: process.env.TRAVIS_BUILD_NUMBER,
          tags: [process.env.TRAVIS_BRANCH, process.env.TRAVIS_PULL_REQUEST]
        },
        captureTimeout: 120000,
        customLaunchers: customLaunchers,
        browsers: Object.keys(customLaunchers),
        singleRun: true
      }
    },

    coveralls: {
      options: {
        force: false
      },
      travis: {
        src: 'test/coverage/**/lcov.info'
      }
    },
    clean: {
      dist: ['dist']
    },
    copy: {
      dist: {
        files: [
          {src: 'lang/*', dest: 'dist/'}
        ]
      }
    }
  });

  // load all tasks from the grunt plugins used in this file
  require('load-grunt-tasks')(grunt);

  // load all grunts/*.js
  grunt.loadTasks('grunts');

  // server: runt server for development
  grunt.registerTask('server', ['connect', 'watch']);

  // test: unit test on test folder
  grunt.registerTask('test', ['jshint', 'karma:all']);

  // test: unit test on travis
  grunt.registerTask('test-travis', ['jshint', 'karma:travis']);

  // test: saucelabs test
  grunt.registerTask('saucelabs-test', ['karma:saucelabs']);

  // dist: make dist files
  grunt.registerTask('dist', [
    'clean:dist',
    'build', 'jshint', 'karma:dist',
    'copy:dist', 'uglify', 'recess', 'compress'
  ]);

  // default: server
  grunt.registerTask('default', ['server']);

  // Meteor tasks
  grunt.registerTask('meteor-test', 'exec:meteor-test');
  grunt.registerTask('meteor-publish', 'exec:meteor-publish');
  grunt.registerTask('meteor', ['meteor-test', 'meteor-publish']);

};
<commit_msg>fix saucelabs connection problem on trvis ci<commit_after>module.exports = function (grunt) {
  'use strict';

  /**
   * read optional JSON from filepath
   * @param {String} filepath
   * @return {Object}
   */
  var readOptionalJSON = function (filepath) {
    var data = {};
    try {
      data = grunt.file.readJSON(filepath);
      // The concatenated file won't pass onevar
      // But our modules can
      delete data.onever;
    } catch (e) { }
    return data;
  };

  var customLaunchers = {
    'SL_IE8': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '8.0',
      platform: 'windows XP'
    },
    'SL_IE9': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '9.0',
      platform: 'windows 7'
    },
    'SL_IE10': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '10.0',
      platform: 'windows 8'
    },
    'SL_IE11': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '11.0',
      platform: 'windows 8.1'
    },
    'SL_CHROME': {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '43',
      platform: 'windows 8'
    },
    'SL_FIREFOX': {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '38',
      platform: 'windows 8'
    },
    'SL_SAFARI': {
      base: 'SauceLabs',
      browserName: 'safari',
      version: '8.0',
      platform: 'OS X 10.10'
    }
  };

  grunt.initConfig({
    // package File
    pkg: grunt.file.readJSON('package.json'),

    // bulid source(grunt-build.js).
    build: {
      all: {
        baseUrl: 'src/js',        // base url
        startFile: 'intro.js',    // intro part
        endFile: 'outro.js',      // outro part
        outFile: 'dist/summernote.js' // out file
      }
    },

    // for javascript convention.
    jshint: {
      all: {
        src: [
          'src/**/*.js',
          'plugin/**/*.js',
          'lang/**/*.js',
          'Gruntfile.js',
          'test/**/*.js',
          '!test/coverage/**/*.js',
          'build/*.js'
        ],
        options: {
          jshintrc: true
        }
      },
      dist: {
        src: 'dist/summernote.js',
        options: readOptionalJSON('.jshintrc')
      }
    },

    // uglify: minify javascript
    uglify: {
      options: {
        banner: '/*! Summernote v<%=pkg.version%> | (c) 2013-2015 Alan Hong and other contributors | MIT license */\n'
      },
      all: {
        files: [
          { 'dist/summernote.min.js': ['dist/summernote.js'] },
          {
            expand: true,
            cwd: 'dist/lang',
            src: '**/*.js',
            dest: 'dist/lang',
            ext: '.min.js'
          }
        ]
      }
    },

    // recess: minify stylesheets
    recess: {
      dist: {
        options: { compile: true, compress: true },
        files: {
          'dist/summernote.css': ['src/less/summernote.less']
        }
      }
    },

    // compress: summernote-{{version}}-dist.zip
    compress: {
      main: {
        options: {
          archive: function () {
            return 'dist/summernote-{{version}}-dist.zip'.replace(
              '{{version}}',
              grunt.config('pkg.version')
            );
          }
        },
        files: [{
          expand: true,
          src: [
            'dist/*.js',
            'dist/*.css'
          ]
        }, {
          src: ['plugin/**/*.js', 'lang/**/*.js'],
          dest: 'dist/'
        }]
      }
    },

    // connect configuration.
    connect: {
      all: {
        options: {
          port: 3000
        }
      }
    },

    // watch source code change
    watch: {
      all: {
        files: ['src/less/*.less', 'src/js/**/*.js'],
        tasks: ['recess', 'jshint'],
        options: {
          livereload: true
        }
      }
    },

    // Meteor commands to test and publish package
    exec: {
      'meteor-test': {
        command: 'meteor/runtests.sh'
      },
      'meteor-publish': {
        command: 'meteor/publish.sh'
      }
    },

    karma: {
      options: {
        configFile: './test/karma.conf.js'
      },
      all: {
        // Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS, IE
        browsers: ['PhantomJS'],
        reporters: ['progress']
      },
      dist: {
        singleRun: true,
        browsers: ['PhantomJS']
      },
      travis: {
        singleRun: true,
        browsers: ['PhantomJS'],
        reporters: ['progress', 'coverage']
      },
      saucelabs: {
        reporters: ['saucelabs'],
        sauceLabs: {
          testName: '[Travis] unit tests for summernote',
          startConnect: false,
          tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
          build: process.env.TRAVIS_BUILD_NUMBER,
          tags: [process.env.TRAVIS_BRANCH, process.env.TRAVIS_PULL_REQUEST]
        },
        captureTimeout: 120000,
        customLaunchers: customLaunchers,
        browsers: Object.keys(customLaunchers),
        singleRun: true
      }
    },

    coveralls: {
      options: {
        force: false
      },
      travis: {
        src: 'test/coverage/**/lcov.info'
      }
    },
    clean: {
      dist: ['dist']
    },
    copy: {
      dist: {
        files: [
          {src: 'lang/*', dest: 'dist/'}
        ]
      }
    }
  });

  // load all tasks from the grunt plugins used in this file
  require('load-grunt-tasks')(grunt);

  // load all grunts/*.js
  grunt.loadTasks('grunts');

  // server: runt server for development
  grunt.registerTask('server', ['connect', 'watch']);

  // test: unit test on test folder
  grunt.registerTask('test', ['jshint', 'karma:all']);

  // test: unit test on travis
  grunt.registerTask('test-travis', ['jshint', 'karma:travis']);

  // test: saucelabs test
  grunt.registerTask('saucelabs-test', ['karma:saucelabs']);

  // dist: make dist files
  grunt.registerTask('dist', [
    'clean:dist',
    'build', 'jshint', 'karma:dist',
    'copy:dist', 'uglify', 'recess', 'compress'
  ]);

  // default: server
  grunt.registerTask('default', ['server']);

  // Meteor tasks
  grunt.registerTask('meteor-test', 'exec:meteor-test');
  grunt.registerTask('meteor-publish', 'exec:meteor-publish');
  grunt.registerTask('meteor', ['meteor-test', 'meteor-publish']);

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {

    /*
     * load all grunt tasks, instead of loading each one like this:
     * grunt.loadNpmTasks('grunt-concurrent'); ...
     * This reads the file package.json
     * More info here: https://github.com/sindresorhus/load-grunt-tasks
     */
    require('load-grunt-tasks')(grunt);

    /*
     * -----------------------------
     * Tasks:
     */

    //default task: grunt
    grunt.registerTask('default', [
        'build' //by default, just build
    ]);

    //build task: grunt
    // grunt.registerTask('build', [
    //     'clean:dist', //clean dist folder
    //     'copy:templates', //copy js and template files
    //     'uglify', //uglify js files
    //     'sass:dist', //compile scss
    //     'preview_pages', //build preview_pages
    // ]);

    //developer task: grunt dev
    grunt.registerTask('dev', [

        'clean:dist', //clean dist folder
        'write_plugins', //includes all tools and components in plugins.js
        'generate_styles', //generate scss
        'sass:dev', //compile scss
        'preview_pages_menu', //build preview_pages menu template
        'includereplace:preview_pages_dev', //preview_pages folder
        'preview_pages_index', //build preview_pages
        'copy:scripts',
        'copy:templates',
        'copy:preview_pages', //copies preview_page assets
        'copy:waffles', //copies waffles
        'copy:assets', //copies assets
        'connect', //run locally
        'watch' //watch for code changes
    ]);

    //developer task: grunt dev
    grunt.registerTask('build', [

        'clean:dist', //clean dist folder
        'includereplace:build', //build AMD wrapper
        'write_plugins', //includes all tools and components in plugins.js
        'requirejs:dist', //use requirejs for amd module
        'generate_styles', //generate scss
        'sass:dist', //compile scss
        'preview_pages_menu', //build preview_pages menu template
        'includereplace:preview_pages_build', //preview_pages folder
        'preview_pages_index', //build preview_pages
        'copy:preview_pages', //copies preview_page assets
        'copy:waffles', //copies waffles
        'copy:assets', //copies assets

    ]);

    //default task with connect
    grunt.registerTask('serve', [
        'default', //default build
        'connect', //run locally
        'watch' //watch for code changes
    ]);

    /*
     * -----------------------------
     * Configuration:
     */

    grunt.initConfig({

        // Clean dist folder to have a clean start
        clean: {
            dist: ["dist/*"]
        },

        // Copy all js and template files to dist folder
        copy: {
            preview_pages: {
                cwd: 'preview_pages',
                src: ['assets/scripts.js', 'assets/style.css'],
                dest: 'dist/preview_pages/',
                expand: true
            },
            waffles: {
                cwd: 'data-waffles',
                src: ['**/*'],
                dest: 'dist/data-waffles/',
                expand: true
            },
            assets: {
                cwd: 'src',
                src: ['assets/imgs/**/*'],
                dest: 'dist/',
                expand: true
            },
            scripts: {
                cwd: 'src',
                src: ['**/*.js'],
                dest: 'dist/',
                expand: true
            },
            templates: {
                cwd: 'src',
                src: ['**/*.html'],
                dest: 'dist/',
                expand: true
            }
        },

        // Uglifying JS files
        uglify: {
            files: {
                cwd: 'src/', // base path
                src: '**/*.js', // source files mask
                dest: 'dist', // destination folder
                expand: true, // allow dynamic building
                mangle: false, // disallow change in names
                flatten: false // remove all unnecessary nesting
            }
        },

        // Compile SCSS files into CSS (dev mode is not compressed)
        sass: {
            dist: {
                options: {
                    style: 'compressed'
                },
                files: {
                    'dist/vizabi.css': 'src/assets/style/vizabi.scss',
                }
            },
            dev: {
                options: {
                    style: 'expanded'
                },
                files: {
                    'dist/vizabi.css': 'src/assets/style/vizabi.scss',
                }
            }
        },

        // Make sure necessary files are built when changes are made
        watch: {
            styles: {
                files: ['src/**/*.scss'],
                tasks: ['sass:dev']
            },
            preview_pages: {
                files: ['preview_pages/**/*.html', '!preview_pages/index.html'],
                tasks: ['includereplace:preview_pages_dev', 'preview_pages_index', 'copy:preview_pages']
            },
            scripts: {
                files: ['src/**/*.js'],
                tasks: ['copy:scripts', 'copy:templates']
            },
            options: {
                livereload: {
                    port: '<%= connect.options.livereload %>'
                }
            }
        },

        connect: {
            options: {
                port: 9000,
                livereload: 35729,
                // change this to '0.0.0.0' to access the server from outside
                hostname: 'localhost'
            },
            livereload: {
                options: {
                    open: 'http://<%= connect.options.hostname %>:<%= connect.options.port %>/dist/preview_pages/'
                }
            }
        },

        requirejs: {
            // Options: https://github.com/jrburke/r.js/blob/master/build/preview_page.build.js
            dist: {
                options: {
                    baseUrl: "src/",
                    mainConfigFile: "src/config.js",
                    out: "dist/vizabi.js",
                    optimize: "uglify",
                    generateSourceMaps: false,
                }
            }
        },

        includereplace: {
            build: {
                options: {
                    prefix: ''
                },
                src: 'src/build/vizabi-amd.frag',
                dest: 'src/vizabi-amd.js'
            },
            //build preview_pages without require
            preview_pages_build: {
                options: {
                    prefix: '',
                    globals: {
                        include_require: ''
                    }
                },
                src: 'preview_pages/**/*.html',
                dest: 'dist/'
            },
            //build preview_pages with require
            preview_pages_dev: {
                options: {
                    prefix: '',
                    globals: {
                        include_require: ''
                    }
                },
                src: 'preview_pages/**/*.html',
                dest: 'dist/'
            }
        }
    });

    /*
     * ---------
     * Building custom preview_page index
     */

    grunt.registerTask('preview_pages_index', 'Writes preview_pages index', function() {

        var preview_pages_folder = 'dist/preview_pages/',
            preview_pages_index = preview_pages_folder + 'index.html',
            contents = "
Vizabi Examples:
",
            current_dir;

        grunt.file.recurse(preview_pages_folder, function(abs, root, dir, file) {
            if (typeof dir !== 'undefined' && file.indexOf('.html') !== -1) {
                if (current_dir !== dir) {
                    current_dir = dir;
                    contents += "
" + dir + "
";
                }
                var link = dir + '/' + file;
                var preview_page = "
" + file + "
";
                contents += preview_page;
            }
        });
        grunt.file.write(preview_pages_index, contents);
        grunt.log.writeln("Wrote preview_pages index.");
    });

    grunt.registerTask('preview_pages_menu', 'Writes _preview_pages.tpl', function() {

        var preview_pages_folder = 'preview_pages/',
            preview_pages_file = preview_pages_folder + 'assets/_preview.tpl',
            current_dir,
            contents = "";

        grunt.file.recurse(preview_pages_folder, function(abs, root, dir, file) {
            if (typeof dir !== 'undefined' && file.indexOf('.html') !== -1) {
                file = file.replace(".html", "");
                var link = dir + '/' + file;
                var preview_page = "
"+link+"
";
                contents += preview_page;
            }
        });
        grunt.file.write(preview_pages_file, contents);
        grunt.log.writeln("Wrote preview_pages menu template.");
    });

    /*
     * ---------
     * Hotfix to include everything into the AMD
     * Include every tool and component into src/plugins.js
     */

    grunt.registerTask('write_plugins', 'Includes every component and tool into the AMD module', function() {

        var tools_folder = 'src/tools/',
            components_folder = 'src/components/',
            plugins_file = 'src/plugins.js',
            contents = [],
            current_dir;

        grunt.file.recurse(tools_folder, function(abs, root, dir, file) {
            var clean_abs;
            if (typeof dir !== 'undefined' && file.indexOf('.js') !== -1) {
                // src/tools/_examples/bar-chart/bar-chart.js --> tools/_examples/bar-chart/bar-chart
                clean_abs = abs.replace(".js", "").replace("src/", "");
                contents.push('"' + clean_abs + '"');
            }
            else if (typeof dir !== 'undefined' && file.indexOf('.html') !== -1) {
                clean_abs = abs.replace("src/", "");
                contents.push('"text!' + clean_abs + '"');
            }
        });

        grunt.file.recurse(components_folder, function(abs, root, dir, file) {
            var clean_abs;
            if (typeof dir !== 'undefined' && file.indexOf('.js') !== -1) {
                clean_abs = abs.replace(".js", "").replace("src/", "");
                contents.push('"' + clean_abs + '"');
            }
            else if (typeof dir !== 'undefined' && file.indexOf('.html') !== -1) {
                clean_abs = abs.replace("src/", "");
                contents.push('"text!' + clean_abs + '"');
            }
        });

        contents = 'define([' + contents.join(",") + '], function() {});';
        grunt.file.write(plugins_file, contents);

        grunt.log.writeln("All tools and components have been included in the AMD module.");
    });

/*
     * ---------
     * Include all tool styles into vizabi.scss
     */

    grunt.registerTask('generate_styles', 'Adds each tool scss to vizabi.scss', function() {

        var tools_folder = 'src/tools/',
            scss_file = 'src/assets/style/vizabi.scss',
            includes = ['_vizabi.scss'],
            contents = '',
            current_dir;

        grunt.file.recurse(tools_folder, function(abs, root, dir, file) {
            if (typeof dir !== 'undefined' && file.indexOf('.scss') !== -1) {
                var clean_abs = abs.replace("src/", "");
                includes.push('../../' + clean_abs);
            }
        });

        for (var i = 0; i < includes.length; i++) {
            contents += '@import "'+includes[i]+'";\n';
        };

        grunt.file.write(scss_file, contents);

        grunt.log.writeln("All styles included in vizabi.scss");
    });

}<commit_msg>Fix write_plugin task. Now it grabs only .js and .html, not .js.swp or .html.swp<commit_after>module.exports = function(grunt) {

    /*
     * load all grunt tasks, instead of loading each one like this:
     * grunt.loadNpmTasks('grunt-concurrent'); ...
     * This reads the file package.json
     * More info here: https://github.com/sindresorhus/load-grunt-tasks
     */
    require('load-grunt-tasks')(grunt);

    /*
     * -----------------------------
     * Tasks:
     */

    //default task: grunt
    grunt.registerTask('default', [
        'build' //by default, just build
    ]);

    //build task: grunt
    // grunt.registerTask('build', [
    //     'clean:dist', //clean dist folder
    //     'copy:templates', //copy js and template files
    //     'uglify', //uglify js files
    //     'sass:dist', //compile scss
    //     'preview_pages', //build preview_pages
    // ]);

    //developer task: grunt dev
    grunt.registerTask('dev', [

        'clean:dist', //clean dist folder
        'write_plugins', //includes all tools and components in plugins.js
        'generate_styles', //generate scss
        'sass:dev', //compile scss
        'preview_pages_menu', //build preview_pages menu template
        'includereplace:preview_pages_dev', //preview_pages folder
        'preview_pages_index', //build preview_pages
        'copy:scripts',
        'copy:templates',
        'copy:preview_pages', //copies preview_page assets
        'copy:waffles', //copies waffles
        'copy:assets', //copies assets
        'connect', //run locally
        'watch' //watch for code changes
    ]);

    //developer task: grunt dev
    grunt.registerTask('build', [

        'clean:dist', //clean dist folder
        'includereplace:build', //build AMD wrapper
        'write_plugins', //includes all tools and components in plugins.js
        'requirejs:dist', //use requirejs for amd module
        'generate_styles', //generate scss
        'sass:dist', //compile scss
        'preview_pages_menu', //build preview_pages menu template
        'includereplace:preview_pages_build', //preview_pages folder
        'preview_pages_index', //build preview_pages
        'copy:preview_pages', //copies preview_page assets
        'copy:waffles', //copies waffles
        'copy:assets', //copies assets

    ]);

    //default task with connect
    grunt.registerTask('serve', [
        'default', //default build
        'connect', //run locally
        'watch' //watch for code changes
    ]);

    /*
     * -----------------------------
     * Configuration:
     */

    grunt.initConfig({

        // Clean dist folder to have a clean start
        clean: {
            dist: ["dist/*"]
        },

        // Copy all js and template files to dist folder
        copy: {
            preview_pages: {
                cwd: 'preview_pages',
                src: ['assets/scripts.js', 'assets/style.css'],
                dest: 'dist/preview_pages/',
                expand: true
            },
            waffles: {
                cwd: 'data-waffles',
                src: ['**/*'],
                dest: 'dist/data-waffles/',
                expand: true
            },
            assets: {
                cwd: 'src',
                src: ['assets/imgs/**/*'],
                dest: 'dist/',
                expand: true
            },
            scripts: {
                cwd: 'src',
                src: ['**/*.js'],
                dest: 'dist/',
                expand: true
            },
            templates: {
                cwd: 'src',
                src: ['**/*.html'],
                dest: 'dist/',
                expand: true
            }
        },

        // Uglifying JS files
        uglify: {
            files: {
                cwd: 'src/', // base path
                src: '**/*.js', // source files mask
                dest: 'dist', // destination folder
                expand: true, // allow dynamic building
                mangle: false, // disallow change in names
                flatten: false // remove all unnecessary nesting
            }
        },

        // Compile SCSS files into CSS (dev mode is not compressed)
        sass: {
            dist: {
                options: {
                    style: 'compressed'
                },
                files: {
                    'dist/vizabi.css': 'src/assets/style/vizabi.scss',
                }
            },
            dev: {
                options: {
                    style: 'expanded'
                },
                files: {
                    'dist/vizabi.css': 'src/assets/style/vizabi.scss',
                }
            }
        },

        // Make sure necessary files are built when changes are made
        watch: {
            styles: {
                files: ['src/**/*.scss'],
                tasks: ['sass:dev']
            },
            preview_pages: {
                files: ['preview_pages/**/*.html', '!preview_pages/index.html'],
                tasks: ['includereplace:preview_pages_dev', 'preview_pages_index', 'copy:preview_pages']
            },
            scripts: {
                files: ['src/**/*.js'],
                tasks: ['copy:scripts', 'copy:templates']
            },
            options: {
                livereload: {
                    port: '<%= connect.options.livereload %>'
                }
            }
        },

        connect: {
            options: {
                port: 9000,
                livereload: 35729,
                // change this to '0.0.0.0' to access the server from outside
                hostname: 'localhost'
            },
            livereload: {
                options: {
                    open: 'http://<%= connect.options.hostname %>:<%= connect.options.port %>/dist/preview_pages/'
                }
            }
        },

        requirejs: {
            // Options: https://github.com/jrburke/r.js/blob/master/build/preview_page.build.js
            dist: {
                options: {
                    baseUrl: "src/",
                    mainConfigFile: "src/config.js",
                    out: "dist/vizabi.js",
                    optimize: "uglify",
                    generateSourceMaps: false,
                }
            }
        },

        includereplace: {
            build: {
                options: {
                    prefix: ''
                },
                src: 'src/build/vizabi-amd.frag',
                dest: 'src/vizabi-amd.js'
            },
            //build preview_pages without require
            preview_pages_build: {
                options: {
                    prefix: '',
                    globals: {
                        include_require: ''
                    }
                },
                src: 'preview_pages/**/*.html',
                dest: 'dist/'
            },
            //build preview_pages with require
            preview_pages_dev: {
                options: {
                    prefix: '',
                    globals: {
                        include_require: ''
                    }
                },
                src: 'preview_pages/**/*.html',
                dest: 'dist/'
            }
        }
    });

    /*
     * ---------
     * Building custom preview_page index
     */

    grunt.registerTask('preview_pages_index', 'Writes preview_pages index', function() {

        var preview_pages_folder = 'dist/preview_pages/',
            preview_pages_index = preview_pages_folder + 'index.html',
            contents = "
Vizabi Examples:
",
            current_dir;

        grunt.file.recurse(preview_pages_folder, function(abs, root, dir, file) {
            if (typeof dir !== 'undefined' && file.indexOf('.html') !== -1) {
                if (current_dir !== dir) {
                    current_dir = dir;
                    contents += "
" + dir + "
";
                }
                var link = dir + '/' + file;
                var preview_page = "
" + file + "
";
                contents += preview_page;
            }
        });
        grunt.file.write(preview_pages_index, contents);
        grunt.log.writeln("Wrote preview_pages index.");
    });

    grunt.registerTask('preview_pages_menu', 'Writes _preview_pages.tpl', function() {

        var preview_pages_folder = 'preview_pages/',
            preview_pages_file = preview_pages_folder + 'assets/_preview.tpl',
            current_dir,
            contents = "";

        grunt.file.recurse(preview_pages_folder, function(abs, root, dir, file) {
            if (typeof dir !== 'undefined' && file.indexOf('.html') !== -1) {
                file = file.replace(".html", "");
                var link = dir + '/' + file;
                var preview_page = "
"+link+"
";
                contents += preview_page;
            }
        });
        grunt.file.write(preview_pages_file, contents);
        grunt.log.writeln("Wrote preview_pages menu template.");
    });

    /*
     * ---------
     * Hotfix to include everything into the AMD
     * Include every tool and component into src/plugins.js
     */

    grunt.registerTask('write_plugins', 'Includes every component and tool into the AMD module', function() {

        var tools_folder = 'src/tools/',
            components_folder = 'src/components/',
            plugins_file = 'src/plugins.js',
            contents = [],
            current_dir;

        grunt.file.recurse(tools_folder, function(abs, root, dir, file) {
            var clean_abs;
            if (typeof dir !== 'undefined' && /\.js$/.test(file)) {
                // src/tools/_examples/bar-chart/bar-chart.js --> tools/_examples/bar-chart/bar-chart
                clean_abs = abs.replace(".js", "").replace("src/", "");
                contents.push('"' + clean_abs + '"');
            }
            else if (typeof dir !== 'undefined' && /\.html$/.test(file)) {
                clean_abs = abs.replace("src/", "");
                contents.push('"text!' + clean_abs + '"');
            }
        });

        grunt.file.recurse(components_folder, function(abs, root, dir, file) {
            var clean_abs;
            if (typeof dir !== 'undefined' && /\.js$/.test(file)) {
                clean_abs = abs.replace(".js", "").replace("src/", "");
                contents.push('"' + clean_abs + '"');
            }
            else if (typeof dir !== 'undefined' && /\.html$/.test(file)) {
                clean_abs = abs.replace("src/", "");
                contents.push('"text!' + clean_abs + '"');
            }
        });

        contents = 'define([' + contents.join(",") + '], function() {});';
        grunt.file.write(plugins_file, contents);

        grunt.log.writeln("All tools and components have been included in the AMD module.");
    });

/*
     * ---------
     * Include all tool styles into vizabi.scss
     */

    grunt.registerTask('generate_styles', 'Adds each tool scss to vizabi.scss', function() {

        var tools_folder = 'src/tools/',
            scss_file = 'src/assets/style/vizabi.scss',
            includes = ['_vizabi.scss'],
            contents = '',
            current_dir;

        grunt.file.recurse(tools_folder, function(abs, root, dir, file) {
            if (typeof dir !== 'undefined' && file.indexOf('.scss') !== -1) {
                var clean_abs = abs.replace("src/", "");
                includes.push('../../' + clean_abs);
            }
        });

        for (var i = 0; i < includes.length; i++) {
            contents += '@import "'+includes[i]+'";\n';
        };

        grunt.file.write(scss_file, contents);

        grunt.log.writeln("All styles included in vizabi.scss");
    });

}
<|endoftext|>


<commit_before>function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

var Sherlok = {

  annotate: function (pipelineId, text_to_annotate, element_id) {

    $.post("/annotate/" + pipelineId, {"text": text_to_annotate}, function(annotated_json) {

      var sofa = annotated_json["_referenced_fss"]["1"];
      var txt = sofa["sofaString"];

      // collect annotations
      var blacklist = ["Sofa", "DocumentAnnotation"];
      var annots = [];

      var annotationSet = annotated_json["_views"]["_InitialView"];
      for (type in annotationSet) {
        if (!isInArray(type, blacklist)) {
          for (k in annotationSet[type]) {
            var annot = annotationSet[type][k];
            var begin = annot["begin"] || 0, end = annot["end"];
            var value = annot["value"] || type; // if no "value", use type instead.
            annots[annots.length] = {begin: begin, end: end, value: value};
          }
        }
      }

      // highlight text (add spans)
      var newTxt = "";
      var last = txt.length;
      $.each(annots.sort(predicatBy("end")), function(index3, a){
        console.log(a);
        if (a.end <= last){
          newTxt = '' + txt.substring(a.begin, a.end) + '' +  txt.substring(a.end, last) + newTxt;
          last = a.begin;
        }
      });
      newTxt = txt.substring(0, last) + newTxt;
      $("#"+element_id).html(newTxt);
    });
  }
}

// sort by inverse predicate
function predicatBy(prop) {
  return function(a,b) {
    if (a[prop] > b[prop]) {
      return -1;
    } else if (a[prop] < b[prop]) {
      return 1;
    }
    return 0;
  }
}
<commit_msg>support references<commit_after>function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

function isInt(value) {
  return !isNaN(value) &&
         parseInt(Number(value)) == value &&
         !isNaN(parseInt(value, 10));
}

var Sherlok = {

  annotate: function (pipelineId, text_to_annotate, element_id) {

    $.post("/annotate/" + pipelineId, {"text": text_to_annotate}, function(annotated_json) {

      var refs = annotated_json["_referenced_fss"];
      var sofa = refs["1"];
      var txt = sofa["sofaString"];

      // collect annotations
      var blacklist = ["Sofa", "DocumentAnnotation"];
      var annots = [];

      var annotationSet = annotated_json["_views"]["_InitialView"];
      for (type in annotationSet) {
        if (!isInArray(type, blacklist)) {
          for (k in annotationSet[type]) {
            var annot = annotationSet[type][k];

            // handle references
            if (isInt(annot)) {
              annot = refs[annot];
            }

            var begin = annot["begin"] || 0;
            var end   = annot["end"];
            var value = annot["value"] || type; // if no "value", use type instead.
            annots[annots.length] = {begin: begin, end: end, value: value};
          }
        }
      }

      // highlight text (add spans)
      var newTxt = "";
      var last = txt.length;
      $.each(annots.sort(predicatBy("end")), function(index3, a){
        console.log(a);
        if (a.end <= last){
          newTxt = '' + txt.substring(a.begin, a.end) + '' +  txt.substring(a.end, last) + newTxt;
          last = a.begin;
        }
      });
      newTxt = txt.substring(0, last) + newTxt;
      $("#"+element_id).html(newTxt);
    });
  }
}

// sort by inverse predicate
function predicatBy(prop) {
  return function(a,b) {
    if (a[prop] > b[prop]) {
      return -1;
    } else if (a[prop] < b[prop]) {
      return 1;
    }
    return 0;
  }
}
<|endoftext|>


<commit_before>import {
  select,
  event as currentEvent,
} from 'd3-selection';
import { drag, dragDisable } from 'd3-drag';
import 'd3-transition'; // defines selection.transition()

import Codeck from './Codeck';
// import installServiceWorker from './worker';

dragDisable(window);

const { floor } = Math;
const codeck = new Codeck();

const svg = select('#cards svg')
  .attr('width', '600px')
  .attr('height', '400px');

const messageInput = select('#message');
const cleanedMessageSpan = select('.cleanednotification');

messageInput.node().maxLength = codeck.maxLength;
messageInput.node().size = codeck.maxLength;

const cards = {};
codeck.deck.forEach((key, idx) => {
  cards[key] = { key, idx, dragging: false, dx: 0, dy: 0 };
});

const cardOrder = codeck.deck.slice(); // copy of deck.

let debounceInputId = -1;
messageInput.on('keyup', () => {
  clearTimeout(debounceInputId);
  debounceInputId = setTimeout(updateMessage, 100);
});

function cleanMessage(text) {
  return text.toUpperCase().trim()
    .replace(/['"]/g, ',')
    .replace(/[!?]/g, '.')
    .replace(/[^A-Z0-9,. ]/g, '');
}

function updateMessage() {
  const typedMessage = messageInput.node().value;
  const cleanedMessage = cleanMessage(messageInput.node().value);
  const newOrder = codeck.encode(cleanedMessage.toLowerCase());
  newOrder.forEach((cardKey, i) => {
    cardOrder[i] = cardKey;
    cards[cardKey].idx = i;
  });
  if (typedMessage === cleanedMessage) {
    cleanedMessageSpan.classed('hide', true);
  } else {
    cleanedMessageSpan
      .classed('hide', false)
      .select('span')
        .text(cleanedMessage);
  }
  renderCards();
}

function moveCard(card, di) {
  if (card + di > cardOrder.length || card + di < 0) return;

  if (di > 0) {
    for (let i = card.idx; i < card.idx + di; i++) {
      cardOrder[i] = cardOrder[i + 1];
      cards[cardOrder[i]].idx = i;
    }
  } else if (di < 0) {
    for (let i = card.idx; i > card.idx + di; i--) {
      cardOrder[i] = cardOrder[i - 1];
      cards[cardOrder[i]].idx = i;
    }
  }
  cardOrder[card.idx + di] = card.key;
  card.idx += di;
  renderCards();
}

function renderCards() {
  svg.selectAll('.card').transition()
    .delay(d => d.idx * 5)
    .filter(d => !d.dragging)
    .attr('transform', d =>
      `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`);
}

function dragstarted(d) {
  d.dragging = true;
  select(this).style('filter', 'url(#shadow)');
}

function dragged(d) {
  d.dx += currentEvent.dx;
  d.dy += currentEvent.dy;
  if (d.dx > 28) {
    d.dx -= 48;
    moveCard(d, 1);
  } else if (d.dx < -28) {
    d.dx += 48;
    moveCard(d, -1);
  }
  if (d.dy > 34) {
    d.dy -= 60;
    moveCard(d, 9);
  } else if (d.dy < -34) {
    d.dy += 60;
    moveCard(d, -9);
  }
  select(this).attr('transform', d =>
    `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`);
}

function dragended(d) {
  d.dx = 0;
  d.dy = 0;
  d.dragging = false;
  select(this).style('filter', null);
  renderCards();
  const message = codeck.decode(cardOrder);
  messageInput.node().value = message.trim().toUpperCase();
  cleanedMessageSpan.classed('hide', true);
}

function showCardsInit() {
  svg.selectAll('.card')
    .data(Object.values(cards), card => card.key)
    .enter().append('text')
      .attr('class', 'card')
      .attr('transform', 'translate(0, 0)')
      .text(card => card.key)
      .attr('y', 60)
      .attr('fill', d => (floor(d.idx / 13) % 2 !== 0) ? 'red' : 'black')
      .call(drag()
        .on('start', dragstarted)
        .on('drag', dragged)
        .on('end', dragended));
  renderCards();
}

setTimeout(showCardsInit, 100);

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('worker.js');
  });
}
<commit_msg>Revert preventdefault behavior<commit_after>import {
  select,
  event as currentEvent,
} from 'd3-selection';
import { drag } from 'd3-drag';
import 'd3-transition'; // defines selection.transition()

import Codeck from './Codeck';

const { floor } = Math;
const codeck = new Codeck();

const svg = select('#cards svg')
  .attr('width', '600px')
  .attr('height', '400px');

const messageInput = select('#message');
const cleanedMessageSpan = select('.cleanednotification');

messageInput.node().maxLength = codeck.maxLength;
messageInput.node().size = codeck.maxLength;

const cards = {};
codeck.deck.forEach((key, idx) => {
  cards[key] = { key, idx, dragging: false, dx: 0, dy: 0 };
});

const cardOrder = codeck.deck.slice(); // copy of deck.

let debounceInputId = -1;
messageInput.on('keyup', () => {
  clearTimeout(debounceInputId);
  debounceInputId = setTimeout(updateMessage, 100);
});

function cleanMessage(text) {
  return text.toUpperCase().trim()
    .replace(/['"]/g, ',')
    .replace(/[!?]/g, '.')
    .replace(/[^A-Z0-9,. ]/g, '');
}

function updateMessage() {
  const typedMessage = messageInput.node().value;
  const cleanedMessage = cleanMessage(messageInput.node().value);
  const newOrder = codeck.encode(cleanedMessage.toLowerCase());
  newOrder.forEach((cardKey, i) => {
    cardOrder[i] = cardKey;
    cards[cardKey].idx = i;
  });
  if (typedMessage === cleanedMessage) {
    cleanedMessageSpan.classed('hide', true);
  } else {
    cleanedMessageSpan
      .classed('hide', false)
      .select('span')
        .text(cleanedMessage);
  }
  renderCards();
}

function moveCard(card, di) {
  if (card + di > cardOrder.length || card + di < 0) return;

  if (di > 0) {
    for (let i = card.idx; i < card.idx + di; i++) {
      cardOrder[i] = cardOrder[i + 1];
      cards[cardOrder[i]].idx = i;
    }
  } else if (di < 0) {
    for (let i = card.idx; i > card.idx + di; i--) {
      cardOrder[i] = cardOrder[i - 1];
      cards[cardOrder[i]].idx = i;
    }
  }
  cardOrder[card.idx + di] = card.key;
  card.idx += di;
  renderCards();
}

function renderCards() {
  svg.selectAll('.card').transition()
    .delay(d => d.idx * 5)
    .filter(d => !d.dragging)
    .attr('transform', d =>
      `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`);
}

function dragstarted(d) {
  d.dragging = true;
  currentEvent.sourceEvent.preventDefault();
  select(this).style('filter', 'url(#shadow)');
}

function dragged(d) {
  d.dx += currentEvent.dx;
  d.dy += currentEvent.dy;
  if (d.dx > 28) {
    d.dx -= 48;
    moveCard(d, 1);
  } else if (d.dx < -28) {
    d.dx += 48;
    moveCard(d, -1);
  }
  if (d.dy > 34) {
    d.dy -= 60;
    moveCard(d, 9);
  } else if (d.dy < -34) {
    d.dy += 60;
    moveCard(d, -9);
  }
  select(this).attr('transform', d =>
    `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`);
}

function dragended(d) {
  d.dx = 0;
  d.dy = 0;
  d.dragging = false;
  select(this).style('filter', null);
  renderCards();
  const message = codeck.decode(cardOrder);
  messageInput.node().value = message.trim().toUpperCase();
  cleanedMessageSpan.classed('hide', true);
}

function showCardsInit() {
  svg.selectAll('.card')
    .data(Object.values(cards), card => card.key)
    .enter().append('text')
      .attr('class', 'card')
      .attr('transform', 'translate(0, 0)')
      .text(card => card.key)
      .attr('y', 60)
      .attr('fill', d => (floor(d.idx / 13) % 2 !== 0) ? 'red' : 'black')
      .call(drag()
        .on('start', dragstarted)
        .on('drag', dragged)
        .on('end', dragended));
  renderCards();
}

setTimeout(showCardsInit, 100);

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('worker.js');
  });
}
<|endoftext|>


<commit_before>/**
 * @file bastionLog event
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

/**
 * @param {object} Bastion The Bastion Discord client object
 * @param {string} event The event's name
 * @param {Guild} guild The guild object which triggered this event
 * @returns {void}
 */
module.exports = (Bastion, event, guild) => {
  if (!Bastion.ping) {
    throw 'Invalid Bastion Discord client object';
  }
  if (typeof event !== 'string') {
    throw 'Event name should be a string';
  }

  Bastion.db.get('SELECT log, logChannelID FROM bastionSettings').
    then(bastionSettings => {
      if (!bastionSettings) return;

      let log = (bastionSettings.log === 'true');
      if (!log) return;

      let logChannelID = bastionSettings.logChannelID,
        logChannel = Bastion.channels.get(logChannelID);

      if (!logChannel) return;

      let color,
        logData = [
          {
            name: 'Server Name',
            value: guild.name,
            inline: true
          },
          {
            name: 'Server ID',
            value: guild.id,
            inline: true
          },
          {
            name: 'Server Owner',
            value: guild.owner.user.tag,
            inline: true
          },
          {
            name: 'Server Owner ID',
            value: guild.ownerID,
            inline: true
          }
        ];

      switch (event) {
        case 'guildCreate':
          event = 'Joined Server';
          color = Bastion.colors.green;
          break;

        case 'guildDelete':
          event = 'Left Server';
          color = Bastion.colors.red;
          break;

        default:
          return Bastion.log.error(`Bastion logging is not present for ${event} event.`);
      }

      logChannel.send({
        embed: {
          color: color,
          title: event,
          fields: logData,
          timestamp: new Date()
        }
      }).catch(e => {
        Bastion.log.error(e);
      });
    }).catch(e => {
      Bastion.log.error(e);
    });
};
<commit_msg>Added guild icon to bastionLog event<commit_after>/**
 * @file bastionLog event
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

/**
 * @param {object} Bastion The Bastion Discord client object
 * @param {string} event The event's name
 * @param {Guild} guild The guild object which triggered this event
 * @returns {void}
 */
module.exports = (Bastion, event, guild) => {
  if (!Bastion.ping) {
    throw 'Invalid Bastion Discord client object';
  }
  if (typeof event !== 'string') {
    throw 'Event name should be a string';
  }

  Bastion.db.get('SELECT log, logChannelID FROM bastionSettings').
    then(bastionSettings => {
      if (!bastionSettings) return;

      let log = (bastionSettings.log === 'true');
      if (!log) return;

      let logChannelID = bastionSettings.logChannelID,
        logChannel = Bastion.channels.get(logChannelID);

      if (!logChannel) return;

      let color, guildIcon = guild.iconURL || 'https://discordapp.com/assets/2c21aeda16de354ba5334551a883b481.png',
        logData = [
          {
            name: 'Server Name',
            value: guild.name,
            inline: true
          },
          {
            name: 'Server ID',
            value: guild.id,
            inline: true
          },
          {
            name: 'Server Owner',
            value: guild.owner.user.tag,
            inline: true
          },
          {
            name: 'Server Owner ID',
            value: guild.ownerID,
            inline: true
          }
        ];

      switch (event) {
        case 'guildCreate':
          event = 'Joined Server';
          color = Bastion.colors.green;
          break;

        case 'guildDelete':
          event = 'Left Server';
          color = Bastion.colors.red;
          break;

        default:
          return Bastion.log.error(`Bastion logging is not present for ${event} event.`);
      }

      logChannel.send({
        embed: {
          color: color,
          title: event,
          fields: logData,
          thumbnail: {
            url: guildIcon
          },
          timestamp: new Date()
        }
      }).catch(e => {
        Bastion.log.error(e);
      });
    }).catch(e => {
      Bastion.log.error(e);
    });
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserify = require('gulp-browserify');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var gzip = require('gulp-gzip');
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var gulpif = require('gulp-if');
var es = require('event-stream');
var clean = require('gulp-clean');

gulp.task('check', function() {
	gulp.src(['lib/javascripts/**', '!lib/javascripts/graph_components/class.js'])
	.pipe(jshint())
	.pipe(jshint.reporter('default'))
});

gulp.task('dashboard', function() {
	var stream = gulp.src(['lib/javascripts/power_dashboard.js'])
	.pipe(browserify({
		insertGlobals : true,
		debug : false
	}))
	.pipe(concat('dashboard.js'))
	.pipe(gulp.dest('./tmp'))
	return stream;
});

gulp.task('sass', function () {
	var sassOpts = {includePaths: [require('node-bourbon').includePaths, './lib/stylesheets']};
	if(gulp.env.production) sassOpts.outputStyle = 'compressed';
	gulp.src(['./lib/stylesheets/application.scss'])
	.pipe(sass(sassOpts))
	.pipe(concat(gulp.env.production ? 'dashboard.min.css' : 'dashboard.css'))
	.pipe(gulp.dest('./build'));
});

gulp.task('images', function() {
	return gulp.src(['./lib/stylesheets/sprite.png'])
	.pipe(gulp.dest('./build'))
});

gulp.task('scripts', ['dashboard'], function() {
	var stream = gulp.src([
		'bower_components/underscore/underscore.js',
		'bower_components/backbone/backbone.js',
		'bower_components/jquery-tiny-pubsub/dist/ba-tiny-pubsub.js',
		'bower_components/json2/json2.js',
		'bower_components/sylvester/sylvester.src.js',
		'bower_components/d3/d3.js',
		'bower_components/tweenjs/src/Tween.js',
		'bower_components/moment/moment.js',
		'bower_components/modernizr/modernizr.js',
		'lib/javascripts/graph_components/class.js',
		'tmp/dashboard.js'
	])
	.pipe(concat(gulp.env.production ? 'dashboard.min.js' : 'dashboard.js'))
	.pipe(gulpif(gulp.env.production, uglify()))
	.pipe(gulp.dest('./build'));
	return stream;
});

gulp.task('scripts-with-cleanup', ['scripts'], function() {
	gulp.src(['./tmp/*.js'])
	.pipe(clean({force: true}))
});

gulp.task('default', function() {
	gulp.run('check');
	gulp.run('sass');
	gulp.run('images');
	gulp.run('scripts-with-cleanup');
});

gulp.task('watch', function() {
	gulp.watch([
		'lib/javascripts/**/*.js',
		'lib/stylesheets/**/*.scss',
		'lib/stylesheets.sprite.png'
	], function() {
		gulp.run('scripts-with-cleanup');
	});
});
<commit_msg>Add license to support file<commit_after>/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

var gulp = require('gulp');
var browserify = require('gulp-browserify');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var gzip = require('gulp-gzip');
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var gulpif = require('gulp-if');
var es = require('event-stream');
var clean = require('gulp-clean');

gulp.task('check', function() {
	gulp.src(['lib/javascripts/**', '!lib/javascripts/graph_components/class.js'])
	.pipe(jshint())
	.pipe(jshint.reporter('default'))
});

gulp.task('dashboard', function() {
	var stream = gulp.src(['lib/javascripts/power_dashboard.js'])
	.pipe(browserify({
		insertGlobals : true,
		debug : false
	}))
	.pipe(concat('dashboard.js'))
	.pipe(gulp.dest('./tmp'))
	return stream;
});

gulp.task('sass', function () {
	var sassOpts = {includePaths: [require('node-bourbon').includePaths, './lib/stylesheets']};
	if(gulp.env.production) sassOpts.outputStyle = 'compressed';
	gulp.src(['./lib/stylesheets/application.scss'])
	.pipe(sass(sassOpts))
	.pipe(concat(gulp.env.production ? 'dashboard.min.css' : 'dashboard.css'))
	.pipe(gulp.dest('./build'));
});

gulp.task('images', function() {
	return gulp.src(['./lib/stylesheets/sprite.png'])
	.pipe(gulp.dest('./build'))
});

gulp.task('scripts', ['dashboard'], function() {
	var stream = gulp.src([
		'bower_components/underscore/underscore.js',
		'bower_components/backbone/backbone.js',
		'bower_components/jquery-tiny-pubsub/dist/ba-tiny-pubsub.js',
		'bower_components/json2/json2.js',
		'bower_components/sylvester/sylvester.src.js',
		'bower_components/d3/d3.js',
		'bower_components/tweenjs/src/Tween.js',
		'bower_components/moment/moment.js',
		'bower_components/modernizr/modernizr.js',
		'lib/javascripts/graph_components/class.js',
		'tmp/dashboard.js'
	])
	.pipe(concat(gulp.env.production ? 'dashboard.min.js' : 'dashboard.js'))
	.pipe(gulpif(gulp.env.production, uglify()))
	.pipe(gulp.dest('./build'));
	return stream;
});

gulp.task('scripts-with-cleanup', ['scripts'], function() {
	gulp.src(['./tmp/*.js'])
	.pipe(clean({force: true}))
});

gulp.task('default', function() {
	gulp.run('check');
	gulp.run('sass');
	gulp.run('images');
	gulp.run('scripts-with-cleanup');
});

gulp.task('watch', function() {
	gulp.watch([
		'lib/javascripts/**/*.js',
		'lib/stylesheets/**/*.scss',
		'lib/stylesheets.sprite.png'
	], function() {
		gulp.run('scripts-with-cleanup');
	});
});
<|endoftext|>