<commit_before>'use strict';

/* Controllers */

angular.module(
        'myApp.controllers', []
    ).controller(
        'SchemaTableController',
        [
            '$scope', '$routeParams', '$log', '$q', '$filter', 'ngTableParams', 'utils', 'data',
            function ($scope, $routeParams, $log, $q, $filter, ngTableParams, utils, data) {
                $scope.rowCollection = [ ];
                $scope.statsColumnKey = '_stats_';
                $scope.columnCollection = [ ];
                $scope.ngTableParams = new ngTableParams(
                    {
                        page: 1,
                        count: 20,
                        filter: { }
                    },
                    {
                        counts: [10, 20, 30, 50, 100],
                        total: function() { return $scope.rowCollection.length; },
                        getData: function($defer, params) {
                            var filteredData = params.filter() ?
                                $filter('filter')($scope.rowCollection, params.filter()) :
                                $scope.rowCollection;
                            var orderedData = params.sorting() ?
                                $filter('orderBy')(filteredData, params.orderBy()) :
                                filteredData;

                            params.total(orderedData.length);
                            $defer.resolve(
                                orderedData.slice(
                                    (params.page() - 1) * params.count(),
                                    params.page() * params.count()
                                )
                            );
                        }
                    }
                );

                $scope.quizQueue = [ ];
                $scope.quizLog = [ ];
                $scope.quizIdx = 0;
                $scope.quizCurrent = function(){
                    return $scope.quizQueue[$scope.quizIdx];
                };
                $scope.changeSelection = function(row) {
                    $scope.selectedRows = _.filter(
                        $scope.rowCollection,
                        function(row) { return row.$selected; }
                    );
                };
                $scope.selectedRows = [ ];
                $scope.startQuiz = function() { $log.warn('$scope.startQuiz() not valid to be called'); };
                $scope.nextInput = function() { $log.warn('$scope.nextInput() not valid to be called'); };

                data.schemaMapPromise.then(
                    function (schemaMap) {
                        var schema = schemaMap[$routeParams.schemaId]; // TODO: recover from injecting rogue values

                        $scope.schema = schema;

                        var idCol = _.find(
                            schema.columns,
                            function(col) {
                                return col.columnType == 'id';
                            }
                        );

                        var inputCols =
                            _.filter(
                                schema.columns,
                                function (col) {
                                    return col.columnType == 'input';
                                }
                            );

                        var lcsLevels = [0, 1, 2, 3, 5, 8, 13, 100];

                        var emptyRowStats = function() {
                            return _.object(
                                _.map(
                                    inputCols,
                                    function(col) {
                                        return [col.id, _.map(lcsLevels, function () { return 0; })]
                                    }
                                )
                            );
                        };

                        var schemaStatsJson = window.localStorage[$routeParams.schemaId];
                        var schemaStats = angular.fromJson(schemaStatsJson ? schemaStatsJson : {});
                        function statsMapForRow(row) {
                            if (
                                !_.has(schemaStats, row[idCol.id]) ||
                                    !_.every(
                                        inputCols,
                                        function (col) {
                                            var stats = schemaStats[row[idCol.id]];
                                            return _.has(stats, col.id) &&
                                                _.isArray(stats[col.id]) &&
                                                lcsLevels.length == stats[col.id].length;
                                        }
                                    )
                                ) {
                                schemaStats[row[idCol.id]] = emptyRowStats();
                            }

                            return schemaStats[row[idCol.id]];
                        }
                        function statsForRow(row) {
                            return _.reduce(
                                _.pluck(
                                    _.pairs(
                                        statsMapForRow(row)
                                    ),
                                    "1"
                                ),
                                function(res, cur) {
                                    return _.map(
                                        _.zip(res, cur),
                                        function(arr) { return _.min(arr); }
                                    );
                                }
                            );
                        }
                        function statsForCol(row, inputCol) {
                            return statsMapForRow(row)[inputCol.id];
                        }
                        function statsObj(statsArr) {
                            var statsArrClone = _(statsArr).map(function(v) { return v; });
                            var correct =
                                _(statsArrClone).map(function(v, i, a) { return i == 0 ? v : v - a[i-1];});
                            var tries =
                                _(statsArrClone).last();
                            var triesWeighted =
                                _.chain(correct).map(
                                    function (v, i) {
                                        return v * Math.pow(0.8, i);
                                    }
                                ).reduce(
                                    function (a, b) {
                                        return a + b;
                                    }
                                ).value();
                            return {
                                stats: statsArrClone,
                                tries: tries,
                                correct: correct,
                                weight: tries > 0 ? triesWeighted / tries : 0,
                                stripes: tries <= 0 ? [] :
                                    _(correct).map(function (t, i) { return { width: t / tries, index: i }; })
                            };
                        }
                        function patchStatsObj(rowObj) {
                            var statsVal = statsObj(statsForRow(rowObj));
                            return _.extend(
                                rowObj,
                                _.object(
                                    [$scope.statsColumnKey, $scope.statsColumnKey + "weight_"],
                                    [statsVal, statsVal.weight]
                                )
                            )
                        }

                        var columnKeys = schema.columns.map(
                            function(col) { return col.id; }
                        );

                        $scope.rowCollection =
                            schema.data.map(function (row) {
                                return patchStatsObj(_.object(columnKeys, row));
                            });

                        function isColumnGreedy(col) {
                            return col.width.indexOf("+") >= 0;
                        }
                        var greedyColumnCount =
                            schema.columns.filter(isColumnGreedy).length;

                        $scope.columnCollection =
                            [
                                {
                                    visible: true,
                                    field: $scope.statsColumnKey,
                                    title: 'Stats',
                                    sortable: $scope.statsColumnKey + "weight_",
                                    filter: _.object([$scope.statsColumnKey + "weight_"], ['text']),
                                    cellClass: 'schemaTable_category',
                                    colStyle: {
                                        'max-width': '3em',
                                        'width': '3em'
                                    }
                                }
                            ].concat(
                                schema.columns.map(
                                    function(col) {
                                        var cellClasses = col.cellClassShort.split(/ +/);
                                        cellClasses.push(col.columnType);
                                        var colDef = {
                                            visible: true,
                                            field: col.id,
                                            title: col.name,
                                            sortable: col.id,
                                            filter: _.object([col.id], ['text']),
                                            cellClass: cellClasses.map(function(cc) { return 'schemaTable_' + cc;}).join(' ')
                                        };

                                        var colStyleObj = {};
                                        if (isColumnGreedy(col)) {
                                            colStyleObj = {
                                                'min-width': '' + parseInt(col.width) + 'px',
                                                'width': Math.ceil(100.0 / greedyColumnCount) + "%"
                                            };
                                        } else {
                                            colStyleObj = {
                                                'max-width': '' + parseInt(col.width) + 'px',
                                                'width': '' + parseInt(col.width) + 'px'
                                            };
                                        }
                                        colDef.colStyle = colStyleObj;
                                        return colDef;
                                    }
                                )
                            );

                        $scope.ngTableParams.sorting(idCol.id, 'asc');
                        $scope.ngTableParams.reload();

                        $scope.startQuiz = function() {
                            var selectedData =
                                _.flatten(
                                    _.map(
                                        $scope.selectedRows,
                                        function(row) {
                                            var first = inputCols[0];
                                            var lcpLen =
                                                _.min(
                                                    _.map(
                                                        _.rest(inputCols),
                                                        function(col) {
                                                            return utils.strLCP(row[first.id], row[col.id]);
                                                        }
                                                    )
                                                );
                                            return _.map(
                                                inputCols,
                                                function (col) {
                                                    return {
                                                        id: row[idCol.id],
                                                        inputCol: col,
                                                        expected: row[col.id],
                                                        actual: inputCols.length > 1 ?
                                                            row[col.id].substring(0, _.random(_.max([0, lcpLen-1]))) :
                                                            '',
                                                        stats: statsForCol(row, col),
                                                        editDist: function() {
                                                            return utils.editDist(this.actual, this.expected);
                                                        },
                                                        editDistCss: function() {
                                                            var editDistVal = this.editDist();
                                                            return -1 + _.reduce(
                                                                lcsLevels,
                                                                function (memo, elem) {
                                                                    return editDistVal >= elem ? memo + 1 : memo;
                                                                },
                                                                0
                                                            );
                                                        }
                                                    };
                                                }
                                            );
                                        }
                                    )
                                );

                            $scope.quizLog = [];
                            $scope.quizQueue = selectedData;
                            $scope.quizIdx = _.random(0, selectedData.length - 1);

                            $scope.nextInput = function() {
                                var quizCurrent = $scope.quizCurrent();
                                var quizCurrentDist = quizCurrent.editDist();
                                quizCurrent.stats = _(quizCurrent.stats).map(
                                    function(count, idx) {
                                        return count + (lcsLevels[idx] >= quizCurrentDist ? 1 : 0);
                                    }
                                );
                                $scope.quizLog.push(quizCurrent);
                                $scope.quizQueue.splice($scope.quizIdx, 1);
                                $scope.quizIdx = _.random(0, $scope.quizQueue.length - 1);

                                if ($scope.quizQueue.length == 0) {
                                    _($scope.quizLog).each(
                                        function(quiz) {
                                            schemaStats[quiz.id][quiz.inputCol.id] = quiz.stats;
                                        }
                                    );
                                    //  re-set all relevant fields into tabular data
                                    _.chain($scope.quizLog).map(
                                        function(quiz) { return quiz.id; }
                                    ).uniq().each(
                                        function(rowId) {
                                            _.chain($scope.rowCollection).filter(
                                                function(row) { return row[idCol.id] == rowId; }
                                            ).each(
                                                function(row){
                                                    _.extend(
                                                        row,
                                                        patchStatsObj(row)
                                                    )
                                                }
                                            );
                                        }
                                    );

                                    window.localStorage[$routeParams.schemaId] = angular.toJson(schemaStats);
                                }
                            }
                        };
                    }
                );
            }
        ]
    );
<commit_msg>de-selecting correct answers<commit_after>'use strict';

/* Controllers */

angular.module(
        'myApp.controllers', []
    ).controller(
        'SchemaTableController',
        [
            '$scope', '$routeParams', '$log', '$q', '$filter', 'ngTableParams', 'utils', 'data',
            function ($scope, $routeParams, $log, $q, $filter, ngTableParams, utils, data) {
                $scope.rowCollection = [ ];
                $scope.statsColumnKey = '_stats_';
                $scope.columnCollection = [ ];
                $scope.ngTableParams = new ngTableParams(
                    {
                        page: 1,
                        count: 20,
                        filter: { }
                    },
                    {
                        counts: [10, 20, 30, 50, 100],
                        total: function() { return $scope.rowCollection.length; },
                        getData: function($defer, params) {
                            var filteredData = params.filter() ?
                                $filter('filter')($scope.rowCollection, params.filter()) :
                                $scope.rowCollection;
                            var orderedData = params.sorting() ?
                                $filter('orderBy')(filteredData, params.orderBy()) :
                                filteredData;

                            params.total(orderedData.length);
                            $defer.resolve(
                                orderedData.slice(
                                    (params.page() - 1) * params.count(),
                                    params.page() * params.count()
                                )
                            );
                        }
                    }
                );

                $scope.quizQueue = [ ];
                $scope.quizLog = [ ];
                $scope.quizIdx = 0;
                $scope.quizCurrent = function(){
                    return $scope.quizQueue[$scope.quizIdx];
                };
                $scope.changeSelection = function(row) {
                    $scope.selectedRows = _.filter(
                        $scope.rowCollection,
                        function(row) { return row.$selected; }
                    );
                };
                $scope.selectedRows = [ ];
                $scope.startQuiz = function() { $log.warn('$scope.startQuiz() not valid to be called'); };
                $scope.nextInput = function() { $log.warn('$scope.nextInput() not valid to be called'); };

                data.schemaMapPromise.then(
                    function (schemaMap) {
                        var schema = schemaMap[$routeParams.schemaId]; // TODO: recover from injecting rogue values

                        $scope.schema = schema;

                        var idCol = _.find(
                            schema.columns,
                            function(col) {
                                return col.columnType == 'id';
                            }
                        );

                        var inputCols =
                            _.filter(
                                schema.columns,
                                function (col) {
                                    return col.columnType == 'input';
                                }
                            );

                        var lcsLevels = [0, 1, 2, 3, 5, 8, 13, 100];

                        var emptyRowStats = function() {
                            return _.object(
                                _.map(
                                    inputCols,
                                    function(col) {
                                        return [col.id, _.map(lcsLevels, function () { return 0; })]
                                    }
                                )
                            );
                        };

                        var schemaStatsJson = window.localStorage[$routeParams.schemaId];
                        var schemaStats = angular.fromJson(schemaStatsJson ? schemaStatsJson : {});
                        function statsMapForRow(row) {
                            if (
                                !_.has(schemaStats, row[idCol.id]) ||
                                    !_.every(
                                        inputCols,
                                        function (col) {
                                            var stats = schemaStats[row[idCol.id]];
                                            return _.has(stats, col.id) &&
                                                _.isArray(stats[col.id]) &&
                                                lcsLevels.length == stats[col.id].length;
                                        }
                                    )
                                ) {
                                schemaStats[row[idCol.id]] = emptyRowStats();
                            }

                            return schemaStats[row[idCol.id]];
                        }
                        function statsForRow(row) {
                            return _.reduce(
                                _.pluck(
                                    _.pairs(
                                        statsMapForRow(row)
                                    ),
                                    "1"
                                ),
                                function(res, cur) {
                                    return _.map(
                                        _.zip(res, cur),
                                        function(arr) { return _.min(arr); }
                                    );
                                }
                            );
                        }
                        function statsForCol(row, inputCol) {
                            return statsMapForRow(row)[inputCol.id];
                        }
                        function statsObj(statsArr) {
                            var statsArrClone = _(statsArr).map(function(v) { return v; });
                            var correct =
                                _(statsArrClone).map(function(v, i, a) { return i == 0 ? v : v - a[i-1];});
                            var tries =
                                _(statsArrClone).last();
                            var triesWeighted =
                                _.chain(correct).map(
                                    function (v, i) {
                                        return v * Math.pow(0.8, i);
                                    }
                                ).reduce(
                                    function (a, b) {
                                        return a + b;
                                    }
                                ).value();
                            return {
                                stats: statsArrClone,
                                tries: tries,
                                correct: correct,
                                weight: tries > 0 ? triesWeighted / tries : 0,
                                stripes: tries <= 0 ? [] :
                                    _(correct).map(function (t, i) { return { width: t / tries, index: i }; })
                            };
                        }
                        function patchStatsObj(rowObj) {
                            var statsVal = statsObj(statsForRow(rowObj));
                            return _.extend(
                                rowObj,
                                _.object(
                                    [$scope.statsColumnKey, $scope.statsColumnKey + "weight_"],
                                    [statsVal, statsVal.weight]
                                )
                            )
                        }

                        var columnKeys = schema.columns.map(
                            function(col) { return col.id; }
                        );

                        $scope.rowCollection =
                            schema.data.map(function (row) {
                                return patchStatsObj(_.object(columnKeys, row));
                            });

                        function isColumnGreedy(col) {
                            return col.width.indexOf("+") >= 0;
                        }
                        var greedyColumnCount =
                            schema.columns.filter(isColumnGreedy).length;

                        $scope.columnCollection =
                            [
                                {
                                    visible: true,
                                    field: $scope.statsColumnKey,
                                    title: 'Stats',
                                    sortable: $scope.statsColumnKey + "weight_",
                                    filter: _.object([$scope.statsColumnKey + "weight_"], ['text']),
                                    cellClass: 'schemaTable_category',
                                    colStyle: {
                                        'max-width': '3em',
                                        'width': '3em'
                                    }
                                }
                            ].concat(
                                schema.columns.map(
                                    function(col) {
                                        var cellClasses = col.cellClassShort.split(/ +/);
                                        cellClasses.push(col.columnType);
                                        var colDef = {
                                            visible: true,
                                            field: col.id,
                                            title: col.name,
                                            sortable: col.id,
                                            filter: _.object([col.id], ['text']),
                                            cellClass: cellClasses.map(function(cc) { return 'schemaTable_' + cc;}).join(' ')
                                        };

                                        var colStyleObj = {};
                                        if (isColumnGreedy(col)) {
                                            colStyleObj = {
                                                'min-width': '' + parseInt(col.width) + 'px',
                                                'width': Math.ceil(100.0 / greedyColumnCount) + "%"
                                            };
                                        } else {
                                            colStyleObj = {
                                                'max-width': '' + parseInt(col.width) + 'px',
                                                'width': '' + parseInt(col.width) + 'px'
                                            };
                                        }
                                        colDef.colStyle = colStyleObj;
                                        return colDef;
                                    }
                                )
                            );

                        $scope.ngTableParams.sorting(idCol.id, 'asc');
                        $scope.ngTableParams.reload();

                        $scope.startQuiz = function() {
                            var selectedData =
                                _.flatten(
                                    _.map(
                                        $scope.selectedRows,
                                        function(row) {
                                            var first = inputCols[0];
                                            var lcpLen =
                                                _.min(
                                                    _.map(
                                                        _.rest(inputCols),
                                                        function(col) {
                                                            return utils.strLCP(row[first.id], row[col.id]);
                                                        }
                                                    )
                                                );
                                            return _.map(
                                                inputCols,
                                                function (col) {
                                                    return {
                                                        id: row[idCol.id],
                                                        inputCol: col,
                                                        expected: row[col.id],
                                                        actual: inputCols.length > 1 ?
                                                            row[col.id].substring(0, _.random(_.max([0, lcpLen-1]))) :
                                                            '',
                                                        stats: statsForCol(row, col),
                                                        editDist: function() {
                                                            return utils.editDist(this.actual, this.expected);
                                                        },
                                                        editDistCss: function() {
                                                            var editDistVal = this.editDist();
                                                            return -1 + _.reduce(
                                                                lcsLevels,
                                                                function (memo, elem) {
                                                                    return editDistVal >= elem ? memo + 1 : memo;
                                                                },
                                                                0
                                                            );
                                                        }
                                                    };
                                                }
                                            );
                                        }
                                    )
                                );

                            $scope.quizLog = [];
                            $scope.quizQueue = selectedData;
                            $scope.quizIdx = _.random(0, selectedData.length - 1);

                            $scope.nextInput = function() {
                                var quizCurrent = $scope.quizCurrent();
                                var quizCurrentDist = quizCurrent.editDist();
                                quizCurrent.stats = _(quizCurrent.stats).map(
                                    function(count, idx) {
                                        return count + (lcsLevels[idx] >= quizCurrentDist ? 1 : 0);
                                    }
                                );
                                $scope.quizLog.push(quizCurrent);
                                $scope.quizQueue.splice($scope.quizIdx, 1);
                                $scope.quizIdx = _.random(0, $scope.quizQueue.length - 1);

                                if ($scope.quizQueue.length == 0) {
                                    _($scope.quizLog).each(
                                        function(quiz) {
                                            schemaStats[quiz.id][quiz.inputCol.id] = quiz.stats;
                                        }
                                    );
                                    //  re-set all relevant fields into tabular data
                                    _.chain($scope.quizLog).map(
                                        function(quiz) { return quiz.id; }
                                    ).uniq().each(
                                        function(rowId) {
                                            _.chain($scope.rowCollection).filter(
                                                function(row) { return row[idCol.id] == rowId; }
                                            ).each(
                                                function(row){
                                                    _.extend(
                                                        row,
                                                        patchStatsObj(row)
                                                    );
                                                    var allCorrectForRow =
                                                        _.chain($scope.quizLog).filter(
                                                            function(quiz) {
                                                                return quiz.id == rowId;
                                                            }
                                                        ).every(
                                                            function(quiz) {
                                                                return quiz.expected == quiz.actual;
                                                            }
                                                        ).value();
                                                    row.$selected = row.$selected && !allCorrectForRow;
                                                }
                                            );
                                        }
                                    );

                                    window.localStorage[$routeParams.schemaId] = angular.toJson(schemaStats);
                                }
                            }
                        };
                    }
                );
            }
        ]
    );
<|endoftext|>


<commit_before>const libxmljs = require('libxmljs');
const fetch = require('node-fetch');
const E2eHelpers = require('../../../testing/e2e/helpers');
const Timeouts = require('../../../testing/e2e/timeouts.js');

const SITEMAP_URL = `${E2eHelpers.baseUrl}/sitemap.xml`;
const SITEMAP_LOC_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9';
const DOMAIN_REGEX = /http[s]?:\/\/(.*?)\//;

function sitemapURLs() {
  return fetch(SITEMAP_URL)
    .then(res => res.text())
    .then(body => libxmljs.parseXml(body))
    .then(doc =>
      doc
        .find('//xmlns:loc', SITEMAP_LOC_NS)
        .map(n => n.text().replace(DOMAIN_REGEX, `${E2eHelpers.baseUrl}/`))
        .filter(url => !url.endsWith('auth/login/callback/'))
        .filter(url => !/.*opt-out-information-sharing.*/.test(url)),
    )
    .then(urls => {
      const onlyTest508Rules = [
        // 404 page contains 2 search auto-suggest elements with the same element ID,
        // which violates WCAG 2.0 standards. This element id is referenced by
        // https://search.usa.gov/assets/sayt_loader_libs.js, so if we change the ID
        // of one of the elements, search won't work.
        '/404.html',
        // This is here because aXe bug flags the custom select component on this page
        '/facilities/',
        // This is here because an aXe bug flags the autosuggest component on this page
        '/gi-bill-comparison-tool/',
      ];
      // Whitelist of URLs to only test against the 'section508' rule set and not
      // the stricter 'wcag2a' rule set. For each URL added to this list, please
      // add a comment explaining why it cannot be tested against stricter rules.
      return { urls, onlyTest508Rules };
    });
}

function runTests(client, segment, only508List) {
  segment.forEach(url => {
    const only508 = only508List.filter(path => url.endsWith(path)).length > 0;
    client
      .perform(() => {
        // eslint-disable-next-line no-console
        console.log(url);
      })
      .url(url)
      .waitForElementVisible('body', Timeouts.normal)
      .axeCheck(
        'document',
        only508 ? { scope: url, rules: ['section508'] } : { scope: url },
      );
  });
}

module.exports = { runTests, sitemapURLs };
<commit_msg>update sitemap url (#8735)<commit_after>const libxmljs = require('libxmljs');
const fetch = require('node-fetch');
const E2eHelpers = require('../../../testing/e2e/helpers');
const Timeouts = require('../../../testing/e2e/timeouts.js');

const SITEMAP_URL = `${E2eHelpers.baseUrl}/sitemap-dynamic.xml`;
const SITEMAP_LOC_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9';
const DOMAIN_REGEX = /http[s]?:\/\/(.*?)\//;

function sitemapURLs() {
  return fetch(SITEMAP_URL)
    .then(res => res.text())
    .then(body => libxmljs.parseXml(body))
    .then(doc =>
      doc
        .find('//xmlns:loc', SITEMAP_LOC_NS)
        .map(n => n.text().replace(DOMAIN_REGEX, `${E2eHelpers.baseUrl}/`))
        .filter(url => !url.endsWith('auth/login/callback/'))
        .filter(url => !/.*opt-out-information-sharing.*/.test(url)),
    )
    .then(urls => {
      const onlyTest508Rules = [
        // 404 page contains 2 search auto-suggest elements with the same element ID,
        // which violates WCAG 2.0 standards. This element id is referenced by
        // https://search.usa.gov/assets/sayt_loader_libs.js, so if we change the ID
        // of one of the elements, search won't work.
        '/404.html',
        // This is here because aXe bug flags the custom select component on this page
        '/facilities/',
        // This is here because an aXe bug flags the autosuggest component on this page
        '/gi-bill-comparison-tool/',
      ];
      // Whitelist of URLs to only test against the 'section508' rule set and not
      // the stricter 'wcag2a' rule set. For each URL added to this list, please
      // add a comment explaining why it cannot be tested against stricter rules.
      return { urls, onlyTest508Rules };
    });
}

function runTests(client, segment, only508List) {
  segment.forEach(url => {
    const only508 = only508List.filter(path => url.endsWith(path)).length > 0;
    client
      .perform(() => {
        // eslint-disable-next-line no-console
        console.log(url);
      })
      .url(url)
      .waitForElementVisible('body', Timeouts.normal)
      .axeCheck(
        'document',
        only508 ? { scope: url, rules: ['section508'] } : { scope: url },
      );
  });
}

module.exports = { runTests, sitemapURLs };
<|endoftext|>


<commit_before>/**
 * Handle facet actions (add/remove facet filter from url) and redirect to that url
 * @param string action Accepted value "remove" / "add" what needs to be done with the facet
 * @param string groupName The facet group name used as facet group name in filter query
 * @param string facetValue The facet value that needs to be added or removed
 * @param string baseUrl The url to redirect to, optional parameter
 **/
var handleFacet = function(action, groupName, facetValue, baseUrl) {
  //Will be done later using smart tags / q boosts
  //TODO: Fix this and make it possible to add or remove tags
  var url = $.url(window.location.href);

  var newUrl = (typeof baseUrl !== "undefined") ? baseUrl : url.attr("path");
  var paramId = 0;
  var params = $.url(window.location.href).param();

  if (action == "add") {
    if (typeof params["ff"] === "undefined") {
      params["ff"] = new Object();
    }

    if($.inArray(groupName + "[" + facetValue + "]", params["ff"]) == -1){
      params["ff"].push(groupName + "[" + facetValue + "]");
    }
  } else {
    delete params["ff"][groupName];
  }

  //replacing [] with '' ff=publication-type%5BCase+Reports%5D

  //newUrl += ($.param(params)) ? "?" + ($.param(params)) : "";
  newUrl += "?ff="+groupName + "[" + facetValue + "]";
  console.log(newUrl);
  //window.location.href = newUrl;
  //ReloadMain content doesn't work because jquery doesn't serialize the params correctly'
  //reloadMainContent(params, newUrl);
};

/** Handle events on clickable tags **/
var bindClickableTagsEvents = function(){
  $("#results .label-tag.clickable").unbind();
  $("#results .label-tag.clickable").click(function() {
    console.log("Adding condition "+$(this).attr("data-filter"));
    var input = $("<input type='hidden'/>");
    input.attr("name", $(this).attr("data-condition"));
    input.attr("value", $(this).attr("data-condition-value"));
    $('form').append(input);
    $('form').submit();
    return false;
  });

}

/** Handle autocomplete on searchField **/
var bindSearchAutocompleteEvent = function() {

  var cache_autocomplete = {};
  $("#edismax-query").autocomplete({
    minLength : 2,
    select : function(event, ui) {
      if (ui.item) {
        $('#edismax-query').val(ui.item.value);
        $("form").submit();
      }
    },
    source : function(request, response) {
      var term = request.term;
      if (term in cache_autocomplete) {

        var data = cache_autocomplete[term]
        response($.map(data.suggestions, function(item) {
          return {
            label : item,
            value : item
          }
        }));
        return;
      }

      $.ajax({
        url : $("#edismax-query").attr("data-autocomplete-url"),
        dataType : 'json',
        data : {
          wt : 'json',
          'json.nl' : 'arrarr',
          q : request.term,
          'terms.sort' : 'index',
          'terms.limit' : 5
        },
        jsonp : 'json.wrf',
        success : function(data) {
          // Caching response
          cache_autocomplete[term] = data;
          response($.map(data.suggestions, function(item) {
            return {
              label : item,
              value : item
            }
          }));
        }
      });
    }
  });
};

/**
 * Bind all events to facets (clicks, show more, ... The function is called each
 * time the facet list is refreshed.
 */
var bindFacetEvents = function() {

  // Show more show / show less action on the UL
  $('ul.facet-list')
      .each(
          function() {
            // Hide all facets greater than 3 and then display selected facets
            $(this).children('li:gt(3)').hide();
            $(this).children('li.selected').show();
            $(this).children('li.button').show();

            // If some facets are hidden, we add a show more button
            if ($(this).children('li:hidden').length > 0) {
              // When facets aren't refresh, we need to ensure we
              // don't add show more button one more time'
              if (!$(this).hasClass("show-more-enabled")) {
                $(this).addClass("show-more-enabled");
                $(this)
                    .append(
                        '
Show more...
');
              }
            }
          });

  // Click event on show more button
  $('.show-more').unbind();
  $('.show-more')
      .click(
          function(e) {
            e.preventDefault();

            if ($(this).hasClass("less")) {
              var list = $(this).parents('ul.facet-list').children('li')
                  .filter('li:gt(3)').filter("li:not(.selected)").filter(
                      "li:not(.button)");

              // $.cookie($(this).prev('ul').attr("id"), 0);
              $(this).html("Show more...");
              $(this).removeClass("less");
              list.slideUp();
            } else {

              var list = $(this).parents('ul.facet-list').children('li:hidden');
              $(this).html("Show less...");
              $(this).addClass("less");
              // isTrigger is only defined when click is simulated
              if (typeof (e.isTrigger) === 'undefined') {
                list.slideDown();
              } else {
                list.show(); // Display the list faster
              }

              // $.cookie($(this).prev('ul').attr("id"), 1);
            }
          });

  $('ul.facet-list').each(function() {
    // Triggers click if required
    /*
     * if ($.cookie($(this).attr('id')) == 1) {
     * $(this).next("a.show-more").click(); }
     */
  });
};

var bindResultPageEvents = function() {

  // Bind all page events
  bindFacetEvents();
  bindSearchAutocompleteEvent();
  bindClickableTagsEvents();
};

$(document).ready(function() {
  // Cleans all params that are not set.
  $('form#searchForm').submit(function() {
    $(':input', this).each(function() {
      this.disabled = !($(this).val());
    });
  });

  bindResultPageEvents();

  // Enable AJAX tabs in Bootstrap
  $('[data-toggle="tabajax"]').click(function(e) {
    e.preventDefault()
    var loadurl = $(this).attr('href')
    var targ = $(this).attr('data-target')
    $.get(loadurl, function(data) {
      $(targ).html(data)

    });
    $(this).tab('show')
  });
});<commit_msg>Can Remove tag from UI<commit_after>/**
 * Handle facet actions (add/remove facet filter from url) and redirect to that url
 * @param string action Accepted value "remove" / "add" what needs to be done with the facet
 * @param string groupName The facet group name used as facet group name in filter query
 * @param string facetValue The facet value that needs to be added or removed
 * @param string baseUrl The url to redirect to, optional parameter
 **/
var handleFacet = function(action, groupName, facetValue, baseUrl) {
  //Will be done later using smart tags / q boosts
  //TODO: Fix this and make it possible to add or remove tags
  var url = $.url(window.location.href);

  var newUrl = (typeof baseUrl !== "undefined") ? baseUrl : url.attr("path");
  var paramId = 0;
  var params = $.url(window.location.href).param();

  if (action == "add") {
    if (typeof params["ff"] === "undefined") {
      params["ff"] = new Object();
    }

    if($.inArray(groupName + "[" + facetValue + "]", params["ff"]) == -1){
      params["ff"].push(groupName + "[" + facetValue + "]");
    }
  } else {
    delete params["ff"][groupName];
  }

  //replacing [] with '' ff=publication-type%5BCase+Reports%5D

  //newUrl += ($.param(params)) ? "?" + ($.param(params)) : "";
  newUrl += "?ff="+groupName + "[" + facetValue + "]";
  console.log(newUrl);
  //window.location.href = newUrl;
  //ReloadMain content doesn't work because jquery doesn't serialize the params correctly'
  //reloadMainContent(params, newUrl);
};

/** Handle events on clickable tags **/
var bindClickableTagsEvents = function(){
  $("#results .label-tag.clickable").unbind();
  $("#results .label-tag.clickable").click(function() {
    var tag = $(this);
    if($(this).hasClass("selected")){
        $('input[name=ff]').each(function(){
            if(tag.attr("data-condition-value").indexOf($(this).attr("value"))>-1){
                $(this).parent().remove();
            }
        });
    } else {
        console.log("Adding condition "+$(this).attr("data-filter"));
        var input = $("<input type='hidden'/>");
        input.attr("name", $(this).attr("data-condition"));
        input.attr("value", $(this).attr("data-condition-value"));
        $('form').append(input);
    }
    $('form').submit();
    return false;
  });

}

/** Handle autocomplete on searchField **/
var bindSearchAutocompleteEvent = function() {

  var cache_autocomplete = {};
  $("#edismax-query").autocomplete({
    minLength : 2,
    select : function(event, ui) {
      if (ui.item) {
        $('#edismax-query').val(ui.item.value);
        $("form").submit();
      }
    },
    source : function(request, response) {
      var term = request.term;
      if (term in cache_autocomplete) {

        var data = cache_autocomplete[term]
        response($.map(data.suggestions, function(item) {
          return {
            label : item,
            value : item
          }
        }));
        return;
      }

      $.ajax({
        url : $("#edismax-query").attr("data-autocomplete-url"),
        dataType : 'json',
        data : {
          wt : 'json',
          'json.nl' : 'arrarr',
          q : request.term,
          'terms.sort' : 'index',
          'terms.limit' : 5
        },
        jsonp : 'json.wrf',
        success : function(data) {
          // Caching response
          cache_autocomplete[term] = data;
          response($.map(data.suggestions, function(item) {
            return {
              label : item,
              value : item
            }
          }));
        }
      });
    }
  });
};

/**
 * Bind all events to facets (clicks, show more, ... The function is called each
 * time the facet list is refreshed.
 */
var bindFacetEvents = function() {

  // Show more show / show less action on the UL
  $('ul.facet-list')
      .each(
          function() {
            // Hide all facets greater than 3 and then display selected facets
            $(this).children('li:gt(3)').hide();
            $(this).children('li.selected').show();
            $(this).children('li.button').show();

            // If some facets are hidden, we add a show more button
            if ($(this).children('li:hidden').length > 0) {
              // When facets aren't refresh, we need to ensure we
              // don't add show more button one more time'
              if (!$(this).hasClass("show-more-enabled")) {
                $(this).addClass("show-more-enabled");
                $(this)
                    .append(
                        '
Show more...
');
              }
            }
          });

  // Click event on show more button
  $('.show-more').unbind();
  $('.show-more')
      .click(
          function(e) {
            e.preventDefault();

            if ($(this).hasClass("less")) {
              var list = $(this).parents('ul.facet-list').children('li')
                  .filter('li:gt(3)').filter("li:not(.selected)").filter(
                      "li:not(.button)");

              // $.cookie($(this).prev('ul').attr("id"), 0);
              $(this).html("Show more...");
              $(this).removeClass("less");
              list.slideUp();
            } else {

              var list = $(this).parents('ul.facet-list').children('li:hidden');
              $(this).html("Show less...");
              $(this).addClass("less");
              // isTrigger is only defined when click is simulated
              if (typeof (e.isTrigger) === 'undefined') {
                list.slideDown();
              } else {
                list.show(); // Display the list faster
              }

              // $.cookie($(this).prev('ul').attr("id"), 1);
            }
          });

  $('ul.facet-list').each(function() {
    // Triggers click if required
    /*
     * if ($.cookie($(this).attr('id')) == 1) {
     * $(this).next("a.show-more").click(); }
     */
  });
};

var bindResultPageEvents = function() {

  // Bind all page events
  bindFacetEvents();
  bindSearchAutocompleteEvent();
  bindClickableTagsEvents();
};

$(document).ready(function() {
  // Cleans all params that are not set.
  $('form#searchForm').submit(function() {
    $(':input', this).each(function() {
      this.disabled = !($(this).val());
    });
  });

  bindResultPageEvents();

  // Enable AJAX tabs in Bootstrap
  $('[data-toggle="tabajax"]').click(function(e) {
    e.preventDefault()
    var loadurl = $(this).attr('href')
    var targ = $(this).attr('data-target')
    $.get(loadurl, function(data) {
      $(targ).html(data)

    });
    $(this).tab('show')
  });
});<|endoftext|>


<commit_before>var hub     = require('hub');

var express = require('express');
var router  = express.Router();

router.get('/', function(req, res) {
    hub.mariaSqlClientRO.query('SELECT `id`,`name` FROM `tags`', function(err, rows) {
        if(err) {
            res.sendStatus(500);
            // TODO: Proper error handling
            return;
        }
        // TODO: concatenate the results to a nice JSON reply
        hub.mariaSqlClientRO.query('SELECT `id`,`name` FROM `types`', function(err, rows) {
            if(err) {
                res.sendStatus(500);
                // TODO: Proper error handling
                return;
            }
            // TODO: concatenate the results to a nice JSON reply
            res.sendStatus(200); // TODO: send out the reply here instead of a status code
        });
    });
});

module.exports = router;<commit_msg>return query results to client<commit_after>var hub     = require('hub');

var express = require('express');
var router  = express.Router();

router.get('/', function(req, res) {
    var meta = {};
    hub.mariaSqlClientRO.query('SELECT `id`,`name` FROM `tags`', function(err, rows) {
        if(err) {
            res.sendStatus(500);
            return;
        }

        meta.tags = rows;

        hub.mariaSqlClientRO.query('SELECT `id`,`name` FROM `types`', function(err, rows) {
            if(err) {
                res.sendStatus(500);
                return;
            }

            meta.types = rows;

            res.send(meta);
        });
    });
});

module.exports = router;<|endoftext|>


<commit_before>goog.provide('ol.control.ScaleLine');

goog.require('ol');
goog.require('ol.Object');
goog.require('ol.asserts');
goog.require('ol.control.Control');
goog.require('ol.control.ScaleLineUnits');
goog.require('ol.css');
goog.require('ol.events');
goog.require('ol.proj');
goog.require('ol.proj.Units');

/**
 * @classdesc
 * A control displaying rough y-axis distances, calculated for the center of the
 * viewport. For conformal projections (e.g. EPSG:3857, the default view
 * projection in OpenLayers), the scale is valid for all directions.
 * No scale line will be shown when the y-axis distance of a pixel at the
 * viewport center cannot be calculated in the view projection.
 * By default the scale line will show in the bottom left portion of the map,
 * but this can be changed by using the css selector `.ol-scale-line`.
 *
 * @constructor
 * @extends {ol.control.Control}
 * @param {olx.control.ScaleLineOptions=} opt_options Scale line options.
 * @api
 */
ol.control.ScaleLine = function(opt_options) {

  var options = opt_options ? opt_options : {};

  var className = options.className !== undefined ? options.className : 'ol-scale-line';

  /**
   * @private
   * @type {Element}
   */
  this.innerElement_ = document.createElement('DIV');
  this.innerElement_.className = className + '-inner';

  /**
   * @private
   * @type {Element}
   */
  this.element_ = document.createElement('DIV');
  this.element_.className = className + ' ' + ol.css.CLASS_UNSELECTABLE;
  this.element_.appendChild(this.innerElement_);

  /**
   * @private
   * @type {?olx.ViewState}
   */
  this.viewState_ = null;

  /**
   * @private
   * @type {number}
   */
  this.minWidth_ = options.minWidth !== undefined ? options.minWidth : 64;

  /**
   * @private
   * @type {boolean}
   */
  this.renderedVisible_ = false;

  /**
   * @private
   * @type {number|undefined}
   */
  this.renderedWidth_ = undefined;

  /**
   * @private
   * @type {string}
   */
  this.renderedHTML_ = '';

  var render = options.render ? options.render : ol.control.ScaleLine.render;

  ol.control.Control.call(this, {
    element: this.element_,
    render: render,
    target: options.target
  });

  ol.events.listen(
      this, ol.Object.getChangeEventType(ol.control.ScaleLine.Property_.UNITS),
      this.handleUnitsChanged_, this);

  this.setUnits(/** @type {ol.control.ScaleLineUnits} */ (options.units) ||
      ol.control.ScaleLineUnits.METRIC);

};
ol.inherits(ol.control.ScaleLine, ol.control.Control);

/**
 * @const
 * @type {Array.<number>}
 */
ol.control.ScaleLine.LEADING_DIGITS = [1, 2, 5];

/**
 * Return the units to use in the scale line.
 * @return {ol.control.ScaleLineUnits|undefined} The units to use in the scale
 *     line.
 * @observable
 * @api
 */
ol.control.ScaleLine.prototype.getUnits = function() {
  return /** @type {ol.control.ScaleLineUnits|undefined} */ (
      this.get(ol.control.ScaleLine.Property_.UNITS));
};

/**
 * Update the scale line element.
 * @param {ol.MapEvent} mapEvent Map event.
 * @this {ol.control.ScaleLine}
 * @api
 */
ol.control.ScaleLine.render = function(mapEvent) {
  var frameState = mapEvent.frameState;
  if (!frameState) {
    this.viewState_ = null;
  } else {
    this.viewState_ = frameState.viewState;
  }
  this.updateElement_();
};

/**
 * @private
 */
ol.control.ScaleLine.prototype.handleUnitsChanged_ = function() {
  this.updateElement_();
};

/**
 * Set the units to use in the scale line.
 * @param {ol.control.ScaleLineUnits} units The units to use in the scale line.
 * @observable
 * @api
 */
ol.control.ScaleLine.prototype.setUnits = function(units) {
  this.set(ol.control.ScaleLine.Property_.UNITS, units);
};

/**
 * @private
 */
ol.control.ScaleLine.prototype.updateElement_ = function() {
  var viewState = this.viewState_;

  if (!viewState) {
    if (this.renderedVisible_) {
      this.element_.style.display = 'none';
      this.renderedVisible_ = false;
    }
    return;
  }

  var center = viewState.center;
  var projection = viewState.projection;
  var metersPerUnit = projection.getMetersPerUnit();
  var pointResolution =
      ol.proj.getPointResolution(projection, viewState.resolution, center) *
      metersPerUnit;

  var nominalCount = this.minWidth_ * pointResolution;
  var suffix = '';
  var units = this.getUnits();
  if (units == ol.control.ScaleLineUnits.DEGREES) {
    var metersPerDegree = ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES];
    pointResolution /= metersPerDegree;
    if (nominalCount < metersPerDegree / 60) {
      suffix = '\u2033'; // seconds
      pointResolution *= 3600;
    } else if (nominalCount < metersPerDegree) {
      suffix = '\u2032'; // minutes
      pointResolution *= 60;
    } else {
      suffix = '\u00b0'; // degrees
    }
  } else if (units == ol.control.ScaleLineUnits.IMPERIAL) {
    if (nominalCount < 0.9144) {
      suffix = 'in';
      pointResolution /= 0.0254;
    } else if (nominalCount < 1609.344) {
      suffix = 'ft';
      pointResolution /= 0.3048;
    } else {
      suffix = 'mi';
      pointResolution /= 1609.344;
    }
  } else if (units == ol.control.ScaleLineUnits.NAUTICAL) {
    pointResolution /= 1852;
    suffix = 'nm';
  } else if (units == ol.control.ScaleLineUnits.METRIC) {
    if (nominalCount < 1) {
      suffix = 'mm';
      pointResolution *= 1000;
    } else if (nominalCount < 1000) {
      suffix = 'm';
    } else {
      suffix = 'km';
      pointResolution /= 1000;
    }
  } else if (units == ol.control.ScaleLineUnits.US) {
    if (nominalCount < 0.9144) {
      suffix = 'in';
      pointResolution *= 39.37;
    } else if (nominalCount < 1609.344) {
      suffix = 'ft';
      pointResolution /= 0.30480061;
    } else {
      suffix = 'mi';
      pointResolution /= 1609.3472;
    }
  } else {
    ol.asserts.assert(false, 33); // Invalid units
  }

  var i = 3 * Math.floor(
      Math.log(this.minWidth_ * pointResolution) / Math.log(10));
  var count, width;
  while (true) {
    count = ol.control.ScaleLine.LEADING_DIGITS[((i % 3) + 3) % 3] *
        Math.pow(10, Math.floor(i / 3));
    width = Math.round(count / pointResolution);
    if (isNaN(width)) {
      this.element_.style.display = 'none';
      this.renderedVisible_ = false;
      return;
    } else if (width >= this.minWidth_) {
      break;
    }
    ++i;
  }

  var html = count + ' ' + suffix;
  if (this.renderedHTML_ != html) {
    this.innerElement_.innerHTML = html;
    this.renderedHTML_ = html;
  }

  if (this.renderedWidth_ != width) {
    this.innerElement_.style.width = width + 'px';
    this.renderedWidth_ = width;
  }

  if (!this.renderedVisible_) {
    this.element_.style.display = '';
    this.renderedVisible_ = true;
  }

};

/**
 * @enum {string}
 * @private
 */
ol.control.ScaleLine.Property_ = {
  UNITS: 'units'
};
<commit_msg>Add support of micrometers to scaleline<commit_after>goog.provide('ol.control.ScaleLine');

goog.require('ol');
goog.require('ol.Object');
goog.require('ol.asserts');
goog.require('ol.control.Control');
goog.require('ol.control.ScaleLineUnits');
goog.require('ol.css');
goog.require('ol.events');
goog.require('ol.proj');
goog.require('ol.proj.Units');

/**
 * @classdesc
 * A control displaying rough y-axis distances, calculated for the center of the
 * viewport. For conformal projections (e.g. EPSG:3857, the default view
 * projection in OpenLayers), the scale is valid for all directions.
 * No scale line will be shown when the y-axis distance of a pixel at the
 * viewport center cannot be calculated in the view projection.
 * By default the scale line will show in the bottom left portion of the map,
 * but this can be changed by using the css selector `.ol-scale-line`.
 *
 * @constructor
 * @extends {ol.control.Control}
 * @param {olx.control.ScaleLineOptions=} opt_options Scale line options.
 * @api
 */
ol.control.ScaleLine = function(opt_options) {

  var options = opt_options ? opt_options : {};

  var className = options.className !== undefined ? options.className : 'ol-scale-line';

  /**
   * @private
   * @type {Element}
   */
  this.innerElement_ = document.createElement('DIV');
  this.innerElement_.className = className + '-inner';

  /**
   * @private
   * @type {Element}
   */
  this.element_ = document.createElement('DIV');
  this.element_.className = className + ' ' + ol.css.CLASS_UNSELECTABLE;
  this.element_.appendChild(this.innerElement_);

  /**
   * @private
   * @type {?olx.ViewState}
   */
  this.viewState_ = null;

  /**
   * @private
   * @type {number}
   */
  this.minWidth_ = options.minWidth !== undefined ? options.minWidth : 64;

  /**
   * @private
   * @type {boolean}
   */
  this.renderedVisible_ = false;

  /**
   * @private
   * @type {number|undefined}
   */
  this.renderedWidth_ = undefined;

  /**
   * @private
   * @type {string}
   */
  this.renderedHTML_ = '';

  var render = options.render ? options.render : ol.control.ScaleLine.render;

  ol.control.Control.call(this, {
    element: this.element_,
    render: render,
    target: options.target
  });

  ol.events.listen(
      this, ol.Object.getChangeEventType(ol.control.ScaleLine.Property_.UNITS),
      this.handleUnitsChanged_, this);

  this.setUnits(/** @type {ol.control.ScaleLineUnits} */ (options.units) ||
      ol.control.ScaleLineUnits.METRIC);

};
ol.inherits(ol.control.ScaleLine, ol.control.Control);

/**
 * @const
 * @type {Array.<number>}
 */
ol.control.ScaleLine.LEADING_DIGITS = [1, 2, 5];

/**
 * Return the units to use in the scale line.
 * @return {ol.control.ScaleLineUnits|undefined} The units to use in the scale
 *     line.
 * @observable
 * @api
 */
ol.control.ScaleLine.prototype.getUnits = function() {
  return /** @type {ol.control.ScaleLineUnits|undefined} */ (
      this.get(ol.control.ScaleLine.Property_.UNITS));
};

/**
 * Update the scale line element.
 * @param {ol.MapEvent} mapEvent Map event.
 * @this {ol.control.ScaleLine}
 * @api
 */
ol.control.ScaleLine.render = function(mapEvent) {
  var frameState = mapEvent.frameState;
  if (!frameState) {
    this.viewState_ = null;
  } else {
    this.viewState_ = frameState.viewState;
  }
  this.updateElement_();
};

/**
 * @private
 */
ol.control.ScaleLine.prototype.handleUnitsChanged_ = function() {
  this.updateElement_();
};

/**
 * Set the units to use in the scale line.
 * @param {ol.control.ScaleLineUnits} units The units to use in the scale line.
 * @observable
 * @api
 */
ol.control.ScaleLine.prototype.setUnits = function(units) {
  this.set(ol.control.ScaleLine.Property_.UNITS, units);
};

/**
 * @private
 */
ol.control.ScaleLine.prototype.updateElement_ = function() {
  var viewState = this.viewState_;

  if (!viewState) {
    if (this.renderedVisible_) {
      this.element_.style.display = 'none';
      this.renderedVisible_ = false;
    }
    return;
  }

  var center = viewState.center;
  var projection = viewState.projection;
  var metersPerUnit = projection.getMetersPerUnit();
  var pointResolution =
      ol.proj.getPointResolution(projection, viewState.resolution, center) *
      metersPerUnit;

  var nominalCount = this.minWidth_ * pointResolution;
  var suffix = '';
  var units = this.getUnits();
  if (units == ol.control.ScaleLineUnits.DEGREES) {
    var metersPerDegree = ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES];
    pointResolution /= metersPerDegree;
    if (nominalCount < metersPerDegree / 60) {
      suffix = '\u2033'; // seconds
      pointResolution *= 3600;
    } else if (nominalCount < metersPerDegree) {
      suffix = '\u2032'; // minutes
      pointResolution *= 60;
    } else {
      suffix = '\u00b0'; // degrees
    }
  } else if (units == ol.control.ScaleLineUnits.IMPERIAL) {
    if (nominalCount < 0.9144) {
      suffix = 'in';
      pointResolution /= 0.0254;
    } else if (nominalCount < 1609.344) {
      suffix = 'ft';
      pointResolution /= 0.3048;
    } else {
      suffix = 'mi';
      pointResolution /= 1609.344;
    }
  } else if (units == ol.control.ScaleLineUnits.NAUTICAL) {
    pointResolution /= 1852;
    suffix = 'nm';
  } else if (units == ol.control.ScaleLineUnits.METRIC) {
    if (nominalCount < 0.001) {
      suffix = 'μm';
      pointResolution *= 1000000;
    } else if (nominalCount < 1) {
      suffix = 'mm';
      pointResolution *= 1000;
    } else if (nominalCount < 1000) {
      suffix = 'm';
    } else {
      suffix = 'km';
      pointResolution /= 1000;
    }
  } else if (units == ol.control.ScaleLineUnits.US) {
    if (nominalCount < 0.9144) {
      suffix = 'in';
      pointResolution *= 39.37;
    } else if (nominalCount < 1609.344) {
      suffix = 'ft';
      pointResolution /= 0.30480061;
    } else {
      suffix = 'mi';
      pointResolution /= 1609.3472;
    }
  } else {
    ol.asserts.assert(false, 33); // Invalid units
  }

  var i = 3 * Math.floor(
      Math.log(this.minWidth_ * pointResolution) / Math.log(10));
  var count, width;
  while (true) {
    count = ol.control.ScaleLine.LEADING_DIGITS[((i % 3) + 3) % 3] *
        Math.pow(10, Math.floor(i / 3));
    width = Math.round(count / pointResolution);
    if (isNaN(width)) {
      this.element_.style.display = 'none';
      this.renderedVisible_ = false;
      return;
    } else if (width >= this.minWidth_) {
      break;
    }
    ++i;
  }

  var html = count + ' ' + suffix;
  if (this.renderedHTML_ != html) {
    this.innerElement_.innerHTML = html;
    this.renderedHTML_ = html;
  }

  if (this.renderedWidth_ != width) {
    this.innerElement_.style.width = width + 'px';
    this.renderedWidth_ = width;
  }

  if (!this.renderedVisible_) {
    this.element_.style.display = '';
    this.renderedVisible_ = true;
  }

};

/**
 * @enum {string}
 * @private
 */
ol.control.ScaleLine.Property_ = {
  UNITS: 'units'
};
<|endoftext|>


<commit_before>/* jshint quotmark: single */
/* jshint evil: true */

(function () {
    'use strict';

    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) {
            return typeof args[number] != 'undefined' ? args[number] : match;
        });
    };

    var editor, settings, title;

    var run = function () {
        $('#output-container').html('');
        $('#debugger').html('');
        $('#restart').hide();
        var result = settings.compile({
            data: editor.getValue(),
            success: function (data) {
                $('#restart').show();

                $('
', { id: 'output' })
                .appendTo('#output-container');

                $('
').appendTo('#output-container');

                if (data.indexOf('Failed') === 0) {
                    $('#output').html(data);
                    return;
                }

                eval(data);
                $('#output').squiffy({
                    scroll: 'element',
                    persist: false,
                    restartPrompt: false,
                    onSet: function (attribute, value) {
                        onSet(attribute, value);
                    }
                });
            },
            fail: function (data) {
                $('#output').html(result.message);
            }
        });
    };

    var restart = function () {
        $('#debugger').html('');
        $('#output').squiffy('restart');
    };

    var localSaveTimeout;

    var editorChange = function () {
        if (localSaveTimeout) clearTimeout(localSaveTimeout);
        localSaveTimeout = setTimeout(localSave, 1000);
    };

    var localSave = function () {
        var data = editor.getValue();
        if (settings.storageKey) {
            localStorage[settings.storageKey] = data;
        }
        processFile(data);
    };

    var processFile = function (data) {
        var titleRegex = /^@title (.*)$/;

        var lines = data.replace(/\r/g, '').split('\n');
        lines.forEach(function (line) {
            var stripLine = line.trim();
            var match = titleRegex.exec(stripLine);

            if (match && title !== match[1]) {
                title = match[1];
                if (settings.updateTitle) {
                    settings.updateTitle(title);
                }
            }
        });
    };

    var methods = {
        init: function (options) {
            var element = this;
            settings = options;

            element.html(editorHtml);
            element.layout({
                applyDefaultStyles: true,
                onresize: function () {
                    if (editor) editor.resize();
                },
                north__resizable: false,
                north__closable: false,
                north__spacing_open: 0,
                east__size: 0.5,
                south__size: 80,
            });

            editor = ace.edit('editor');
            editor.setTheme('ace/theme/eclipse');
            editor.getSession().setMode('ace/mode/markdown');
            editor.getSession().setUseWrapMode(true);
            editor.getSession().on('change', editorChange);
            editor.focus();

            editor.getSession().setValue(options.data, -1);

            if (options.open) {
                $('#open').show();
                $('#open').click(options.open);
            }

            if (options.save) {
                $('#save').show();
                $('#save').click(function () {
                    clearTimeout(localSaveTimeout);
                    localSave();
                    options.save(title);
                });
            }

            $('#run').click(run);
            $('#restart').click(restart);
        },
        load: function (data) {
            editor.getSession().setValue(data, -1);
        },
        save: function () {
            return editor.getValue();
        },
        setStorageKey: function (key) {
            settings.storageKey = key;
        },
    };

    $.fn.squiffyEditor = function (methodOrOptions) {
        if (methods[methodOrOptions]) {
            return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof methodOrOptions === 'object' || ! methodOrOptions) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  methodOrOptions + ' does not exist');
        }
    };

    var onSet = function (attribute, value) {
        // don't log internal attribute changes
        if (attribute.indexOf('_') === 0) return;

        $('
').html('{0} = {1}'.format(attribute, value)).appendTo('#debugger');
    };

    var editorHtml =
        '
\n' +
            '<button id="open" class="btn btn-primary" style="display: none"> Open</button>\n' +
            '<button id="save" class="btn btn-primary" style="display: none"> Save</button>\n' +
            '<button id="run" class="btn btn-success"> Run</button>\n' +
            '<button id="restart" class="btn btn-success" style="display: none"> Restart</button>\n' +
            '
\n' +
                '
\n' +
                        '<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">\n' +
                                '\n' +
                                'Download\n' +
                                '\n' +
                        '</button>\n' +
                        '
\n' +
                                '
Squiffy script
\n' +
                                '
Export HTML and JavaScript
\n' +
                                '
Export JavaScript only
\n' +
                        '
\n' +
                '
\n' +
                '<button id="preview" class="btn btn-primary"> Preview</button>\n' +
                '<button id="publish" class="btn btn-primary"> Publish</button>\n' +
            '
\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n';
})();<commit_msg>Set title as "Untitled" if not specified<commit_after>/* jshint quotmark: single */
/* jshint evil: true */

(function () {
    'use strict';

    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) {
            return typeof args[number] != 'undefined' ? args[number] : match;
        });
    };

    var editor, settings, title;

    var run = function () {
        $('#output-container').html('');
        $('#debugger').html('');
        $('#restart').hide();
        var result = settings.compile({
            data: editor.getValue(),
            success: function (data) {
                $('#restart').show();

                $('
', { id: 'output' })
                .appendTo('#output-container');

                $('
').appendTo('#output-container');

                if (data.indexOf('Failed') === 0) {
                    $('#output').html(data);
                    return;
                }

                eval(data);
                $('#output').squiffy({
                    scroll: 'element',
                    persist: false,
                    restartPrompt: false,
                    onSet: function (attribute, value) {
                        onSet(attribute, value);
                    }
                });
            },
            fail: function (data) {
                $('#output').html(result.message);
            }
        });
    };

    var restart = function () {
        $('#debugger').html('');
        $('#output').squiffy('restart');
    };

    var localSaveTimeout;

    var editorChange = function () {
        if (localSaveTimeout) clearTimeout(localSaveTimeout);
        localSaveTimeout = setTimeout(localSave, 1000);
    };

    var localSave = function () {
        var data = editor.getValue();
        if (settings.storageKey) {
            localStorage[settings.storageKey] = data;
        }
        processFile(data);
    };

    var processFile = function (data) {
        var titleRegex = /^@title (.*)$/;
        var newTitle;

        var lines = data.replace(/\r/g, '').split('\n');
        lines.forEach(function (line) {
            var stripLine = line.trim();
            var match = titleRegex.exec(stripLine);

            if (match) {
                newTitle = match[1]
            }
        });

        if (!title || title !== newTitle) {
            title = newTitle || 'Untitled';
            if (settings.updateTitle) {
                settings.updateTitle(title);
            }
        }
    };

    var methods = {
        init: function (options) {
            var element = this;
            settings = options;

            element.html(editorHtml);
            element.layout({
                applyDefaultStyles: true,
                onresize: function () {
                    if (editor) editor.resize();
                },
                north__resizable: false,
                north__closable: false,
                north__spacing_open: 0,
                east__size: 0.5,
                south__size: 80,
            });

            editor = ace.edit('editor');
            editor.setTheme('ace/theme/eclipse');
            editor.getSession().setMode('ace/mode/markdown');
            editor.getSession().setUseWrapMode(true);
            editor.getSession().on('change', editorChange);
            editor.focus();

            editor.getSession().setValue(options.data, -1);

            if (options.open) {
                $('#open').show();
                $('#open').click(options.open);
            }

            if (options.save) {
                $('#save').show();
                $('#save').click(function () {
                    clearTimeout(localSaveTimeout);
                    localSave();
                    options.save(title);
                });
            }

            $('#run').click(run);
            $('#restart').click(restart);
        },
        load: function (data) {
            editor.getSession().setValue(data, -1);
        },
        save: function () {
            return editor.getValue();
        },
        setStorageKey: function (key) {
            settings.storageKey = key;
        },
    };

    $.fn.squiffyEditor = function (methodOrOptions) {
        if (methods[methodOrOptions]) {
            return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof methodOrOptions === 'object' || ! methodOrOptions) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  methodOrOptions + ' does not exist');
        }
    };

    var onSet = function (attribute, value) {
        // don't log internal attribute changes
        if (attribute.indexOf('_') === 0) return;

        $('
').html('{0} = {1}'.format(attribute, value)).appendTo('#debugger');
    };

    var editorHtml =
        '
\n' +
            '<button id="open" class="btn btn-primary" style="display: none"> Open</button>\n' +
            '<button id="save" class="btn btn-primary" style="display: none"> Save</button>\n' +
            '<button id="run" class="btn btn-success"> Run</button>\n' +
            '<button id="restart" class="btn btn-success" style="display: none"> Restart</button>\n' +
            '
\n' +
                '
\n' +
                        '<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">\n' +
                                '\n' +
                                'Download\n' +
                                '\n' +
                        '</button>\n' +
                        '
\n' +
                                '
Squiffy script
\n' +
                                '
Export HTML and JavaScript
\n' +
                                '
Export JavaScript only
\n' +
                        '
\n' +
                '
\n' +
                '<button id="preview" class="btn btn-primary"> Preview</button>\n' +
                '<button id="publish" class="btn btn-primary"> Publish</button>\n' +
            '
\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n';
})();<|endoftext|>


<commit_before>var http = require('http'),
nodeStatic = require('node-static'),
url = require('url'),
players = require('players'),
games = require('games'),
ingame = require('ingame'),
nowjs = require('now');
port = 8000;

var server = http.createServer(function(req, res) {
	var publicFiles = new nodeStatic.Server('public', {
		cache: false
	}), sharedFiles = new nodeStatic.Server('shared', {
		cache: false
	});

	publicFiles.serve(req, res, function (e) {
		if (e) {
			sharedFiles.serve(req, res);
		}
	});
});

var everyone = nowjs.initialize(server);

var s4 = function() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};

global.guid = function(times) {
	times = times ? times : 1;
	var guid = '';
	for (var i = 0; i < times; i++) {
		guid += s4();
	}
	return guid;
};

everyone.now.register = players.register;
everyone.now.playNow = games.playNow;
everyone.now.startEndMove = ingame.startEndMove;
everyone.now.placeBomb = ingame.placeBomb;

everyone.on('disconnect', function(clientId) {
	games.logout(clientId);
	players.logout(clientId);
});

server.listen(port);
console.log('Server running at ' + port);
<commit_msg>new port<commit_after>var http = require('http'),
nodeStatic = require('node-static'),
url = require('url'),
players = require('players'),
games = require('games'),
ingame = require('ingame'),
nowjs = require('now');
port = 9706;

var server = http.createServer(function(req, res) {
	var publicFiles = new nodeStatic.Server('public', {
		cache: false
	}), sharedFiles = new nodeStatic.Server('shared', {
		cache: false
	});

	publicFiles.serve(req, res, function (e) {
		if (e) {
			sharedFiles.serve(req, res);
		}
	});
});

var everyone = nowjs.initialize(server);

var s4 = function() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};

global.guid = function(times) {
	times = times ? times : 1;
	var guid = '';
	for (var i = 0; i < times; i++) {
		guid += s4();
	}
	return guid;
};

everyone.now.register = players.register;
everyone.now.playNow = games.playNow;
everyone.now.startEndMove = ingame.startEndMove;
everyone.now.placeBomb = ingame.placeBomb;

everyone.on('disconnect', function(clientId) {
	games.logout(clientId);
	players.logout(clientId);
});

server.listen(port);
console.log('Server running at ' + port);
<|endoftext|>


<commit_before>import "./examen.html";
import {Selecciones} from "../../api/seleccion.js";
import {Verdaderos} from "../../api/verdadero.js";

//import {Random} from 'meteor/'

Template.examen.onCreated(function(){
    this.posSeleccion = 0;
    this.posVerdadero = 0;
    this.answersSeleccion = [0,0,0,0,0];
   // seleccionEscogida = [0,0,0,0,0,0,0,0,0,0];
    //verdaderoEscogido = [0,0,0,0,0,0,0,0,0,0];
    this.answersVerdaderos = [false,false,false,false,false];
    Meteor.subscribe("Verdaderos");
    Meteor.subscribe("Selecciones");

});

Template.examen.helpers({
    /*
    verdaderos:function(){
        return Verdaderos.find({});
    },
    selecciones:function(){
        return Selecciones.find({});
    },
    */
    /*
    sizeVerdaderos:function(){
        return Verdaderos.count();
    },
    sizeSelecciones:function(){
        return Selecciones.count();
    },
    */
    preguntaSeleccion: function(){
        //var random = Math.floor( (Selecciones.find().count()-1)*Math.random());
        //Math.random() * (max - min + 1)) + min;
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+1));

        //var query = Selecciones.findOne({index:random});
        //query.select('respuesta');
        /*query.exec(function(err,seleccion){
            if(err)return handleError(err);
          Template.instance().answersSeleccion[Template.instance().posSeleccion] = seleccion.respuesta;
        });
        */

        //Template.instance().answersSeleccion[Template.instance().posSeleccion] = Selecciones.find({index:random},{respuesta:1, _id:0});
        //var temp  = Selecciones.find({index:random},{respuesta:1, _id:0});
        //var temp2 = temp.toArray();
        //var temp3 = temp2[1];
        //alert(temp3);

        //var array = myDocument.split();
        //alert(array[1]);
        var myDocument = Selecciones.find().fetch()[random];
        alert(console.log(myDocument.respuesta));

        Template.instance().posSeleccion = Template.instance().posSeleccion+1;
        //alert(Template.instance().posSeleccion);

        return Selecciones.find({index:random});
    },
    preguntaVerdadero: function(){
        var random = Math.floor( (Verdaderos.find().count()-1)*Math.random())

        //Template.instance().answersVerdaderos[Template.instance().posVerdadero] = Verdaderos.findOne( {index:random }).respuesta;
        //Template.instance().posVerdadero = Template.instance().posVerdadero+1;
        //return Verdaderos.findOne( {index:random });
    },
    changeAnswer:function(respuesta){
        alert(respuesta);
    }
    /*,

    opcion:function(numPregunta,numOpcion){
        var realSelectionIndex = Template.instance().seleccionEscogida[numPregunta];
        //var realSelection = Selecciones.findOne({index:realSelectionIndex});
        if(numOpcion === 1){
            return Selecciones.findOne({index:realSelectionIndex}).opcion1;
        }else if (numOpcion ===2 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion2;
        }else if(numOpcion ===3 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion3;
        }else if(numOpcion ===4 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion4;
        }
    }
    */
});

<commit_msg>removing accidental alert<commit_after>import "./examen.html";
import {Selecciones} from "../../api/seleccion.js";
import {Verdaderos} from "../../api/verdadero.js";

//import {Random} from 'meteor/'

Template.examen.onCreated(function(){
    this.posSeleccion = 0;
    this.posVerdadero = 0;
    this.answersSeleccion = [0,0,0,0,0];
   // seleccionEscogida = [0,0,0,0,0,0,0,0,0,0];
    //verdaderoEscogido = [0,0,0,0,0,0,0,0,0,0];
    this.answersVerdaderos = [false,false,false,false,false];
    Meteor.subscribe("Verdaderos");
    Meteor.subscribe("Selecciones");

});

Template.examen.helpers({
    /*
    verdaderos:function(){
        return Verdaderos.find({});
    },
    selecciones:function(){
        return Selecciones.find({});
    },
    */
    /*
    sizeVerdaderos:function(){
        return Verdaderos.count();
    },
    sizeSelecciones:function(){
        return Selecciones.count();
    },
    */
    preguntaSeleccion: function(){
        //var random = Math.floor( (Selecciones.find().count()-1)*Math.random());
        //Math.random() * (max - min + 1)) + min;
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+1));

        //var query = Selecciones.findOne({index:random});
        //query.select('respuesta');
        /*query.exec(function(err,seleccion){
            if(err)return handleError(err);
          Template.instance().answersSeleccion[Template.instance().posSeleccion] = seleccion.respuesta;
        });
        */

        //Template.instance().answersSeleccion[Template.instance().posSeleccion] = Selecciones.find({index:random},{respuesta:1, _id:0});
        //var temp  = Selecciones.find({index:random},{respuesta:1, _id:0});
        //var temp2 = temp.toArray();
        //var temp3 = temp2[1];
        //alert(temp3);

        //var array = myDocument.split();
        //alert(array[1]);
        var myDocument = Selecciones.find().fetch()[random];
        console.log(myDocument.respuesta);

        Template.instance().posSeleccion = Template.instance().posSeleccion+1;
        //alert(Template.instance().posSeleccion);

        return Selecciones.find({index:random});
    },
    preguntaVerdadero: function(){
        var random = Math.floor( (Verdaderos.find().count()-1)*Math.random())

        //Template.instance().answersVerdaderos[Template.instance().posVerdadero] = Verdaderos.findOne( {index:random }).respuesta;
        //Template.instance().posVerdadero = Template.instance().posVerdadero+1;
        //return Verdaderos.findOne( {index:random });
    },
    changeAnswer:function(respuesta){
        alert(respuesta);
    }
    /*,

    opcion:function(numPregunta,numOpcion){
        var realSelectionIndex = Template.instance().seleccionEscogida[numPregunta];
        //var realSelection = Selecciones.findOne({index:realSelectionIndex});
        if(numOpcion === 1){
            return Selecciones.findOne({index:realSelectionIndex}).opcion1;
        }else if (numOpcion ===2 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion2;
        }else if(numOpcion ===3 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion3;
        }else if(numOpcion ===4 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion4;
        }
    }
    */
});

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import exportToCsv from '@folio/stripes-util/lib/exportCsv';
import Button from '../Button';

class ExportCsv extends React.Component {
  static propTypes = {
    data: PropTypes.arrayOf(PropTypes.object),
    intl: PropTypes.object,
    options: PropTypes.object,
  }

  render() {
    const { data, options, intl } = this.props;
    return (
      <Button onClick={() => { exportToCsv(data, options, intl); }}>
        <FormattedMessage id="stripes-components.exportToCsv" />
      </Button>
    );
  }
}

export default ExportCsv;
<commit_msg>Revert "Stcom csv export (#724)" (#726)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import exportToCsv from '@folio/stripes-util/lib/exportCsv';
import Button from '../Button';

class ExportCsv extends React.Component {
  static propTypes = {
    data: PropTypes.arrayOf(PropTypes.object),
    excludeKeys: PropTypes.arrayOf(PropTypes.string),
  }

  render() {
    const { data, excludeKeys } = this.props;
    return (
      <Button onClick={() => { exportToCsv(data, excludeKeys); }}>
        <FormattedMessage id="stripes-components.exportToCsv" />
      </Button>
    );
  }
}

export default ExportCsv;
<|endoftext|>


<commit_before>// This file contains code to establish
// filtering for files and differences

// list currently active filters
var activeFilesFilters = [];
var activeDiffsFilters = [];

var modelsFilter = [];

// APPLY FILTERS

function applyFilters ()
{
	filestats = applyFilesFilters ();
	diffstats = applyDiffsFilters ();
	console.log("applied");
}

// apply active file filters
function applyFilesFilters ()
{
	var result = originalFilestats;
	activeFilesFilters.forEach (function (filter)
	{
		result = filter (result);
	});
	$("#choiceSelectedVersions").text(Object.keys (result).length);
	return result;
}
// apply active diffs filters
function applyDiffsFilters ()
{
	var result = originalDiffstats;
	activeDiffsFilters.forEach (function (filter)
	{
		result = filter (result);
	});
	$("#choiceSelectedDiffs").text(result.length);
	return result;
}

// ACTIVATE FILTERS

// activate a file filter
function activateFilesFilter (filter)
{
	var add = true;
	activeFilesFilters.forEach (function (f)
	{
		if (f == filter)
		{
			add = false;
			return;
		}
	});
	if (add)
		activeFilesFilters.push (filter);
}

// activate a diff filter
function activateDiffsFilter (filter)
{
	var add = true;
	activeDiffsFilters.forEach (function (f)
	{
		if (f == filter)
		{
			add = false;
			return;
		}
	});
	if (add)
		activeDiffsFilters.push (filter);
}

// DEACTIVATE FILTERS

// deactivate a file filter
function deactivateFilesFilter (filter)
{
	for (var i = activeFilesFilters.length - 1; i >= 0; i--)
		if (activeFilesFilters[i] == filter)
			activeFilesFilters.splice(i, 1)
}

// deactivate a diff filter
function deactivateDiffsFilter (filter)
{
	for (var i = activeDiffsFilters.length - 1; i >= 0; i--)
		if (activeDiffsFilters[i] == filter)
			activeDiffsFilters.splice(i, 1)
}

// ACTUAL FILTERS

// This file contains a number of implemented filters
// that can be applied to models
//
// Every filter takes the matrix of files or diffs
// and returns a matrix that contains only those
// entries of the input that match the filter's
// criteria

function filterRemoveSbmlFiles (table)
{
	var filtered = {};
	for (var id in table)
	{
		if (table.hasOwnProperty(id) && table[id].modeltype != "SBML")
			filtered[id] = table[id];
	}
	return filtered;
}

function filterRemoveSbmlDiffs (table)
{
	var filtered = [];
	for (var id = 0; id < table.length; id++)
	{
		if (table[id]["modeltype"] != "SBML")
			filtered.push (table[id]);
	}
	return filtered;
}

function filterRemoveCellmlFiles (table)
{
	var filtered = {};
	for (var id in table)
	{
		if (table.hasOwnProperty(id) && table[id].modeltype != "CellML")
			filtered[id] = table[id];
	}
	return filtered;
}

function filterRemoveCellmlDiffs (table)
{
	var filtered = [];
	for (var id = 0; id < table.length; id++)
	{
		if (table[id]["modeltype"] != "CellML")
			filtered.push (table[id]);
	}
	return filtered;
}

// filter for times in the files table
function filterTimeFiles (table)
{
	var filtered = {};
	for (var id in table)
	{
		if (table.hasOwnProperty(id) && table[id].date >= extent[0] && table[id].date <= extent[1])
			filtered[id] = table[id];
	}
	return filtered;
}

// filter for times in the diffs table
function filterTimeDiffs (table)
{
	var filtered = [];
	for (var id = 0; id < table.length; id++)
	{
		var datum1 = originalFilestats[ table[id]["model"] + table[id]["version1id"]  ].date;
		var datum2 = originalFilestats[ table[id]["model"] + table[id]["version2id"]  ].date;

		if (datum1 >= extent[0] && datum1 <= extent[1] && datum2 >= extent[0] && datum2 <= extent[1])
			filtered.push (table[id]);
	}
	return filtered;
}

// filter by several model IDs in files table
function filterIdFiles(table){
	var filtered = {};
 	for(var id in table){
		if(table.hasOwnProperty(id) {
			for(var i = 0; i < modelsFilter.length; i++){
				if(table[id].model.indexOf(modelsFilter) > -1){
					filtered[id] = table[id];
				}
			}
		}
	}
	return filtered;
}

// filter by several model IDs in diffs table
function filterIdDiffs (table)
{
	var filtered = [];
 	for (var id = 0; id < table.length; id++)
	{
		if (table[id]["model"].indexOf(modelsFilter) > -1)
			filtered.push (table[id]);
	}
	return filtered;
}
<commit_msg>fixing a bug with file-filtering<commit_after>// This file contains code to establish
// filtering for files and differences

// list currently active filters
var activeFilesFilters = [];
var activeDiffsFilters = [];

var modelsFilter = [];

// APPLY FILTERS

function applyFilters ()
{
	filestats = applyFilesFilters ();
	diffstats = applyDiffsFilters ();
	console.log("applied");
}

// apply active file filters
function applyFilesFilters ()
{
	var result = originalFilestats;
	activeFilesFilters.forEach (function (filter)
	{
		result = filter (result);
	});
	$("#choiceSelectedVersions").text(Object.keys (result).length);
	return result;
}
// apply active diffs filters
function applyDiffsFilters ()
{
	var result = originalDiffstats;
	activeDiffsFilters.forEach (function (filter)
	{
		result = filter (result);
	});
	$("#choiceSelectedDiffs").text(result.length);
	return result;
}

// ACTIVATE FILTERS

// activate a file filter
function activateFilesFilter (filter)
{
	var add = true;
	activeFilesFilters.forEach (function (f)
	{
		if (f == filter)
		{
			add = false;
			return;
		}
	});
	if (add)
		activeFilesFilters.push (filter);
}

// activate a diff filter
function activateDiffsFilter (filter)
{
	var add = true;
	activeDiffsFilters.forEach (function (f)
	{
		if (f == filter)
		{
			add = false;
			return;
		}
	});
	if (add)
		activeDiffsFilters.push (filter);
}

// DEACTIVATE FILTERS

// deactivate a file filter
function deactivateFilesFilter (filter)
{
	for (var i = activeFilesFilters.length - 1; i >= 0; i--)
		if (activeFilesFilters[i] == filter)
			activeFilesFilters.splice(i, 1)
}

// deactivate a diff filter
function deactivateDiffsFilter (filter)
{
	for (var i = activeDiffsFilters.length - 1; i >= 0; i--)
		if (activeDiffsFilters[i] == filter)
			activeDiffsFilters.splice(i, 1)
}

// ACTUAL FILTERS

// This file contains a number of implemented filters
// that can be applied to models
//
// Every filter takes the matrix of files or diffs
// and returns a matrix that contains only those
// entries of the input that match the filter's
// criteria

function filterRemoveSbmlFiles (table)
{
	var filtered = {};
	for (var id in table)
	{
		if (table.hasOwnProperty(id) && table[id].modeltype != "SBML")
			filtered[id] = table[id];
	}
	return filtered;
}

function filterRemoveSbmlDiffs (table)
{
	var filtered = [];
	for (var id = 0; id < table.length; id++)
	{
		if (table[id]["modeltype"] != "SBML")
			filtered.push (table[id]);
	}
	return filtered;
}

function filterRemoveCellmlFiles (table)
{
	var filtered = {};
	for (var id in table)
	{
		if (table.hasOwnProperty(id) && table[id].modeltype != "CellML")
			filtered[id] = table[id];
	}
	return filtered;
}

function filterRemoveCellmlDiffs (table)
{
	var filtered = [];
	for (var id = 0; id < table.length; id++)
	{
		if (table[id]["modeltype"] != "CellML")
			filtered.push (table[id]);
	}
	return filtered;
}

// filter for times in the files table
function filterTimeFiles (table)
{
	var filtered = {};
	for (var id in table)
	{
		if (table.hasOwnProperty(id) && table[id].date >= extent[0] && table[id].date <= extent[1])
			filtered[id] = table[id];
	}
	return filtered;
}

// filter for times in the diffs table
function filterTimeDiffs (table)
{
	var filtered = [];
	for (var id = 0; id < table.length; id++)
	{
		var datum1 = originalFilestats[ table[id]["model"] + table[id]["version1id"]  ].date;
		var datum2 = originalFilestats[ table[id]["model"] + table[id]["version2id"]  ].date;

		if (datum1 >= extent[0] && datum1 <= extent[1] && datum2 >= extent[0] && datum2 <= extent[1])
			filtered.push (table[id]);
	}
	return filtered;
}

// filter by several model IDs in files table
function filterIdFiles(table){
	var filtered = {};
 	for(var id in table){
		if(table.hasOwnProperty(id)) {
			for(var i = 0; i < modelsFilter.length; i++){
				if(table[id].model.indexOf(modelsFilter[i]) > -1){
					filtered[id] = table[id];
				}
			}
		}
	}
	return filtered;
}

// filter by several model IDs in diffs table
function filterIdDiffs (table)
{
	var filtered = [];
 	for (var id = 0; id < table.length; id++) {
		if(table.hasOwnProperty(id)) {
			for(var i = 0; i < modelsFilter.length; i++){
				if (table[id]["model"].indexOf(modelsFilter[i]) > -1) {
					filtered.push (table[id]);
				}
			}
		}
	}
	return filtered;
}
<|endoftext|>