<commit_before>/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
/*

  The MIT License (MIT)

  Copyright (c) 2007-2013 Einar Lielmanis and contributors.

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.

 CSS Beautifier
---------------

    Written by Harutyun Amirjanyan, (amirjanyan@gmail.com)

    Based on code initially developed by: Einar Lielmanis, <elfz@laacz.lv>
        http://jsbeautifier.org/

    Usage:
        css_beautify(source_text);
        css_beautify(source_text, options);

    The options are:
        indent_size (default 4)          — indentation size,
        indent_char (default space)      — character to indent with,

    e.g

    css_beautify(css_source_text, {
      'indent_size': 1,
      'indent_char': '\t'
    });
*/

// http://www.w3.org/TR/CSS21/syndata.html#tokenization
// http://www.w3.org/TR/css3-syntax/

(function () {
    function css_beautify(source_text, options) {
        options = options || {};
        var indentSize = options.indent_size || 4;
        var indentCharacter = options.indent_char || ' ';

        // compatibility
        if (typeof indentSize === "string") {
            indentSize = parseInt(indentSize, 10);
        }

        // tokenizer
        var whiteRe = /^\s+$/;
        var wordRe = /[\w$\-_]/;

        var pos = -1,
            ch;

        function next() {
            ch = source_text.charAt(++pos);
            return ch;
        }

        function peek() {
            return source_text.charAt(pos + 1);
        }

        function eatString(endChar) {
            var start = pos;
            while (next()) {
                if (ch === "\\") {
                    next();
                    next();
                } else if (ch === endChar) {
                    break;
                } else if (ch === "\n") {
                    break;
                }
            }
            return source_text.substring(start, pos + 1);
        }

        function eatWhitespace() {
            var start = pos;
            while (whiteRe.test(peek())) {
                pos++;
            }
            return pos !== start;
        }

        function skipWhitespace() {
            var start = pos;
            do {} while (whiteRe.test(next()));
            return pos !== start + 1;
        }

        function eatComment() {
            var start = pos;
            next();
            while (next()) {
                if (ch === "*" && peek() === "/") {
                    pos++;
                    break;
                }
            }

            return source_text.substring(start, pos + 1);
        }

        function lookBack(str) {
            return source_text.substring(pos - str.length, pos).toLowerCase() ===
                str;
        }

        // printer
        var indentString = source_text.match(/^[\r\n]*[\t ]*/)[0];
        var singleIndent = Array(indentSize + 1).join(indentCharacter);
        var indentLevel = 0;

        function indent() {
            indentLevel++;
            indentString += singleIndent;
        }

        function outdent() {
            indentLevel--;
            indentString = indentString.slice(0, -indentSize);
        }

        var print = {};
        print["{"] = function (ch) {
            print.singleSpace();
            output.push(ch);
            print.newLine();
        };
        print["}"] = function (ch) {
            print.newLine();
            output.push(ch);
            print.newLine();
        };

        print._lastCharWhitespace = function () {
            return whiteRe.test(output[output.length - 1]);
        }

        print.newLine = function (keepWhitespace) {
            if (!keepWhitespace) {
                while (print._lastCharWhitespace()) {
                    output.pop();
                }
            }

            if (output.length) {
                output.push('\n');
            }
            if (indentString) {
                output.push(indentString);
            }
        };
        print.singleSpace = function () {
            if (output.length && !print._lastCharWhitespace()) {
                output.push(' ');
            }
        };
        var output = [];
        if (indentString) {
            output.push(indentString);
        }
        /*_____________________--------------------_____________________*/

        while (true) {
            var isAfterSpace = skipWhitespace();

            if (!ch) {
                break;
            } else if (ch === '/' && peek() === '*') { // comment
                print.newLine();
                output.push(eatComment(), "\n", indentString);
                var header = lookBack("")
                if (header) {
                    print.newLine();
                }
            } else if (ch === '{') {
                indent();
                print["{"](ch);
            } else if (ch === '}') {
                outdent();
                print["}"](ch);
            } else if (ch === ":") {
                eatWhitespace();
                output.push(ch, " ");
            } else if (ch === '"' || ch === '\'') {
                output.push(eatString(ch));
            } else if (ch === ';') {
                output.push(ch, '\n', indentString);
            } else if (ch === '(') { // may be a url
                if (lookBack("url")) {
                    output.push(ch);
                    eatWhitespace();
                    if (next()) {
                        if (ch !== ')' && ch !== '"' && ch !== '\'') {
                            output.push(eatString(')'));
                        } else {
                            pos--;
                        }
                    }
                } else {
                    if (isAfterSpace) {
                        print.singleSpace();
                    }
                    output.push(ch);
                    eatWhitespace();
                }
            } else if (ch === ')') {
                output.push(ch);
            } else if (ch === ',') {
                eatWhitespace();
                output.push(ch);
                print.singleSpace();
            } else if (ch === ']') {
                output.push(ch);
            } else if (ch === '[' || ch === '=') { // no whitespace before or after
                eatWhitespace();
                output.push(ch);
            } else {
                if (isAfterSpace) {
                    print.singleSpace();
                }

                output.push(ch);
            }
        }

        var sweetCode = output.join('').replace(/[\n ]+$/, '');
        return sweetCode;
    }

    if (typeof define === "function") {
        // Add support for require.js
        define(function (require, exports, module) {
            exports.css_beautify = css_beautify;
        });
    } else if (typeof exports !== "undefined") {
        // Add support for CommonJS. Just put this file somewhere on your require.paths
        // and you will be able to `var html_beautify = require("beautify").html_beautify`.
        exports.css_beautify = css_beautify;
    } else if (typeof window !== "undefined") {
        // If we're running a web page and don't have either of the above, add our one global
        window.css_beautify = css_beautify;
    } else if (typeof global !== "undefined") {
        // If we don't even have window, try global.
        global.css_beautify = css_beautify;
    }

}());<commit_msg>introduce new option "end_with_newline". The default value is "false" and this will make sure that the output ends with a newline ("\n")<commit_after>/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
/*

  The MIT License (MIT)

  Copyright (c) 2007-2013 Einar Lielmanis and contributors.

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.

 CSS Beautifier
---------------

    Written by Harutyun Amirjanyan, (amirjanyan@gmail.com)

    Based on code initially developed by: Einar Lielmanis, <elfz@laacz.lv>
        http://jsbeautifier.org/

    Usage:
        css_beautify(source_text);
        css_beautify(source_text, options);

    The options are:
        indent_size (default 4)          — indentation size,
        indent_char (default space)      — character to indent with,
        end_with_newline (default true)  - end with a newline

    e.g

    css_beautify(css_source_text, {
      'indent_size': 1,
      'indent_char': '\t',
      'end_with_newline': false,
    });
*/

// http://www.w3.org/TR/CSS21/syndata.html#tokenization
// http://www.w3.org/TR/css3-syntax/

(function () {
    function css_beautify(source_text, options) {
        options = options || {};
        var indentSize = options.indent_size || 4;
        var indentCharacter = options.indent_char || ' ';
        var endWithNewline = options.end_with_newline || false;

        // compatibility
        if (typeof indentSize === "string") {
            indentSize = parseInt(indentSize, 10);
        }

        // tokenizer
        var whiteRe = /^\s+$/;
        var wordRe = /[\w$\-_]/;

        var pos = -1,
            ch;

        function next() {
            ch = source_text.charAt(++pos);
            return ch;
        }

        function peek() {
            return source_text.charAt(pos + 1);
        }

        function eatString(endChar) {
            var start = pos;
            while (next()) {
                if (ch === "\\") {
                    next();
                    next();
                } else if (ch === endChar) {
                    break;
                } else if (ch === "\n") {
                    break;
                }
            }
            return source_text.substring(start, pos + 1);
        }

        function eatWhitespace() {
            var start = pos;
            while (whiteRe.test(peek())) {
                pos++;
            }
            return pos !== start;
        }

        function skipWhitespace() {
            var start = pos;
            do {} while (whiteRe.test(next()));
            return pos !== start + 1;
        }

        function eatComment() {
            var start = pos;
            next();
            while (next()) {
                if (ch === "*" && peek() === "/") {
                    pos++;
                    break;
                }
            }

            return source_text.substring(start, pos + 1);
        }

        function lookBack(str) {
            return source_text.substring(pos - str.length, pos).toLowerCase() ===
                str;
        }

        // printer
        var indentString = source_text.match(/^[\r\n]*[\t ]*/)[0];
        var singleIndent = Array(indentSize + 1).join(indentCharacter);
        var indentLevel = 0;

        function indent() {
            indentLevel++;
            indentString += singleIndent;
        }

        function outdent() {
            indentLevel--;
            indentString = indentString.slice(0, -indentSize);
        }

        var print = {};
        print["{"] = function (ch) {
            print.singleSpace();
            output.push(ch);
            print.newLine();
        };
        print["}"] = function (ch) {
            print.newLine();
            output.push(ch);
            print.newLine();
        };

        print._lastCharWhitespace = function () {
            return whiteRe.test(output[output.length - 1]);
        }

        print.newLine = function (keepWhitespace) {
            if (!keepWhitespace) {
                while (print._lastCharWhitespace()) {
                    output.pop();
                }
            }

            if (output.length) {
                output.push('\n');
            }
            if (indentString) {
                output.push(indentString);
            }
        };
        print.singleSpace = function () {
            if (output.length && !print._lastCharWhitespace()) {
                output.push(' ');
            }
        };
        var output = [];
        if (indentString) {
            output.push(indentString);
        }
        /*_____________________--------------------_____________________*/

        while (true) {
            var isAfterSpace = skipWhitespace();

            if (!ch) {
                break;
            } else if (ch === '/' && peek() === '*') { // comment
                print.newLine();
                output.push(eatComment(), "\n", indentString);
                var header = lookBack("")
                if (header) {
                    print.newLine();
                }
            } else if (ch === '{') {
                indent();
                print["{"](ch);
            } else if (ch === '}') {
                outdent();
                print["}"](ch);
            } else if (ch === ":") {
                eatWhitespace();
                output.push(ch, " ");
            } else if (ch === '"' || ch === '\'') {
                output.push(eatString(ch));
            } else if (ch === ';') {
                output.push(ch, '\n', indentString);
            } else if (ch === '(') { // may be a url
                if (lookBack("url")) {
                    output.push(ch);
                    eatWhitespace();
                    if (next()) {
                        if (ch !== ')' && ch !== '"' && ch !== '\'') {
                            output.push(eatString(')'));
                        } else {
                            pos--;
                        }
                    }
                } else {
                    if (isAfterSpace) {
                        print.singleSpace();
                    }
                    output.push(ch);
                    eatWhitespace();
                }
            } else if (ch === ')') {
                output.push(ch);
            } else if (ch === ',') {
                eatWhitespace();
                output.push(ch);
                print.singleSpace();
            } else if (ch === ']') {
                output.push(ch);
            } else if (ch === '[' || ch === '=') { // no whitespace before or after
                eatWhitespace();
                output.push(ch);
            } else {
                if (isAfterSpace) {
                    print.singleSpace();
                }

                output.push(ch);
            }
        }

        var sweetCode = output.join('').replace(/[\n ]+$/, '');

        // establish end_with_newline
        var should = endWithNewline;
        var actually = /\n$/.test(sweetCode)
        if (should && !actually)
            sweetCode += "\n";
        else if (!should && actually)
            sweetCode = sweetCode.slice(0, -1);

        return sweetCode;
    }

    if (typeof define === "function") {
        // Add support for require.js
        define(function (require, exports, module) {
            exports.css_beautify = css_beautify;
        });
    } else if (typeof exports !== "undefined") {
        // Add support for CommonJS. Just put this file somewhere on your require.paths
        // and you will be able to `var html_beautify = require("beautify").html_beautify`.
        exports.css_beautify = css_beautify;
    } else if (typeof window !== "undefined") {
        // If we're running a web page and don't have either of the above, add our one global
        window.css_beautify = css_beautify;
    } else if (typeof global !== "undefined") {
        // If we don't even have window, try global.
        global.css_beautify = css_beautify;
    }

}());<|endoftext|>


<commit_before>var _ = require('lodash');
var moment = require('frozen-moment');
var periodTools = require('./periodTools');
var ressourcesMap = require('./ressources');
var individuSchema = require('./individu');
var menageSchema = require('./menage');
var familleSchema = require('./famille');
var foyerSchema = require('./foyerFiscal');
var common = require('./common');
var PRESTATIONS = require('../prestations');

var isNotValidValue = function(value) {
    return _.isNaN(value) || _.isUndefined(value) || value === null;
};

var getPeriods = function(dateDeValeur) {
    dateDeValeur = moment(dateDeValeur).freeze();
    return {
        thisMonth: {
            key: dateDeValeur.format('YYYY-MM')
        },
        lastMonth: {
            key: dateDeValeur.subtract(1, 'months').format('YYYY-MM')
        },
        m_2: {
            key: dateDeValeur.subtract(2, 'months').format('YYYY-MM')
        },
        m_3: {
            key: dateDeValeur.subtract(3, 'months').format('YYYY-MM')
        },
        // array containing the last 12 months (taken individually)
        last12Months: _.map(_.range(1, 12 + 1), function(monthIndex) {
            return {
                key: dateDeValeur.subtract(monthIndex, 'months').format('YYYY-MM')
            };
        }),
       rollingYear: {
            start: dateDeValeur.subtract(1, 'years').subtract(1, 'months'),
            end: dateDeValeur,
            key: 'year:' + dateDeValeur.subtract(1, 'years').format('YYYY-MM')
        },
        anneeFiscaleReference: {
            key: dateDeValeur.subtract(2, 'years').year()
        },
        rollingTrimester: {
            start: dateDeValeur.subtract(3, 'months').subtract(1, 'months'),
            end: dateDeValeur,
            key: dateDeValeur.subtract(3, 'months').format('YYYY-MM') + ':3'
        }
    };
};

var applyRessources = function(mesAidesEntity, openfiscaEntity, mappingSchema, situation) {
    var dateDeValeur = situation.dateDeValeur;
    var periods = getPeriods(dateDeValeur);

    function isPeriodWithin(agregatKey, periode) {
        return periode.isAfter(periods[agregatKey].start, 'month') && periode.isBefore(periods[agregatKey].end, 'month');
    }

    var ressourcesByType = _.groupBy(mesAidesEntity.ressources, 'type');

    _.forEach(mappingSchema, function(definitions, openfiscaKey) {
        if (! _.isArray(definitions)) {
            definitions = [definitions];
        }
        _.forEach(definitions, function(definition) {

            var srcKey = definition.src || definition;
            var fn = definition.fn;

            if (ressourcesByType[srcKey]) {
                var result = openfiscaEntity[openfiscaKey] || {};

                _.forEach(ressourcesByType[srcKey], function(item) {
                    var montant = fn ? fn(item.montant) : item.montant;
                    if (item.periode) {
                        // Période d'origine
                        if (! result[item.periode]) {
                            result[item.periode] = 0;
                        }
                        result[item.periode] += montant;

                        // Aggrégats
                        _.keys(periods).forEach(function (agregatKey) {
                            if (agregatKey != 'anneeFiscaleReference' && isPeriodWithin(agregatKey, moment(item.periode, 'YYYY-MM'))) {
                                var periodKey = periods[agregatKey].key;
                                if (! result[periodKey]) {
                                    result[periodKey] = 0;
                                }
                                result[periodKey] += montant;
                            }
                        });
                    }
                });

                // On prolonge la ressource perçue quand c'est possible
                var ressourceLastMonth = _.find(ressourcesByType[srcKey], {periode : periods.lastMonth.key});
                if (ressourceLastMonth && ressourceLastMonth.montant && !_.contains(mesAidesEntity.interruptedRessources, srcKey)) {
                    result[periods.thisMonth.key] = result[periods.thisMonth.key] || 0;
                    result[periods.thisMonth.key] += fn ? fn(ressourceLastMonth.montant) : ressourceLastMonth.montant;
                }

                openfiscaEntity[openfiscaKey] = result;

                // On suppose que les revenus pour l'année fiscale de référence sont les mêmes que pour les 12 derniers mois, si ces revenus n'ont pas encore
                // été renseignés
                var rollingYearKey = periods.rollingYear.key,
                    anneeFiscaleReferenceKey = periods.anneeFiscaleReference.key;
                if (! situation.ressourcesYearMoins2Captured) {
                    openfiscaEntity[openfiscaKey][anneeFiscaleReferenceKey] = openfiscaEntity[openfiscaKey][rollingYearKey];
                }
            }
        });
    });
};

var setNonInjectedPrestationsToZero = function(famille, individus, dateDeValeur) {
    var periods = getPeriods(dateDeValeur);
    var targetPeriods = periods.last12Months.concat([periods.rollingYear]);
    var prestationsFinancieres = _.pick(PRESTATIONS, function(definition) {
        return definition.type == Number;
    });
    _.forEach(targetPeriods, function(period) {
        _.forEach(prestationsFinancieres, function(definition, prestationName) {
            if (definition.prestationIndividuelle) {
                _.forEach(individus, function(individu) {
                    individu[prestationName] = individu[prestationName] || {};
                    individu[prestationName][period.key] = individu[prestationName][period.key] || 0;
                });
            } else {
                famille[prestationName] = famille[prestationName] || {};
                famille[prestationName][period.key] = famille[prestationName][period.key] || 0;
            }
        });
    });
};

function buildOpenFiscaEntity (mesAidesEntity, mappingSchema, situation) {
    var dateDeValeur = situation.dateDeValeur;
    var periods = getPeriods(dateDeValeur);
    var monthKeys = ['thisMonth', 'lastMonth', 'm_2', 'm_3'].map(function (month) {
        return periods[month].key;
    });

    var result = {};
    _.forEach(mappingSchema, function(definition, openfiscaKey) {
        var params = _.isString(definition) ? { src: definition } : definition;

        if (params.values) {
            result[openfiscaKey] = params.values[mesAidesEntity[params.src]];
        } else if (params.fn) {
            result[openfiscaKey] = params.src ? params.fn(mesAidesEntity[params.src], mesAidesEntity, situation) : params.fn(mesAidesEntity, situation);
        } else {
            result[openfiscaKey] = mesAidesEntity[params.src];
        }

        if (params.round && _.isNumber(result[openfiscaKey])) {
            result[openfiscaKey] = Math.round(result[openfiscaKey]);
        }

        // Supprime les null (mal supportés par OpenFisca)
        if (isNotValidValue(result[openfiscaKey])) {
            if ('default' in params) result[openfiscaKey] = params.default;
            else delete result[openfiscaKey];
        }

        // On étend la valeur aux 3 derniers mois, succeptibles d'être appelés par le RSA et la PPA dans Openfisca
        var value = result[openfiscaKey];
        if (! _.isUndefined(value) && ! params.doNotExtend) {
            result[openfiscaKey] = {};
            monthKeys.forEach(function(monthKey) {
                result[openfiscaKey][monthKey] = value;
            });
        }
    });
    return result;
}

var mapIndividus = exports.mapIndividus = function (situation) {
    var individus = _.filter(situation.individus, function(individu) {
        return common.isIndividuValid(individu, situation);
    });

    return _.map(individus, function(individu) {
        if (individu.role === 'demandeur') {
            _.extend(individu, situation.patrimoine);

        }
        var openfiscaIndividu = buildOpenFiscaEntity(individu, individuSchema, situation);
        applyRessources(individu, openfiscaIndividu, ressourcesMap.individu, situation);
        return openfiscaIndividu;
    });
};

var mapFamille = function(situation) {
    var famille = buildOpenFiscaEntity(situation, familleSchema, situation);
    var ressources = [];
    _.forEach(situation.individus, function(individu) {
        ressources = ressources.concat(individu.ressources);
    });
    applyRessources({ ressources: ressources }, famille, ressourcesMap.famille, situation);

    return famille;
};

var mapFoyerFiscal = exports.mapFoyerFiscal = function(situation) {
    var foyerFiscal = buildOpenFiscaEntity(situation, foyerSchema, situation);
    var ressources = [];
    _.forEach(situation.individus, function(individu) {
        ressources = ressources.concat(individu.ressources);
    });
    applyRessources({ ressources: ressources }, foyerFiscal, ressourcesMap.foyerFiscal, situation);

    return foyerFiscal;
};

exports.buildOpenFiscaRequest = function(situation, debug) {
    var famille = mapFamille(situation),
        individus = mapIndividus(situation),
        foyerFiscal = mapFoyerFiscal(situation);

    setNonInjectedPrestationsToZero(famille, individus, situation.dateDeValeur);

    return {
        intermediate_variables: debug,
        labels: true,
        base_reforms: ['aides_cd93'],
        scenarios: [{
            test_case: {
                familles: [ famille ],
                foyers_fiscaux: [ foyerFiscal ],
                individus: individus,
                menages: [ buildOpenFiscaEntity(situation, menageSchema, situation) ]
            },
            period: 'month:' + periodTools.toOpenFiscaFormat(situation.dateDeValeur)
        }],
        variables: _.keys(PRESTATIONS)
    };
};
<commit_msg>Rename periods keys<commit_after>var _ = require('lodash');
var moment = require('frozen-moment');
var periodTools = require('./periodTools');
var ressourcesMap = require('./ressources');
var individuSchema = require('./individu');
var menageSchema = require('./menage');
var familleSchema = require('./famille');
var foyerSchema = require('./foyerFiscal');
var common = require('./common');
var PRESTATIONS = require('../prestations');

var isNotValidValue = function(value) {
    return _.isNaN(value) || _.isUndefined(value) || value === null;
};

var getPeriods = function(dateDeValeur) {
    dateDeValeur = moment(dateDeValeur).freeze();
    return {
        thisMonth: {
            key: dateDeValeur.format('YYYY-MM')
        },
        '1MonthsAgo': {
            key: dateDeValeur.subtract(1, 'months').format('YYYY-MM')
        },
        '2MonthsAgo': {
            key: dateDeValeur.subtract(2, 'months').format('YYYY-MM')
        },
        '3MonthsAgo': {
            key: dateDeValeur.subtract(3, 'months').format('YYYY-MM')
        },
        // array containing the last 12 months (taken individually)
        last12Months: _.map(_.range(1, 12 + 1), function(monthIndex) {
            return {
                key: dateDeValeur.subtract(monthIndex, 'months').format('YYYY-MM')
            };
        }),
       rollingYear: {
            start: dateDeValeur.subtract(1, 'years').subtract(1, 'months'),
            end: dateDeValeur,
            key: 'year:' + dateDeValeur.subtract(1, 'years').format('YYYY-MM')
        },
        anneeFiscaleReference: {
            key: dateDeValeur.subtract(2, 'years').year()
        },
        rollingTrimester: {
            start: dateDeValeur.subtract(3, 'months').subtract(1, 'months'),
            end: dateDeValeur,
            key: dateDeValeur.subtract(3, 'months').format('YYYY-MM') + ':3'
        }
    };
};

var applyRessources = function(mesAidesEntity, openfiscaEntity, mappingSchema, situation) {
    var dateDeValeur = situation.dateDeValeur;
    var periods = getPeriods(dateDeValeur);

    function isPeriodWithin(agregatKey, periode) {
        return periode.isAfter(periods[agregatKey].start, 'month') && periode.isBefore(periods[agregatKey].end, 'month');
    }

    var ressourcesByType = _.groupBy(mesAidesEntity.ressources, 'type');

    _.forEach(mappingSchema, function(definitions, openfiscaKey) {
        if (! _.isArray(definitions)) {
            definitions = [definitions];
        }
        _.forEach(definitions, function(definition) {

            var srcKey = definition.src || definition;
            var fn = definition.fn;

            if (ressourcesByType[srcKey]) {
                var result = openfiscaEntity[openfiscaKey] || {};

                _.forEach(ressourcesByType[srcKey], function(item) {
                    var montant = fn ? fn(item.montant) : item.montant;
                    if (item.periode) {
                        // Période d'origine
                        if (! result[item.periode]) {
                            result[item.periode] = 0;
                        }
                        result[item.periode] += montant;

                        // Aggrégats
                        _.keys(periods).forEach(function (agregatKey) {
                            if (agregatKey != 'anneeFiscaleReference' && isPeriodWithin(agregatKey, moment(item.periode, 'YYYY-MM'))) {
                                var periodKey = periods[agregatKey].key;
                                if (! result[periodKey]) {
                                    result[periodKey] = 0;
                                }
                                result[periodKey] += montant;
                            }
                        });
                    }
                });

                // On prolonge la ressource perçue quand c'est possible
                var ressourceLastMonth = _.find(ressourcesByType[srcKey], {periode : periods['1MonthsAgo'].key});
                if (ressourceLastMonth && ressourceLastMonth.montant && !_.contains(mesAidesEntity.interruptedRessources, srcKey)) {
                    result[periods.thisMonth.key] = result[periods.thisMonth.key] || 0;
                    result[periods.thisMonth.key] += fn ? fn(ressourceLastMonth.montant) : ressourceLastMonth.montant;
                }

                openfiscaEntity[openfiscaKey] = result;

                // On suppose que les revenus pour l'année fiscale de référence sont les mêmes que pour les 12 derniers mois, si ces revenus n'ont pas encore
                // été renseignés
                var rollingYearKey = periods.rollingYear.key,
                    anneeFiscaleReferenceKey = periods.anneeFiscaleReference.key;
                if (! situation.ressourcesYearMoins2Captured) {
                    openfiscaEntity[openfiscaKey][anneeFiscaleReferenceKey] = openfiscaEntity[openfiscaKey][rollingYearKey];
                }
            }
        });
    });
};

var setNonInjectedPrestationsToZero = function(famille, individus, dateDeValeur) {
    var periods = getPeriods(dateDeValeur);
    var targetPeriods = periods.last12Months.concat([periods.rollingYear]);
    var prestationsFinancieres = _.pick(PRESTATIONS, function(definition) {
        return definition.type == Number;
    });
    _.forEach(targetPeriods, function(period) {
        _.forEach(prestationsFinancieres, function(definition, prestationName) {
            if (definition.prestationIndividuelle) {
                _.forEach(individus, function(individu) {
                    individu[prestationName] = individu[prestationName] || {};
                    individu[prestationName][period.key] = individu[prestationName][period.key] || 0;
                });
            } else {
                famille[prestationName] = famille[prestationName] || {};
                famille[prestationName][period.key] = famille[prestationName][period.key] || 0;
            }
        });
    });
};

function buildOpenFiscaEntity (mesAidesEntity, mappingSchema, situation) {
    var dateDeValeur = situation.dateDeValeur;
    var periods = getPeriods(dateDeValeur);
    var monthKeys = ['thisMonth', '1MonthsAgo', '2MonthsAgo', '3MonthsAgo'].map(function (month) {
        return periods[month].key;
    });

    var result = {};
    _.forEach(mappingSchema, function(definition, openfiscaKey) {
        var params = _.isString(definition) ? { src: definition } : definition;

        if (params.values) {
            result[openfiscaKey] = params.values[mesAidesEntity[params.src]];
        } else if (params.fn) {
            result[openfiscaKey] = params.src ? params.fn(mesAidesEntity[params.src], mesAidesEntity, situation) : params.fn(mesAidesEntity, situation);
        } else {
            result[openfiscaKey] = mesAidesEntity[params.src];
        }

        if (params.round && _.isNumber(result[openfiscaKey])) {
            result[openfiscaKey] = Math.round(result[openfiscaKey]);
        }

        // Supprime les null (mal supportés par OpenFisca)
        if (isNotValidValue(result[openfiscaKey])) {
            if ('default' in params) result[openfiscaKey] = params.default;
            else delete result[openfiscaKey];
        }

        // On étend la valeur aux 3 derniers mois, succeptibles d'être appelés par le RSA et la PPA dans Openfisca
        var value = result[openfiscaKey];
        if (! _.isUndefined(value) && ! params.doNotExtend) {
            result[openfiscaKey] = {};
            monthKeys.forEach(function(monthKey) {
                result[openfiscaKey][monthKey] = value;
            });
        }
    });
    return result;
}

var mapIndividus = exports.mapIndividus = function (situation) {
    var individus = _.filter(situation.individus, function(individu) {
        return common.isIndividuValid(individu, situation);
    });

    return _.map(individus, function(individu) {
        if (individu.role === 'demandeur') {
            _.extend(individu, situation.patrimoine);

        }
        var openfiscaIndividu = buildOpenFiscaEntity(individu, individuSchema, situation);
        applyRessources(individu, openfiscaIndividu, ressourcesMap.individu, situation);
        return openfiscaIndividu;
    });
};

var mapFamille = function(situation) {
    var famille = buildOpenFiscaEntity(situation, familleSchema, situation);
    var ressources = [];
    _.forEach(situation.individus, function(individu) {
        ressources = ressources.concat(individu.ressources);
    });
    applyRessources({ ressources: ressources }, famille, ressourcesMap.famille, situation);

    return famille;
};

var mapFoyerFiscal = exports.mapFoyerFiscal = function(situation) {
    var foyerFiscal = buildOpenFiscaEntity(situation, foyerSchema, situation);
    var ressources = [];
    _.forEach(situation.individus, function(individu) {
        ressources = ressources.concat(individu.ressources);
    });
    applyRessources({ ressources: ressources }, foyerFiscal, ressourcesMap.foyerFiscal, situation);

    return foyerFiscal;
};

exports.buildOpenFiscaRequest = function(situation, debug) {
    var famille = mapFamille(situation),
        individus = mapIndividus(situation),
        foyerFiscal = mapFoyerFiscal(situation);

    setNonInjectedPrestationsToZero(famille, individus, situation.dateDeValeur);

    return {
        intermediate_variables: debug,
        labels: true,
        base_reforms: ['aides_cd93'],
        scenarios: [{
            test_case: {
                familles: [ famille ],
                foyers_fiscaux: [ foyerFiscal ],
                individus: individus,
                menages: [ buildOpenFiscaEntity(situation, menageSchema, situation) ]
            },
            period: 'month:' + periodTools.toOpenFiscaFormat(situation.dateDeValeur)
        }],
        variables: _.keys(PRESTATIONS)
    };
};
<|endoftext|>


<commit_before>Meteor.publish('messages', function (roomId, limit) {
    var room = Rooms.findOne({_id: roomId});
    if (room && (!room.isPrivate || _(room.invited).contains(this.userId))) {
        var query = {roomId: roomId, type: {$ne: 'feedback'}};
        var thresholdMessage = Messages.findOne(query, {skip: limit, sort: {timestamp: -1}});
        if (thresholdMessage && thresholdMessage.timestamp) {
            query.timestamp = {$gt: thresholdMessage.timestamp};
        }
        return Messages.find(query, {sort: {timestamp: -1}});
    }
    else {
        throw new Meteor.Error(503, 'No soup for you hackerpants.');
    }
});
Meteor.publish('feedbackMessages', function (roomId) {
    var now = new Date().getTime();
    return Messages.find({roomId: roomId, type: 'feedback', userId: this.userId, timestamp: {$gt: now}}, {
        limit: 10,
        sort: {timestamp: -1}
    });
});
Meteor.publish('message', function (messageId) {
    return Messages.find({_id: messageId});
});
Meteor.publish('messageContextAbove', function (messageId) {
    var message = Messages.findOne({_id: messageId});
    return [Messages.find({
        roomId: message.roomId,
        type: {$ne: 'feedback'},
        timestamp: {$gt: message.timestamp}
    }, {limit: 2, sort: {timestamp: 1}})];
});
Meteor.publish('messageContextBelow', function (messageId) {
    var message = Messages.findOne({_id: messageId});
    return [Messages.find({
        roomId: message.roomId,
        type: {$ne: 'feedback'},
        timestamp: {$lt: message.timestamp}
    }, {limit: 2, sort: {timestamp: -1}})];
});
Meteor.publish('currentRooms', function () {
    return Rooms.find({users: this.userId});
});
Meteor.publish('availableRooms', function () {
    return Rooms.find({$or: [{isPrivate: false}, {isPrivate: true, invited: this.userId}]});
});
Meteor.publish('users', function () {
    return Meteor.users.find({}, {
        fields: {
            _id: 1,
            username: 1,
            "profile.avatar":1,
            "profile.color":1,
            "status.idle": 1,
            "status.offline": 1,
            "status.online": 1,
            "status.lastTyping": 1,
            "status.lastActiveRoom": 1,
            "status.currentRoom": 1,
            "status.lastActivity": 1,
            "status.lastLogin.date": 1
        }
    });
});
Meteor.publish('myPreferences', function () {
    return Meteor.users.find({_id: this.userId}, {
        fields: {
            _id: 1,
            preferences: 1,
            profile: 1
        }
    });
});
Meteor.publish('myCursors', function () {
    return Meteor.users.find({_id: this.userId}, {
        fields: {
            _id: 1,
            cursors: 1,
        }
    });
});
Meteor.publish('notifications', function () {
    return Notifications.find({userId: this.userId});
});
Meteor.publish('emojis', function () {
    return Emojis.find();
});
Meteor.publish('memes', function () {
    return Memes.find();
});

Meteor.publish('newMessages', function () {
    // TODO: Reactivity
    var rooms = Rooms.find({users: this.userId}).fetch();
    var roomIds = _(rooms).map(function (room) {
        return room._id;
    });
    var now = new Date().getTime();
    return Messages.find({roomId: {$in: roomIds}, type: {$ne: 'feedback'}, timestamp: {$gt: now}});
});

Meteor.publish('newMessagesForRoom', function (roomId) {
    var room = Rooms.findOne({_id: roomId});
    if (room && (!room.isPrivate || _(room.invited).contains(this.userId))) {
        var query = {roomId: roomId, type: {$ne: 'feedback'}};
        return Messages.find(query, {sort: {timestamp: -1}, limit: 5});
    }
    else {
        throw new Meteor.Error(503, 'No soup for you hackerpants.');
    }
});

Meteor.publish('roomInvitations', function () {
    return RoomInvitations.find({
        active: true,
        invitedUser: this.userId
    });
});

Meteor.publish('starredMessages', function () {
    return Messages.find({likedBy: this.userId}); // TODO: Security check
});

Meteor.publish('changelogs', function () {
    return Changelogs.find({});
});

// Indexes
Meteor.startup(function(){
    // Supports newMessages, newMessagesForRoom, and messages subscriptions
   Messages._ensureIndex({"roomId": 1, "timestamp": -1, "type": 1});
});<commit_msg>add ensure index for notifications to publications file - other formatting<commit_after>Meteor.publish('messages', function (roomId, limit) {
    var room = Rooms.findOne({_id: roomId});
    if (room && (!room.isPrivate || _(room.invited).contains(this.userId))) {
        var query = {roomId: roomId, type: {$ne: 'feedback'}};
        var thresholdMessage = Messages.findOne(query, {skip: limit, sort: {timestamp: -1}});
        if (thresholdMessage && thresholdMessage.timestamp) {
            query.timestamp = {$gt: thresholdMessage.timestamp};
        }
        return Messages.find(query, {sort: {timestamp: -1}});
    }
    else {
        throw new Meteor.Error(503, 'No soup for you hackerpants.');
    }
});
Meteor.publish('feedbackMessages', function (roomId) {
    var now = new Date().getTime();
    return Messages.find({roomId: roomId, type: 'feedback', userId: this.userId, timestamp: {$gt: now}}, {
        limit: 10,
        sort: {timestamp: -1}
    });
});
Meteor.publish('message', function (messageId) {
    return Messages.find({_id: messageId});
});
Meteor.publish('messageContextAbove', function (messageId) {
    var message = Messages.findOne({_id: messageId});
    return [Messages.find({
        roomId: message.roomId,
        type: {$ne: 'feedback'},
        timestamp: {$gt: message.timestamp}
    }, {limit: 2, sort: {timestamp: 1}})];
});
Meteor.publish('messageContextBelow', function (messageId) {
    var message = Messages.findOne({_id: messageId});
    return [Messages.find({
        roomId: message.roomId,
        type: {$ne: 'feedback'},
        timestamp: {$lt: message.timestamp}
    }, {limit: 2, sort: {timestamp: -1}})];
});
Meteor.publish('currentRooms', function () {
    return Rooms.find({users: this.userId});
});
Meteor.publish('availableRooms', function () {
    return Rooms.find({$or: [{isPrivate: false}, {isPrivate: true, invited: this.userId}]});
});
Meteor.publish('users', function () {
    return Meteor.users.find({}, {
        fields: {
            _id: 1,
            username: 1,
            "profile.avatar": 1,
            "profile.color": 1,
            "status.idle": 1,
            "status.offline": 1,
            "status.online": 1,
            "status.lastTyping": 1,
            "status.lastActiveRoom": 1,
            "status.currentRoom": 1,
            "status.lastActivity": 1,
            "status.lastLogin.date": 1
        }
    });
});
Meteor.publish('myPreferences', function () {
    return Meteor.users.find({_id: this.userId}, {
        fields: {
            _id: 1,
            preferences: 1,
            profile: 1
        }
    });
});
Meteor.publish('myCursors', function () {
    return Meteor.users.find({_id: this.userId}, {
        fields: {
            _id: 1,
            cursors: 1,
        }
    });
});
Meteor.publish('notifications', function () {
    return Notifications.find({userId: this.userId});
});
Meteor.publish('emojis', function () {
    return Emojis.find();
});
Meteor.publish('memes', function () {
    return Memes.find();
});

Meteor.publish('newMessages', function () {
    // TODO: Reactivity
    var rooms = Rooms.find({users: this.userId}).fetch();
    var roomIds = _(rooms).map(function (room) {
        return room._id;
    });
    var now = new Date().getTime();
    return Messages.find({roomId: {$in: roomIds}, type: {$ne: 'feedback'}, timestamp: {$gt: now}});
});

Meteor.publish('newMessagesForRoom', function (roomId) {
    var room = Rooms.findOne({_id: roomId});
    if (room && (!room.isPrivate || _(room.invited).contains(this.userId))) {
        var query = {roomId: roomId, type: {$ne: 'feedback'}};
        return Messages.find(query, {sort: {timestamp: -1}, limit: 5});
    }
    else {
        throw new Meteor.Error(503, 'No soup for you hackerpants.');
    }
});

Meteor.publish('roomInvitations', function () {
    return RoomInvitations.find({
        active: true,
        invitedUser: this.userId
    });
});

Meteor.publish('starredMessages', function () {
    return Messages.find({likedBy: this.userId}); // TODO: Security check
});

Meteor.publish('changelogs', function () {
    return Changelogs.find({});
});

// Indexes
Meteor.startup(function () {
    // Supports newMessages, newMessagesForRoom, and messages subscriptions
    Messages._ensureIndex({"roomId": 1, "timestamp": -1, "type": 1});

    // Supports notifications subscription
    Notifications._ensureIndex({"roomId": 1, "seen": 1, "userId": 1});
});<|endoftext|>


<commit_before>/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
/*

  The MIT License (MIT)

  Copyright (c) 2007-2013 Einar Lielmanis and contributors.

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.

 CSS Beautifier
---------------

    Written by Harutyun Amirjanyan, (amirjanyan@gmail.com)

    Based on code initially developed by: Einar Lielmanis, <elfz@laacz.lv>
        http://jsbeautifier.org/

    Usage:
        css_beautify(source_text);
        css_beautify(source_text, options);

    The options are:
        indent_size (default 4)          — indentation size,
        indent_char (default space)      — character to indent with,

    e.g

    css_beautify(css_source_text, {
      'indent_size': 1,
      'indent_char': '\t'
    });
*/

// http://www.w3.org/TR/CSS21/syndata.html#tokenization
// http://www.w3.org/TR/css3-syntax/

(function() {
    function css_beautify(source_text, options) {
        options = options || {};
        var indentSize = options.indent_size || 4;
        var indentCharacter = options.indent_char || ' ';

        // compatibility
        if (typeof indentSize === "string") {
            indentSize = parseInt(indentSize, 10);
        }

        // tokenizer
        var whiteRe = /^\s+$/;
        var wordRe = /[\w$\-_]/;

        var pos = -1,
            ch;

        function next() {
            ch = source_text.charAt(++pos);
            return ch;
        }

        function peek() {
            return source_text.charAt(pos + 1);
        }

        function eatString(comma) {
            var start = pos;
            while (next()) {
                if (ch === "\\") {
                    next();
                    next();
                } else if (ch === comma) {
                    break;
                } else if (ch === "\n") {
                    break;
                }
            }
            return source_text.substring(start, pos + 1);
        }

        function eatWhitespace() {
            var start = pos;
            while (whiteRe.test(peek())) {
                pos++;
            }
            return pos !== start;
        }

        function skipWhitespace() {
            var start = pos;
            do {} while (whiteRe.test(next()));
            return pos !== start + 1;
        }

        function eatComment() {
            var start = pos;
            next();
            while (next()) {
                if (ch === "*" && peek() === "/") {
                    pos++;
                    break;
                }
            }

            return source_text.substring(start, pos + 1);
        }

        function lookBack(str) {
            return source_text.substring(pos - str.length, pos).toLowerCase() === str;
        }

        // printer
        var indentString = source_text.match(/^[\r\n]*[\t ]*/)[0];
        var singleIndent = Array(indentSize + 1).join(indentCharacter);
        var indentLevel = 0;

        function indent() {
            indentLevel++;
            indentString += singleIndent;
        }

        function outdent() {
            indentLevel--;
            indentString = indentString.slice(0, -indentSize);
        }

        var print = {};
        print["{"] = function(ch) {
            print.singleSpace();
            output.push(ch);
            print.newLine();
        };
        print["}"] = function(ch) {
            print.newLine();
            output.push(ch);
            print.newLine();
        };

        print.newLine = function(keepWhitespace) {
            if (!keepWhitespace) {
                while (whiteRe.test(output[output.length - 1])) {
                    output.pop();
                }
            }

            if (output.length) {
                output.push('\n');
            }
            if (indentString) {
                output.push(indentString);
            }
        };
        print.singleSpace = function() {
            if (output.length && !whiteRe.test(output[output.length - 1])) {
                output.push(' ');
            }
        };
        var output = [];
        if (indentString) {
            output.push(indentString);
        }
        /*_____________________--------------------_____________________*/

        while (true) {
            var isAfterSpace = skipWhitespace();

            if (!ch) {
                break;
            }

            if (ch === '{') {
                indent();
                print["{"](ch);
            } else if (ch === '}') {
                outdent();
                print["}"](ch);
            } else if (ch === '"' || ch === '\'') {
                output.push(eatString(ch));
            } else if (ch === ';') {
                output.push(ch, '\n', indentString);
            } else if (ch === '/' && peek() === '*') { // comment
                print.newLine();
                output.push(eatComment(), "\n", indentString);
            } else if (ch === '(') { // may be a url
                if (lookBack("url")) {
                    output.push(ch);
                    eatWhitespace();
                    if (next()) {
                        if (ch !== ')' && ch !== '"' && ch !== '\'') {
                            output.push(eatString(')'));
                        } else {
                            pos--;
                        }
                    }
                } else {
                    if (isAfterSpace) {
                        print.singleSpace();
                    }
                    output.push(ch);
                    eatWhitespace();
                }
            } else if (ch === ')') {
                output.push(ch);
            } else if (ch === ',') {
                eatWhitespace();
                output.push(ch);
                print.singleSpace();
            } else if (ch === ']') {
                output.push(ch);
            } else if (ch === '[' || ch === '=') { // no whitespace before or after
                eatWhitespace();
                output.push(ch);
            } else {
                if (isAfterSpace) {
                    print.singleSpace();
                }

                output.push(ch);
            }
        }

        var sweetCode = output.join('').replace(/[\n ]+$/, '');
        return sweetCode;
    }

    if (typeof define === "function") {
        // Add support for require.js
        define(function(require, exports, module) {
            exports.css_beautify = css_beautify;
        });
    } else if (typeof exports !== "undefined") {
        // Add support for CommonJS. Just put this file somewhere on your require.paths
        // and you will be able to `var html_beautify = require("beautify").html_beautify`.
        exports.css_beautify = css_beautify;
    } else if (typeof window !== "undefined") {
        // If we're running a web page and don't have either of the above, add our one global
        window.css_beautify = css_beautify;
    } else if (typeof global !== "undefined") {
        // If we don't even have window, try global.
        global.css_beautify = css_beautify;
    }

}());
<commit_msg>beautify with js-beautify<commit_after>/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
/*

  The MIT License (MIT)

  Copyright (c) 2007-2013 Einar Lielmanis and contributors.

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.

 CSS Beautifier
---------------

    Written by Harutyun Amirjanyan, (amirjanyan@gmail.com)

    Based on code initially developed by: Einar Lielmanis, <elfz@laacz.lv>
        http://jsbeautifier.org/

    Usage:
        css_beautify(source_text);
        css_beautify(source_text, options);

    The options are:
        indent_size (default 4)          — indentation size,
        indent_char (default space)      — character to indent with,

    e.g

    css_beautify(css_source_text, {
      'indent_size': 1,
      'indent_char': '\t'
    });
*/

// http://www.w3.org/TR/CSS21/syndata.html#tokenization
// http://www.w3.org/TR/css3-syntax/

(function () {
    function css_beautify(source_text, options) {
        options = options || {};
        var indentSize = options.indent_size || 4;
        var indentCharacter = options.indent_char || ' ';

        // compatibility
        if (typeof indentSize === "string") {
            indentSize = parseInt(indentSize, 10);
        }

        // tokenizer
        var whiteRe = /^\s+$/;
        var wordRe = /[\w$\-_]/;

        var pos = -1,
            ch;

        function next() {
            ch = source_text.charAt(++pos);
            return ch;
        }

        function peek() {
            return source_text.charAt(pos + 1);
        }

        function eatString(comma) {
            var start = pos;
            while (next()) {
                if (ch === "\\") {
                    next();
                    next();
                } else if (ch === comma) {
                    break;
                } else if (ch === "\n") {
                    break;
                }
            }
            return source_text.substring(start, pos + 1);
        }

        function eatWhitespace() {
            var start = pos;
            while (whiteRe.test(peek())) {
                pos++;
            }
            return pos !== start;
        }

        function skipWhitespace() {
            var start = pos;
            do {} while (whiteRe.test(next()));
            return pos !== start + 1;
        }

        function eatComment() {
            var start = pos;
            next();
            while (next()) {
                if (ch === "*" && peek() === "/") {
                    pos++;
                    break;
                }
            }

            return source_text.substring(start, pos + 1);
        }

        function lookBack(str) {
            return source_text.substring(pos - str.length, pos).toLowerCase() ===
                str;
        }

        // printer
        var indentString = source_text.match(/^[\r\n]*[\t ]*/)[0];
        var singleIndent = Array(indentSize + 1).join(indentCharacter);
        var indentLevel = 0;

        function indent() {
            indentLevel++;
            indentString += singleIndent;
        }

        function outdent() {
            indentLevel--;
            indentString = indentString.slice(0, -indentSize);
        }

        var print = {};
        print["{"] = function (ch) {
            print.singleSpace();
            output.push(ch);
            print.newLine();
        };
        print["}"] = function (ch) {
            print.newLine();
            output.push(ch);
            print.newLine();
        };

        print.newLine = function (keepWhitespace) {
            if (!keepWhitespace) {
                while (whiteRe.test(output[output.length - 1])) {
                    output.pop();
                }
            }

            if (output.length) {
                output.push('\n');
            }
            if (indentString) {
                output.push(indentString);
            }
        };
        print.singleSpace = function() {
            if (output.length && !whiteRe.test(output[output.length - 1])) {
                output.push(' ');
            }
        };
        var output = [];
        if (indentString) {
            output.push(indentString);
        }
        /*_____________________--------------------_____________________*/

        while (true) {
            var isAfterSpace = skipWhitespace();

            if (!ch) {
                break;
            }

            if (ch === '{') {
                indent();
                print["{"](ch);
            } else if (ch === '}') {
                outdent();
                print["}"](ch);
            } else if (ch === '"' || ch === '\'') {
                output.push(eatString(ch));
            } else if (ch === ';') {
                output.push(ch, '\n', indentString);
            } else if (ch === '/' && peek() === '*') { // comment
                print.newLine();
                output.push(eatComment(), "\n", indentString);
            } else if (ch === '(') { // may be a url
                if (lookBack("url")) {
                    output.push(ch);
                    eatWhitespace();
                    if (next()) {
                        if (ch !== ')' && ch !== '"' && ch !== '\'') {
                            output.push(eatString(')'));
                        } else {
                            pos--;
                        }
                    }
                } else {
                    if (isAfterSpace) {
                        print.singleSpace();
                    }
                    output.push(ch);
                    eatWhitespace();
                }
            } else if (ch === ')') {
                output.push(ch);
            } else if (ch === ',') {
                eatWhitespace();
                output.push(ch);
                print.singleSpace();
            } else if (ch === ']') {
                output.push(ch);
            } else if (ch === '[' || ch === '=') { // no whitespace before or after
                eatWhitespace();
                output.push(ch);
            } else {
                if (isAfterSpace) {
                    print.singleSpace();
                }

                output.push(ch);
            }
        }

        var sweetCode = output.join('').replace(/[\n ]+$/, '');
        return sweetCode;
    }

    if (typeof define === "function") {
        // Add support for require.js
        define(function (require, exports, module) {
            exports.css_beautify = css_beautify;
        });
    } else if (typeof exports !== "undefined") {
        // Add support for CommonJS. Just put this file somewhere on your require.paths
        // and you will be able to `var html_beautify = require("beautify").html_beautify`.
        exports.css_beautify = css_beautify;
    } else if (typeof window !== "undefined") {
        // If we're running a web page and don't have either of the above, add our one global
        window.css_beautify = css_beautify;
    } else if (typeof global !== "undefined") {
        // If we don't even have window, try global.
        global.css_beautify = css_beautify;
    }

}());<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * A Screen is the largest chunk of a simulation. (Java sims used the term Module, but that term
 * is too overloaded to use with JavaScript and Git.)
 *

 * When creating a Sim, Screens are supplied as the arguments. They can be specified as object literals or through instances of this class.
 * This class may centralize default behavior or state for Screens in the future, but right now it only allows you to create
 * Sims without using named parameter object literals.
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  var Dimension2 = require( 'DOT/Dimension2' );

  /**
   * @param {String} name
   * @param {Node} homeScreenIcon optimal size is 548x373, will be scaled by HomeScreen
   * @param {function} createModel
   * @param {function} createView
   * @param {*} options
   * @constructor
   */
  function Screen( name, homeScreenIcon, createModel, createView, options ) {

    options = _.extend( {
      backgroundColor: 'white',
      navigationBarIcon: homeScreenIcon // must be a minimum of 147x100 and have an aspect ratio of 548/373=1.469.  See https://github.com/phetsims/joist/issues/76
    }, options );

    this.name = name;
    this.homeScreenIcon = homeScreenIcon;
    this.navigationBarIcon = options.navigationBarIcon;
    this.backgroundColor = options.backgroundColor;
    this.createModel = createModel;
    this.createView = createView;
  }

  Screen.HOME_SCREEN_ICON_SIZE = new Dimension2( 548, 373 );
  Screen.NAVBAR_ICON_SIZE = new Dimension2( 147, 100 );

  return Screen;
} );<commit_msg>use {Object} instead of {*} as type expression for options param<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * A Screen is the largest chunk of a simulation. (Java sims used the term Module, but that term
 * is too overloaded to use with JavaScript and Git.)
 *

 * When creating a Sim, Screens are supplied as the arguments. They can be specified as object literals or through instances of this class.
 * This class may centralize default behavior or state for Screens in the future, but right now it only allows you to create
 * Sims without using named parameter object literals.
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  var Dimension2 = require( 'DOT/Dimension2' );

  /**
   * @param {String} name
   * @param {Node} homeScreenIcon optimal size is 548x373, will be scaled by HomeScreen
   * @param {function} createModel
   * @param {function} createView
   * @param {Object} options
   * @constructor
   */
  function Screen( name, homeScreenIcon, createModel, createView, options ) {

    options = _.extend( {
      backgroundColor: 'white',
      navigationBarIcon: homeScreenIcon // must be a minimum of 147x100 and have an aspect ratio of 548/373=1.469.  See https://github.com/phetsims/joist/issues/76
    }, options );

    this.name = name;
    this.homeScreenIcon = homeScreenIcon;
    this.navigationBarIcon = options.navigationBarIcon;
    this.backgroundColor = options.backgroundColor;
    this.createModel = createModel;
    this.createView = createView;
  }

  Screen.HOME_SCREEN_ICON_SIZE = new Dimension2( 548, 373 );
  Screen.NAVBAR_ICON_SIZE = new Dimension2( 147, 100 );

  return Screen;
} );<|endoftext|>


<commit_before>function debugSleep(ms) {
    if (Meteor.settings.debug) {
        Meteor._sleepForMs(ms);
    }
}

function clearFilter(inFilter) {
    inFilter = inFilter || {};
    const filter = {};
    Object.keys(inFilter).forEach((k) => {
        if (inFilter[k]) {
            filter[k] = inFilter[k]
        }
    });
    return filter;
}

function generateOptions(limit = 0, omitFields = [], sortField = "submitted", reverse = true) {
    const options = {};
    if (limit && limit > 0) {
        options.limit = limit;
    }
    if (omitFields && omitFields.length) {
        options.fields = {};
        for (let f of omitFields) {
            options.fields[f] = false;
        }
    }
    if (sortField) {
        options.sort = {};
        options.sort[sortField] = reverse ? -1 : 1;
    }
    return options;
}

Meteor.smartPublish('articles', function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("articles", "imageId", doc => Images.find(doc.imageId));
    return Articles.find(filter, generateOptions(limit, ["text"], "createdAt"));
});

Meteor.smartPublish("article", function (slug) {
    this.addDependency("articles", "imageId", doc => Images.find(doc.imageId));
    return Articles.find({slug: slug});
});

Meteor.smartPublish("tempArticle", function () {
    const userId = this.userId || "";
    if (userId && Roles.userIsInRole(userId, ['admin'])) {
        return TempArticles.find({authorId: userId});
    }
    return [];
});

Meteor.publish("tags", function () {
    return Tags.find();
});

Meteor.smartPublish('jobs', function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("jobs", "companyName", doc => Companies.find({name: doc.companyName}));
    this.addDependency("companies", "imageId", doc => Images.find(doc.imageId));
    return Jobs.find(filter, generateOptions(limit, ["description"], "createdAt"));
});

Meteor.smartPublish("job", function (slug) {
    this.addDependency("jobs", "companyName", doc => Companies.find({name: doc.companyName}));
    this.addDependency("companies", "imageId", doc => Images.find(doc.imageId));
    return Jobs.find({slug: slug});
});

Meteor.smartPublish("companies", function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("companies", "imageId", doc =>  Images.find(doc.imageId));
    return Companies.find(filter, generateOptions(limit, ["text"]));
});

Meteor.publish("companyNames", function () {
    return Companies.find({}, {fields: {name: 1}});
});

Meteor.smartPublish("company", function (slug) {
    this.addDependency("companies", "imageId", doc => Images.find(doc.imageId));
    return Companies.find({slug: slug});
});

Meteor.publish("featuredCompanies", function () {
    return FeaturedCompanies.find({});
});

Meteor.smartPublish("projects", function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("projects", "imageId", doc => Images.find(doc.imageId));
    this.addDependency("projects", "listImageId", doc => doc.listImageId ? Images.find(doc.listImageId) : []);
    return Projects.find(filter, generateOptions(limit, ["description"], "createdAt", true));
});

Meteor.smartPublish("project", function (slug) {
    this.addDependency("projects", "imageId", doc => Images.find(doc.imageId));
    if (this.userId) {
        this.addDependency("projects", "_id",
                doc => Participations.find({authorId: this.userId, projectId: doc._id}))
    }
    return Projects.find({slug: slug});
});

Meteor.publish("featuredProjects", function (limit) {
    return Projects.find({}, generateOptions(limit, ["description"], "importance", true));
});

Meteor.smartPublish("spEvents", function (limit, filter) {
    filter = clearFilter(filter);
    filter['$or'] = [{closed: {'$exists': false}}, {closed: false}];
    return SpEvents.find(filter, generateOptions(limit, ["text", "additionalText"]));
});

Meteor.smartPublish("spEvent", function (slug) {
    const userId = this.userId || "";
    return [
        SpEvents.find({slug: slug}),
        SpEventRegistrations.find({userId: userId})
    ]
});

Meteor.smartPublish("spEventRegistrations", function (slug) {
    const userId = this.userId || "";
    if (userId && Roles.userIsInRole(userId, ['admin'])) {
        this.addDependency("spEvents", "_id", doc => SpEventRegistrations.find({eventId: doc._id}));
        this.addDependency("spEventRegistrations", "userId",
                doc => Meteor.users.find({_id: doc.userId}));
        return SpEvents.find({slug: slug});
    }
    else {
        return [];
    }
});

Meteor.smartPublish("profile", function (username) {
    this.addDependency("users", "profile.photoId", doc => Avatars.find(doc.profile.photoId));
    this.addDependency("users", "_id", doc => Participations.find({authorId: doc._id}));
    this.addDependency("participations", "projectId",
            doc => Projects.find(doc.projectId, {fields: {name: 1, slug: 1, imageId: 1}}));
    this.addDependency("projects", "imageId", doc => Images.find(doc.imageId));
    const user = Meteor.users.findOne({username: username});
    if (user.profile && user.profile.isPrivate && this.userId !== user.id) {
        return [];
    } else {
        return Meteor.users.find({username: username}, {fields: {"_id": 1, "username": 1, profile: 1}});
    }
});

Meteor.publish('countries', function () {
    return Locations.find({});
});

Meteor.publish('professions', function () {
    return Professions.find({});
});

Meteor.smartPublish("projectComments", function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("projectComments", "authorId",
            doc => Meteor.users.find(doc.authorId, {fields: {"username": 1, "profile.photoId": 1}}));
    this.addDependency("users", "profile.photoId", doc => Avatars.find(doc.profile.photoId));
    return ProjectComments.find(filter, generateOptions(limit, [], "createdAt", true));
});

Meteor.publish('customPage', function (slug) {
    return CustomPages.find({slug});
});

Meteor.publish(null, () => Phrases.find({}));

Meteor.publish(null, () => Meteor.roles.find({}));

Meteor.publish(null, function() {
    if (this.userId) {
        const user = Meteor.users.findOne({_id: this.userId});
        if (user && user.profile) {
            return Avatars.find(user.profile.photoId);
        }
    }
    this.ready();
});
<commit_msg>fix(server): For private profile send only username, first and last name.<commit_after>function debugSleep(ms) {
    if (Meteor.settings.debug) {
        Meteor._sleepForMs(ms);
    }
}

function clearFilter(inFilter) {
    inFilter = inFilter || {};
    const filter = {};
    Object.keys(inFilter).forEach((k) => {
        if (inFilter[k]) {
            filter[k] = inFilter[k]
        }
    });
    return filter;
}

function generateOptions(limit = 0, omitFields = [], sortField = "submitted", reverse = true) {
    const options = {};
    if (limit && limit > 0) {
        options.limit = limit;
    }
    if (omitFields && omitFields.length) {
        options.fields = {};
        for (let f of omitFields) {
            options.fields[f] = false;
        }
    }
    if (sortField) {
        options.sort = {};
        options.sort[sortField] = reverse ? -1 : 1;
    }
    return options;
}

Meteor.smartPublish('articles', function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("articles", "imageId", doc => Images.find(doc.imageId));
    return Articles.find(filter, generateOptions(limit, ["text"], "createdAt"));
});

Meteor.smartPublish("article", function (slug) {
    this.addDependency("articles", "imageId", doc => Images.find(doc.imageId));
    return Articles.find({slug: slug});
});

Meteor.smartPublish("tempArticle", function () {
    const userId = this.userId || "";
    if (userId && Roles.userIsInRole(userId, ['admin'])) {
        return TempArticles.find({authorId: userId});
    }
    return [];
});

Meteor.publish("tags", function () {
    return Tags.find();
});

Meteor.smartPublish('jobs', function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("jobs", "companyName", doc => Companies.find({name: doc.companyName}));
    this.addDependency("companies", "imageId", doc => Images.find(doc.imageId));
    return Jobs.find(filter, generateOptions(limit, ["description"], "createdAt"));
});

Meteor.smartPublish("job", function (slug) {
    this.addDependency("jobs", "companyName", doc => Companies.find({name: doc.companyName}));
    this.addDependency("companies", "imageId", doc => Images.find(doc.imageId));
    return Jobs.find({slug: slug});
});

Meteor.smartPublish("companies", function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("companies", "imageId", doc =>  Images.find(doc.imageId));
    return Companies.find(filter, generateOptions(limit, ["text"]));
});

Meteor.publish("companyNames", function () {
    return Companies.find({}, {fields: {name: 1}});
});

Meteor.smartPublish("company", function (slug) {
    this.addDependency("companies", "imageId", doc => Images.find(doc.imageId));
    return Companies.find({slug: slug});
});

Meteor.publish("featuredCompanies", function () {
    return FeaturedCompanies.find({});
});

Meteor.smartPublish("projects", function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("projects", "imageId", doc => Images.find(doc.imageId));
    this.addDependency("projects", "listImageId", doc => doc.listImageId ? Images.find(doc.listImageId) : []);
    return Projects.find(filter, generateOptions(limit, ["description"], "createdAt", true));
});

Meteor.smartPublish("project", function (slug) {
    this.addDependency("projects", "imageId", doc => Images.find(doc.imageId));
    if (this.userId) {
        this.addDependency("projects", "_id",
                doc => Participations.find({authorId: this.userId, projectId: doc._id}))
    }
    return Projects.find({slug: slug});
});

Meteor.publish("featuredProjects", function (limit) {
    return Projects.find({}, generateOptions(limit, ["description"], "importance", true));
});

Meteor.smartPublish("spEvents", function (limit, filter) {
    filter = clearFilter(filter);
    filter['$or'] = [{closed: {'$exists': false}}, {closed: false}];
    return SpEvents.find(filter, generateOptions(limit, ["text", "additionalText"]));
});

Meteor.smartPublish("spEvent", function (slug) {
    const userId = this.userId || "";
    return [
        SpEvents.find({slug: slug}),
        SpEventRegistrations.find({userId: userId})
    ]
});

Meteor.smartPublish("spEventRegistrations", function (slug) {
    const userId = this.userId || "";
    if (userId && Roles.userIsInRole(userId, ['admin'])) {
        this.addDependency("spEvents", "_id", doc => SpEventRegistrations.find({eventId: doc._id}));
        this.addDependency("spEventRegistrations", "userId",
                doc => Meteor.users.find({_id: doc.userId}));
        return SpEvents.find({slug: slug});
    }
    else {
        return [];
    }
});

Meteor.smartPublish("profile", function (username) {
    this.addDependency("users", "profile.photoId", doc => Avatars.find(doc.profile.photoId));
    this.addDependency("users", "_id", doc => Participations.find({authorId: doc._id}));
    this.addDependency("participations", "projectId",
            doc => Projects.find(doc.projectId, {fields: {name: 1, slug: 1, imageId: 1}}));
    this.addDependency("projects", "imageId", doc => Images.find(doc.imageId));
    const user = Meteor.users.findOne({username: username});
    if (user.profile && user.profile.isPrivate && this.userId !== user.id) {
        return Meteor.users.find({username: username},
            {fields: {"_id": 1, "username": 1, "profile.firstName": 1, "profile.lastName": 1}});
    }
    else {
        return Meteor.users.find({username: username}, {fields: {"_id": 1, "username": 1, profile: 1}});
    }
});

Meteor.publish('countries', function () {
    return Locations.find({});
});

Meteor.publish('professions', function () {
    return Professions.find({});
});

Meteor.smartPublish("projectComments", function (limit, filter) {
    filter = clearFilter(filter);
    this.addDependency("projectComments", "authorId",
            doc => Meteor.users.find(doc.authorId, {fields: {"username": 1, "profile.photoId": 1}}));
    this.addDependency("users", "profile.photoId", doc => Avatars.find(doc.profile.photoId));
    return ProjectComments.find(filter, generateOptions(limit, [], "createdAt", true));
});

Meteor.publish('customPage', function (slug) {
    return CustomPages.find({slug});
});

Meteor.publish(null, () => Phrases.find({}));

Meteor.publish(null, () => Meteor.roles.find({}));

Meteor.publish(null, function() {
    if (this.userId) {
        const user = Meteor.users.findOne({_id: this.userId});
        if (user && user.profile) {
            return Avatars.find(user.profile.photoId);
        }
    }
    this.ready();
});
<|endoftext|>


<commit_before>define([
  'jquery', 'underscore', 'peerjs', 'net/BbsNetwork', 'net/RequestDispatcher', 'utils/Utils'
], function($, _, Peer, BbsNetwork, RequestDispatcher, Utils) {
  var NetworkAgent = function(config) {
    var self = this;

    this._config = config;
    this._threadListNetwork = new BbsNetwork(this._replacePeerId(
      config, 'T'
    ), function(fromPeerId, request, callback) {
      self._onRequestReceived(fromPeerId, request, callback);
    });
    this._threadNetworks = {};
    this._requestDispatcher = new RequestDispatcher();
    this._peers = [];
  };

  NetworkAgent.prototype = {
    createNetwork: function(callback) {
      this._threadListNetwork.createNetwork(callback);
    },

    joinNetwork: function(callback) {
      var self = this;

      Utils.debug("Trying to join thread list network.");

      this._getBootstrapIds(function(bootstrapIds) {
        self._peers = bootstrapIds;

        if (_.isEmpty(bootstrapIds)) {
          self.createNetwork(callback);
          return;
        }

        var retryJoinNetwork = function(bootstrapIds, callback) {
          if (_.isEmpty(bootstrapIds)) {
            return callback(null, new Error("Failed to join network."));
          }

          self._threadListNetwork.joinNetwork(_.first(bootstrapIds), function(peerId, error) {
            if (error) {
              Utils.debug("Failed to connect to", _.first(bootstrapIds), "(", error, "). Retry next peer.");
              retryJoinNetwork(_.rest(bootstrapIds), callback);
              return;
            }

            Utils.debug("Joining thread list network succeeded.");

            callback(peerId);
          });
        };
        retryJoinNetwork(bootstrapIds, callback);
      });
    },

    leaveNetwork: function() {
      var self = this;

      _.each(_.keys(this._threadNetworks), function(threadId) {
        self.leaveThreadNetwork(threadId);
      });
      this._threadListNetwork.leaveNetwork();

      Utils.debug("Left thread list network.");
    },

    fetchThreads: function(excludeIds, callback) {
      this._threadListNetwork.fetchThreads(excludeIds, callback);
    },

    spreadThread: function(threadInfo) {
      this._threadListNetwork.spreadThread(threadInfo);
    },

    fetchMessages: function(threadId, excludeIds, callback) {
      if (!_.has(this._threadNetworks, threadId)) {
        return callback(new Error("Unknown thread ID: " + threadId));
      }

      this._threadNetworks[threadId].fetchMessages(threadId, excludeIds, callback);
    },

    spreadMessage: function(messageInfo) {
      this._threadNetworks[messageInfo.threadId].spreadMessage(messageInfo);
    },

    joinThreadNetwork: function(threadId, callback) {
      var self = this;

      if (_.has(this._threadNetworks, threadId)) {
        return callback();
      }

      Utils.debug("Trying to join thread network (thread ID", threadId, ")");

      var threadNetwork = new BbsNetwork(this._replacePeerId(
        this._config, 't'
      ), function(fromPeerId, request, callback) {
        self._onRequestReceived(fromPeerId, request, callback);
      });
      this._threadNetworks[threadId] = threadNetwork;

      this._threadListNetwork.retrieveEntries(threadId, function(bootstrapIds, error) {
        if (error) {
          delete self._threadNetworks[threadId];
          return callback(new Error("Failed to retrieve bootstrap IDs:", error));
        }

        Utils.debug("[joinThreadNetwork] bootstrapIds:", bootstrapIds.toString());

        bootstrapIds = _.filter(bootstrapIds, function(id) {
          return Utils.isNonemptyString(id) && id.charAt(0) === 't';
        });

        if (_.isEmpty(bootstrapIds)) {
          threadNetwork.createNetwork(function(peerId, error) {
            if (error) {
              delete self._threadNetworks[threadId];
              return callback(error);
            }

            Utils.debug("Created thread network (thread ID:", threadId, ")");

            self._threadListNetwork.insertEntry(threadId, peerId);
            callback();
          });
          return;
        }

        var retryJoinNetwork = function(bootstrapIds, callback) {
          if (_.isEmpty(bootstrapIds)) {
            return callback(null, new Error("No peer ID to join is left."));
          }

          threadNetwork.joinNetwork(_.first(bootstrapIds), function(peerId, error) {
            if (error) {
              Utils.debug("Failed to connect to " + _.first(bootstrapIds), ". Retry next peer.");
              return retryJoinNetwork(_.rest(bootstrapIds), callback);
            }

            callback(peerId);
          });
        };

        retryJoinNetwork(bootstrapIds, function(peerId, error) {
          if (error) {
            delete self._threadNetworks[threadId];
            return callback(error);
          }

          Utils.debug("Joining thread network succeeded (thread ID:", threadId, ")");

          self._threadListNetwork.insertEntry(threadId, peerId);
          callback();
        });
      });
    },

    leaveThreadNetwork: function(threadId) {
      if (!_.has(this._threadNetworks, threadId)) {
        throw new Error("Unknown thread ID: " + threadId);
      }
      this._threadListNetwork.removeEntry(threadId, this._threadNetworks[threadId].getPeerId());
      this._threadNetworks[threadId].leaveNetwork();
      delete this._threadNetworks[threadId];

      Utils.debug("Left thread network (thread ID:", threadId, ")");
    },

    _replacePeerId: function(config, prefix) {
      var _config = _.clone(config);
      _config.peer = _.clone(config.peer);
      _config.peer.options = _.clone(config.peer.options);
      _config.peer.id = prefix + (Math.random().toString(36) + '0000000000000000000').substr(2, 16);
      return _config;
    },

    _getBootstrapIds: function(callback) {
      var options = this._config.peer.options;
      var url = 'http://' + options.host + ':' + options.port + '/' + options.key + '/peers';
      $.ajax({
        url: url,
        success: function(peers) {
          if (!_.isArray(peers) || _.isEmpty(peers)) {
            Utils.debug("Retrieved no peer IDs.");
            return callback([]);
          }

          Utils.debug("[_getBootstrapIds] peers:", peers);

          peers = _.filter(peers, function(peer) { return peer.charAt(0) === 'T'; });

          callback(peers);
        },
        error: function(xhr, status, error) {
          console.log("Failed to retrieve peers: " + error);
          callback([]);
        }
      });
    },

    _onRequestReceived: function(fromPeerId, request, callback) {
      this._requestDispatcher.dispatch(fromPeerId, request, callback);
    },

    getJoiningThreadIds: function() {
      return _.keys(this._threadNetworks);
    },

    getPeerId: function(threadId) {
      if (!threadId) {
        return this._threadListNetwork.getPeerId();
      }
      if (!_.has(this._threadNetworks, threadId)) {
        throw new Error("Unknown thread ID: " + threadId);
      }
      return this._threadNetworks[threadId].getPeerId();
    },

    getPeers: function() {
      return this._peers;
    },

    getDirectConnectedPeers: function(threadId) {
      if (!threadId) {
        return this._threadListNetwork.getDirectConnectedPeers();
      }
      if (!_.has(this._threadNetworks, threadId)) {
        throw new Error("Unknown thread ID: " + threadId);
      }
      return this._threadNetworks[threadId].getDirectConnectedPeers();
    },

    getState: function(threadId) {
      if (!threadId) {
        return this._threadListNetwork.getState();
      }
      if (!_.has(this._threadNetworks, threadId)) {
        throw new Error("Unknown thread ID: " + threadId);
      }
      return this._threadNetworks[threadId].getState();
    },

    checkPeerSetting: function() {
      if (!_.isObject(this._config.peer)) {
        throw new Error("Property 'peer' is required in config object.");
      }
      if (!_.isObject(this._config.peer.options)) {
        throw new Error("Property 'options' is required in config.peer object.");
      }
      if (!Utils.isNonemptyString(this._config.peer.options.host) ||
          this._config.peer.options.host === 'YOUR PEERSERVER HOST') {
        throw new Error("Specify the PeerServer host used in the system.");
      }
      if (!Utils.isNonemptyString(this._config.peer.options.key) ||
          this._config.peer.options.key === 'YOUR KEY') {
        throw new Error("Specify the key for the PeerServer used in the system.");
      }
    }
  };

  return NetworkAgent;
});
<commit_msg>Modify NetworkAgent#_getPeerConfig.<commit_after>define([
  'jquery', 'underscore', 'peerjs', 'net/BbsNetwork', 'net/RequestDispatcher', 'utils/Utils'
], function($, _, Peer, BbsNetwork, RequestDispatcher, Utils) {
  var NetworkAgent = function(config) {
    var self = this;

    this._config = config;
    this._threadListNetwork = new BbsNetwork(this._buildConfig('T'), function(fromPeerId, request, callback) {
      self._onRequestReceived(fromPeerId, request, callback);
    });
    this._threadNetworks = {};
    this._requestDispatcher = new RequestDispatcher();
    this._peers = [];
  };

  NetworkAgent.prototype = {
    createNetwork: function(callback) {
      this._threadListNetwork.createNetwork(callback);
    },

    joinNetwork: function(callback) {
      var self = this;

      Utils.debug("Trying to join thread list network.");

      this._getBootstrapIds(function(bootstrapIds) {
        self._peers = bootstrapIds;

        if (_.isEmpty(bootstrapIds)) {
          self.createNetwork(callback);
          return;
        }

        var retryJoinNetwork = function(bootstrapIds, callback) {
          if (_.isEmpty(bootstrapIds)) {
            return callback(null, new Error("Failed to join network."));
          }

          self._threadListNetwork.joinNetwork(_.first(bootstrapIds), function(peerId, error) {
            if (error) {
              Utils.debug("Failed to connect to", _.first(bootstrapIds), "(", error, "). Retry next peer.");
              retryJoinNetwork(_.rest(bootstrapIds), callback);
              return;
            }

            Utils.debug("Joining thread list network succeeded.");

            callback(peerId);
          });
        };
        retryJoinNetwork(bootstrapIds, callback);
      });
    },

    leaveNetwork: function() {
      var self = this;

      _.each(_.keys(this._threadNetworks), function(threadId) {
        self.leaveThreadNetwork(threadId);
      });
      this._threadListNetwork.leaveNetwork();

      Utils.debug("Left thread list network.");
    },

    fetchThreads: function(excludeIds, callback) {
      this._threadListNetwork.fetchThreads(excludeIds, callback);
    },

    spreadThread: function(threadInfo) {
      this._threadListNetwork.spreadThread(threadInfo);
    },

    fetchMessages: function(threadId, excludeIds, callback) {
      if (!_.has(this._threadNetworks, threadId)) {
        return callback(new Error("Unknown thread ID: " + threadId));
      }

      this._threadNetworks[threadId].fetchMessages(threadId, excludeIds, callback);
    },

    spreadMessage: function(messageInfo) {
      this._threadNetworks[messageInfo.threadId].spreadMessage(messageInfo);
    },

    joinThreadNetwork: function(threadId, callback) {
      var self = this;

      if (_.has(this._threadNetworks, threadId)) {
        return callback();
      }

      Utils.debug("Trying to join thread network (thread ID", threadId, ")");

      var threadNetwork = new BbsNetwork(this._buildConfig('t'), function(fromPeerId, request, callback) {
        self._onRequestReceived(fromPeerId, request, callback);
      });
      this._threadNetworks[threadId] = threadNetwork;

      this._threadListNetwork.retrieveEntries(threadId, function(bootstrapIds, error) {
        if (error) {
          delete self._threadNetworks[threadId];
          return callback(new Error("Failed to retrieve bootstrap IDs:", error));
        }

        Utils.debug("[joinThreadNetwork] bootstrapIds:", bootstrapIds.toString());

        bootstrapIds = _.filter(bootstrapIds, function(id) {
          return Utils.isNonemptyString(id) && id.charAt(0) === 't';
        });

        if (_.isEmpty(bootstrapIds)) {
          threadNetwork.createNetwork(function(peerId, error) {
            if (error) {
              delete self._threadNetworks[threadId];
              return callback(error);
            }

            Utils.debug("Created thread network (thread ID:", threadId, ")");

            self._threadListNetwork.insertEntry(threadId, peerId);
            callback();
          });
          return;
        }

        var retryJoinNetwork = function(bootstrapIds, callback) {
          if (_.isEmpty(bootstrapIds)) {
            return callback(null, new Error("No peer ID to join is left."));
          }

          threadNetwork.joinNetwork(_.first(bootstrapIds), function(peerId, error) {
            if (error) {
              Utils.debug("Failed to connect to " + _.first(bootstrapIds), ". Retry next peer.");
              return retryJoinNetwork(_.rest(bootstrapIds), callback);
            }

            callback(peerId);
          });
        };

        retryJoinNetwork(bootstrapIds, function(peerId, error) {
          if (error) {
            delete self._threadNetworks[threadId];
            return callback(error);
          }

          Utils.debug("Joining thread network succeeded (thread ID:", threadId, ")");

          self._threadListNetwork.insertEntry(threadId, peerId);
          callback();
        });
      });
    },

    leaveThreadNetwork: function(threadId) {
      if (!_.has(this._threadNetworks, threadId)) {
        throw new Error("Unknown thread ID: " + threadId);
      }
      this._threadListNetwork.removeEntry(threadId, this._threadNetworks[threadId].getPeerId());
      this._threadNetworks[threadId].leaveNetwork();
      delete this._threadNetworks[threadId];

      Utils.debug("Left thread network (thread ID:", threadId, ")");
    },

    _buildConfig: function(prefix) {
      var _config = _.clone(this._config);
      _config.peer = _.clone(this._config.peer);
      _config.peer.options = _.clone(this._config.peer.options);
      _config.peer.id = prefix + (Math.random().toString(36) + '0000000000000000000').substr(2, 16);
      if (!_config.peer.options.host) {
        _config.peer.options.host = 'localhost';
      }
      return _config;
    },

    _getBootstrapIds: function(callback) {
      var options = this._buildConfig('').peer.options;
      var url = 'http://' + options.host + ':' + options.port + '/' + options.key + '/peers';
      $.ajax({
        url: url,
        success: function(peers) {
          if (!_.isArray(peers) || _.isEmpty(peers)) {
            Utils.debug("Retrieved no peer IDs.");
            return callback([]);
          }

          Utils.debug("[_getBootstrapIds] peers:", peers);

          peers = _.filter(peers, function(peer) { return peer.charAt(0) === 'T'; });

          callback(peers);
        },
        error: function(xhr, status, error) {
          console.log("Failed to retrieve peers: " + error);
          callback([]);
        }
      });
    },

    _onRequestReceived: function(fromPeerId, request, callback) {
      this._requestDispatcher.dispatch(fromPeerId, request, callback);
    },

    getJoiningThreadIds: function() {
      return _.keys(this._threadNetworks);
    },

    getPeerId: function(threadId) {
      if (!threadId) {
        return this._threadListNetwork.getPeerId();
      }
      if (!_.has(this._threadNetworks, threadId)) {
        throw new Error("Unknown thread ID: " + threadId);
      }
      return this._threadNetworks[threadId].getPeerId();
    },

    getPeers: function() {
      return this._peers;
    },

    getDirectConnectedPeers: function(threadId) {
      if (!threadId) {
        return this._threadListNetwork.getDirectConnectedPeers();
      }
      if (!_.has(this._threadNetworks, threadId)) {
        throw new Error("Unknown thread ID: " + threadId);
      }
      return this._threadNetworks[threadId].getDirectConnectedPeers();
    },

    getState: function(threadId) {
      if (!threadId) {
        return this._threadListNetwork.getState();
      }
      if (!_.has(this._threadNetworks, threadId)) {
        throw new Error("Unknown thread ID: " + threadId);
      }
      return this._threadNetworks[threadId].getState();
    },

    checkPeerSetting: function() {
      if (!_.isObject(this._config.peer)) {
        throw new Error("Property 'peer' is required in config object.");
      }
      if (!_.isObject(this._config.peer.options)) {
        throw new Error("Property 'options' is required in config.peer object.");
      }
      if (!Utils.isNonemptyString(this._config.peer.options.host)) {
        throw new Error("Specify the PeerServer host used in the system.");
      }
      if (!Utils.isNonemptyString(this._config.peer.options.key)) {
        throw new Error("Specify the key for the PeerServer used in the system.");
      }
    }
  };

  return NetworkAgent;
});
<|endoftext|>


<commit_before>import React from 'react'
import ShowCard from './ShowCard'
import preload from '../public/data.json'

const Search = React.createClass({
  getInitialState () {
    return {
      searchTerm: 'this is the default string'
    }
  },
  handleSearchTermChange (event) {
    this.setState({searchTerm: event.target.value})
  },
  render () {
    return (

 {this.state.searchTerm}

          <input
            onChange={this.handleSearchTermChange}
            value={this.state.searchTerm}
            type='text'
            placeholder='Search'
          />

          {preload.shows.map((show) => {
            return (
              <ShowCard key={show.imdbID} {...show} />
            )
          })}

    )
  }
})

export default Search
<commit_msg>Add filtering capability<commit_after>import React from 'react'
import ShowCard from './ShowCard'
import preload from '../public/data.json'

const Search = React.createClass({
  getInitialState () {
    return {
      searchTerm: ''
    }
  },
  handleSearchTermChange (event) {
    this.setState({searchTerm: event.target.value})
  },
  render () {
    return (

 svideo

          <input
            onChange={this.handleSearchTermChange}
            value={this.state.searchTerm}
            type='text'
            placeholder='Search'
          />

          {preload.shows
            .filter((show) => `${show.title} ${show.description}`.toUpperCase().indexOf(this.state.searchTerm.toUpperCase()) >= 0)
            .map((show) => {
              return (
                <ShowCard {...show} key={show.imdbID} />
              )
            })}

    )
  }
})

export default Search
<|endoftext|>