<commit_before>const Database = require('./../../utils/database.js');

module.exports = {
    usage: `Used to toggle and configure settings. Configurable settings include automated table unflipping as well as welcome and leave messages. Welcome and Join messages are sent in the channel in which the command is used and can be toggled off by leaving the message field blank.

__Welcome/Leave Messages can include the following text to return different things:__\`\`\`ruby
     GuildName: Server Name
ChannelMention: Mention to Current Channel
   ChannelName: Name of the Current Channel
      UserName: Name of the User
   UserMention: Mention to the User
\`\`\`
Exact case must be used

\`setting tableflip\`
\`setting welcome [message]\`
\`setting leave [message]\``,
    aliases: ['set'],
    dm: false,
    delete: true,
    togglable: false,
    cooldown: 5,
    process: (msg, args) => {
        return new Promise(resolve => {
            //If args are tableflip then toggle the tableflip setting
            if (args.toLowerCase() === 'tableflip') Database.toggleSetting(msg.channel.guild.id, args).then(result => resolve({
                message: "⚙ " + result + " ⚙",
                delete: true
            }))
            else if (args.toLowerCase().startsWith('welcome') || args.toLowerCase().startsWith('leave')) {
                let setting = args.split(' ')[0], //The setting to be changed(either welcome or leave)
                    message = args.substring(setting.length + 1, args.length); //Create a string of the message without the extra space
                if (message.length > 256) //Messages can only be 256 characters in length due to database reasons
                    resolve({
                    message: "🚫 Welcome/Leave Messages are limited to 256 characters in length. 🚫",
                    delete: true
                })
                else Database.toggleSetting(msg.channel.guild.id, setting, message, msg.channel.id).then(result => resolve({ //Toggles the setting, if no message passed toggles it off otherwise sets the message for the current channel
                    message: "⚙ " + result + " ⚙",
                    delete: true
                }))
            } else //If neither tableflip, welcome or leave
                resolve({
                message: "🚫 `" + args.split(' ')[0] + "` isn't an available setting 🚫",
                delete: true
            })
        })
    }
}<commit_msg>Help changes to setting<commit_after>const Database = require('./../../utils/database.js');

module.exports = {
    usage: `Used to configure/toggle settings including **automated table unflipping** and **welcome/leave messages**. **Welcome/leave messages** are sent in the **channel** in which this command is last used and can be toggled off by leaving the message field **blank**.

**__Welcome/Leave Messages can include the following text:__**\`\`\`markdown
[Text](Replaced with this) #Example
[GuildName](Guild Name)
[ChannelMention](Mention to Current Channel)
[ChannelName](Name of the Current Channel)
[UserName](Name of the User)
[UserMention](Mention to the User)

# Exact case MUST be used exluding brackets #
\`\`\`
\`setting tableflip - Toggles tableflip on/off\`
\`setting welcome/leave [message] - Sets welcome/leave to 'message'\``,
    aliases: ['set'],
    dm: false,
    delete: false,
    togglable: false,
    cooldown: 5,
    process: (msg, args) => {
        return new Promise(resolve => {
            //If args are tableflip then toggle the tableflip setting
            if (args.toLowerCase() === 'tableflip') Database.toggleSetting(msg.channel.guild.id, args).then(result => resolve({
                message: "⚙ " + result + " ⚙",
                delete: true
            }))
            else if (args.toLowerCase().startsWith('welcome') || args.toLowerCase().startsWith('leave')) {
                let setting = args.split(' ')[0], //The setting to be changed(either welcome or leave)
                    message = args.substring(setting.length + 1, args.length); //Create a string of the message without the extra space
                if (message.length > 256) //Messages can only be 256 characters in length due to database reasons
                    resolve({
                    message: "🚫 Welcome/Leave Messages are limited to 256 characters in length. 🚫",
                    delete: true
                })
                else Database.toggleSetting(msg.channel.guild.id, setting, message, msg.channel.id).then(result => resolve({ //Toggles the setting, if no message passed toggles it off otherwise sets the message for the current channel
                    message: "⚙ " + result + " ⚙",
                    delete: true
                }))
            } else //If neither tableflip, welcome or leave
                resolve({
                message: "🚫 `" + args.split(' ')[0] + "` isn't an available setting 🚫",
                delete: true
            })
        })
    }
}<|endoftext|>


<commit_before>(function() {

var notes = {
    captainProportional: "The exact multiplier used to compute the damage is proportional to the " +
        "crew's remaining HP and is higher the #1 the HP is. The multiplier is calculated as #2. " +
        "At full health the boost is equal to #3x, with 1 HP left to #4x.",
    fixed: "Fixed damage means it entirely bypasses the enemy's defense.",
	noFixedPerc: "Specials that deal fixed damage or cut a percentage of the enemy's HP are not " +
        "affected by this captain ability",
    orb: "Orb amplification only affects matching and opposite orbs and works both ways: " +
        "matching orbs will deal #1x more damage and opposite orbs will deal #1x less damage.",
    poison: "Poison deals 0.5x character's ATK in fixed damage at the end of each turn.",
    random: "Estimated random damage range: between #1 HP and #2 HP.",
    randomHits: "The target of each of the #1 hits is chosen randomly.",
    specialProportional: "The exact multiplier used to compute the damage is proportional to the " +
        "crew's remaining HP and is higher the #1 the HP is. The multiplier is calculated as: #2.",
    zombie: "The protection only works when attacked by one single enemy and will leave the team with at least 1 HP; " +
        "the effect will not work when attacked by multiples enemies at once."
};

/***********
 * Angular *
 ***********/

var app = angular.module('optc');
var directives = { }, filters = { };

/**********************
 * Element directives *
 **********************/

directives.linkButton = function() {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '../common/views/links.html',
        scope: { exclude: '@' },
        link: function(scope, element, attrs) {
            element.find(".trigger").click(function() {
                element.toggleClass("active");
            });
        }
    };
};

/***********
 * Filters *
 ***********/

filters.decorate = function() {
    return function(input) {
        if (!input) return 'None';
        return input
            .replace(/\[?(STR|DEX|QCK|PSY|INT)\]?/g,'$1')
            .replace(/\[RCV\]/g,'RCV')
            .replace(/\[TND\]/g,' TND')
            .replace(/\[EMPTY\]/g,' EMPTY')
            .replace(/\[BLOCK\]/g,' BLOCK')
            .replace(/\[BOMB\]/g,' BOMB');
    };
};

filters.range = function() {
    return function(input, total) {
        total = parseInt(total,10);
        for (var i=0;i<total;++i) input.push(i);
        return input;
    };
};

filters.notes = function() {
    return function(input) {
        if (!input) return input;
        return input.trim().replace(/#\{(.+?)\}/g,function(x,y) {
            var tokens = y.trim().split(/:/);
            if (!tokens.length || !notes.hasOwnProperty(tokens[0].trim())) return x;
            return notes[tokens[0].trim()].replace(/#(\d+)/g,function(a,b) {
                return (tokens[parseInt(b,10)] || '').trim();
            });
        });
    };
};

/******************
 * Initialization *
 ******************/

for (var directive in directives)
    app.directive(directive, directives[directive]);

for (var filter in filters)
    app.filter(filter, filters[filter]);

})();
<commit_msg>minor fixes<commit_after>(function() {

var notes = {
    captainProportional: "The exact multiplier used to compute the damage is proportional to the " +
        "crew's remaining HP and is higher the #1 the HP is. The multiplier is calculated as #2. " +
        "At full health the boost is equal to #3x, with 1 HP left to #4x.",
    fixed: "Fixed damage means it entirely bypasses the enemy's defense.",
	noFixedPerc: "Specials that deal fixed damage or cut a percentage of the enemy's HP are not " +
        "affected by this captain ability",
    orb: "Orb amplification only affects matching and opposite orbs and works both ways: " +
        "matching orbs will deal #1x more damage and opposite orbs will deal #1x less damage.",
    poison: "Poison deals 0.5x character's ATK in fixed damage at the end of each turn.",
    random: "Estimated random damage range: between #1 HP and #2 HP.",
    randomHits: "The target of each of the #1 hits is chosen randomly.",
    specialProportional: "The exact multiplier used to compute the damage is proportional to the " +
        "crew's remaining HP and is higher the #1 the HP is. The multiplier is calculated as: #2.",
    zombie: "The protection only works when attacked by one single enemy and will leave the team with at least 1 HP; " +
        "the effect will not work when attacked by multiples enemies at once."
};

/***********
 * Angular *
 ***********/

var app = angular.module('optc');
var directives = { }, filters = { };

/**********************
 * Element directives *
 **********************/

directives.linkButton = function() {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '../common/views/links.html',
        scope: { exclude: '@' },
        link: function(scope, element, attrs) {
            element.find(".trigger").click(function() {
                element.toggleClass("active");
            });
        }
    };
};

/***********
 * Filters *
 ***********/

filters.decorate = function() {
    return function(input) {
        if (!input) return 'None';
        if (input.constructor == Array) input = input[0];
        if (input.constructor != String) return 'N/A';
        return input
            .replace(/\[?(STR|DEX|QCK|PSY|INT)\]?/g,'$1')
            .replace(/\[RCV\]/g,'RCV')
            .replace(/\[TND\]/g,' TND')
            .replace(/\[EMPTY\]/g,' EMPTY')
            .replace(/\[BLOCK\]/g,' BLOCK')
            .replace(/\[BOMB\]/g,' BOMB');
    };
};

filters.range = function() {
    return function(input, total) {
        total = parseInt(total,10);
        for (var i=0;i<total;++i) input.push(i);
        return input;
    };
};

filters.notes = function() {
    return function(input) {
        if (!input) return input;
        return input.trim().replace(/#\{(.+?)\}/g,function(x,y) {
            var tokens = y.trim().split(/:/);
            if (!tokens.length || !notes.hasOwnProperty(tokens[0].trim())) return x;
            return notes[tokens[0].trim()].replace(/#(\d+)/g,function(a,b) {
                return (tokens[parseInt(b,10)] || '').trim();
            });
        });
    };
};

/******************
 * Initialization *
 ******************/

for (var directive in directives)
    app.directive(directive, directives[directive]);

for (var filter in filters)
    app.filter(filter, filters[filter]);

})();
<|endoftext|>


<commit_before>/**
 * Functions for the rendering, parsing and validation of forms.
 *
 * @module
 */

/**
 * Module dependencies
 */

var core = require('./core'),
    utils = require('./utils'),
    fieldset = require('./fieldset'),
    render = require('./render'),
    _ = require('./underscore')._;

/**
 * Form object, presents fields and parses responses.
 *
 * #### Options ####
 *
 *

 *

 *      exclude
 *      Array
 *      a list of field names to exclude
 *

 *

 *      fields
 *      Array
 *
 *          a subset of fields to use (inverse of excluded)
 *
 *

 *

 *
 * @name Form(fields | type, [doc])
 * @param {Object} fields  - an object literal containing fields or a Type
 * @param {Object} doc     - (optional) the original document being edited
 * @param {Object} options - (optional) see available options above
 * @constructor
 * @api public
 */

var Form = exports.Form = function Form(fields, doc, options) {
    this.options = options || {};

    this.values = null;
    if (doc) {
        this.values = JSON.parse(JSON.stringify(doc)); /* Copy */
        this.initial_doc = doc;
    }
    if (fields && fields.fields) {
        this.type = fields;
        this.fields = this.type.fields;
    }
    else {
        this.fields = fields;
    }
    /*if (utils.constructorName(fields) === 'Type') {
        this.type = fields;
        this.fields = this.type.field;
    }
    else {
        this.fields = fields;
    }*/
};

/**
 * Overrides values in doc_a with values in doc_b, only when a field is present
 * for that value. This means properties not in fields (or in excluded fields)
 * are retained, while properties which are covered by the fieldset are
 * replaced.
 *
 * This is used when updating the form's values with a request when its been
 * initiated with a previous document. You shouldn't normally need to call this
 * directly.
 *
 * Returns the updated doc_a object.
 *
 * @name override(excludes, field_subset, fields, doc_a, doc_b, path)
 * @param {Array | null} excludes
 * @param {Array | null} field_subset
 * @param {Object} Fields
 * @param {Object} doc_a
 * @param {Object} doc_b
 * @param {Array} path
 * @returns {Object}
 * @api public
 */

exports.override = function (excludes, field_subset, fields, doc_a, doc_b, path) {
    fields = fields || {};
    doc_a = doc_a || {};

    var fields_module = require('./fields');
    var exclude_paths = (excludes || []).map(function (p) {
        return p.split('.');
    });
    var subset_paths = (field_subset || []).map(function (p) {
        return p.split('.');
    });

    var keys = _.keys(doc_b);

    _.each(keys, function (k) {
        var f = fields[k];
        var b = doc_b[k];
        var f_path = path.concat([k]);

        if (typeof b !== 'object' ||
            f instanceof fields_module.Field ||
            f instanceof fields_module.Embedded ||
            f instanceof fields_module.EmbeddedList) {

            if (excludes) {
                for (var i = 0; i < exclude_paths.length; i++) {
                    if (utils.isSubPath(exclude_paths[i], f_path)) {
                        return;
                    }
                }
            }
            if (field_subset) {
                var in_subset = false;
                for (var j = 0; j < subset_paths.length; j++) {
                    if (utils.isSubPath(subset_paths[j], f_path)) {
                        in_subset = true;
                    }
                }
                if (!in_subset) {
                    return;
                }
            }
            doc_a[k] = b;
        }
        else {
            doc_a[k] = exports.override(
                excludes, field_subset, fields[k], doc_a[k], b, f_path
            );
        }
    });
    return doc_a;
};

/**
 * Parses a request and validates the result, binding values and errors to
 * the form instance.
 *
 * @name Form.validate(req)
 * @param {Object} req
 * @returns {Form}
 * @api public
 */

Form.prototype.validate = function (/*optional*/req) {
    if (!req) {
        req = utils.currentRequest();
    }
    this.raw = req.form || {};
    var tree = exports.formValuesToTree(this.raw);
    this.values = exports.override(
        this.options.exclude,
        this.options.fields,
        this.fields,
        this.values || fieldset.createDefaults(this.fields, req) || {},
        exports.parseRaw(this.fields, tree),
        []
    );

    this.errors = fieldset.validate(
        this.fields, this.values, this.values, this.raw, [], false
    );

    if (this.type) {
        // run top level permissions first
        var type_errs = this.type.authorizeTypeLevel(
            this.values, this.initial_doc, req.userCtx
        );
        if (type_errs.length) {
            this.errors = this.errors.concat(type_errs);
        }
        else {
            // if no top-level permissions errors, check each field
            this.errors = this.errors.concat(
                this.type.authorize(
                    this.values, this.initial_doc, req.userCtx
                )
            );
        }
    }
    else {
        this.errors = this.errors.concat(fieldset.authFieldSet(
            this.fields, this.values, this.initial_doc, this.values,
            this.initial_doc, req.userCtx, [], true
        ));
    }

    // clear field properties on errors for excluded fields
    var excludes = this.options.exclude;
    if (excludes) {
        var excl_paths = _.map(excludes, function (p) {
            return p.split('.');
        });
        this.errors = _.map(this.errors, function (e) {
            if (!e.field) {
                return e;
            }
            for (var i = 0, len = excl_paths.length; i < len; i++) {
                var path = excl_paths[i];
                if (utils.isSubPath(path, e.field)) {
                    e.message = e.field.join('.') + ': ' + (
                        e.message || e.toString()
                    );
                    delete e.field;
                    return e;
                }
            }
            return e;
        });
    }

    // clear field properties on errors not in fields subset
    var field_subset = this.options.fields;
    if (field_subset) {
        var subset_paths = _.map(field_subset, function (p) {
            return p.split('.');
        });
        this.errors = _.map(this.errors, function (e) {
            if (!e.field) {
                return e;
            }
            for (var i = 0, len = subset_paths.length; i < len; i++) {
                var path = subset_paths[i];
                if (!utils.isSubPath(path, e.field)) {
                    e.message = e.field.join('.') + ': ' + (
                        e.message || e.toString()
                    );
                    delete e.field;
                    return e;
                }
            }
            return e;
        });
    }

    return this;
};

/**
 * After a form has called validate, this function will return true if the form
 * is valid, false otherwise.
 *
 * @name Form.isValid()
 * @returns {Boolean}
 * @api public
 */

Form.prototype.isValid = function () {
    return !(this.errors && this.errors.length);
};

/**
 * Filters an array of errors, returning only those below a specific field path
 *
 * @param {Array} errs
 * @param {Array} path
 * @returns {Array}
 */

var errsBelowPath = function (errs, path) {
    if (!path || !path.length) {
        return errs;
    }
    return _.filter(errs, function (e) {
        if (!e.field) {
            return false;
        }
        return utils.isSubPath(path, e.field);
    });
};

/**
 * Filters a list of errors, returning only those without a field property.
 * This is used to populate the errors at the top of the form, which apply
 * generally, or cannot be attributed to a single field.
 *
 * @param {Array} errs
 * @returns {Array}
 */

var errsWithoutFields = function (errs) {
    return _.filter(errs, function (e) {
        return !e.field;
    });
};

/**
 * Converts current form to a HTML string, using an optional renderer class.
 *
 * @name Form.toHTML(req, [RendererClass])
 * @param {Object} req Kanso request object; null for most recent. (optional)
 * @param {Renderer} renderer_class (optional)
 * @param {Object} options An object containing widget options, which
 *          will ultimately be provided to each widget's toHTML method.
 * @param {Boolean} create_defaults (optional) Set this to true if you've
 *          provided a document in {doc}, but would still like default
 *          values to be merged in to it via createDefaults. For a field f,
 *          the default value is added to {doc} if and only if doc[f]
 *          is undefined, null, or not present. Defaults to off.
 * @returns {String}
 * @returns {String}
 * @api public
 */

Form.prototype.toHTML = function (/* optional */ req,
                                  /* optional */ renderer_class,
                                  /* optional */ options,
                                  /* optional */ create_defaults) {
    if (!req) {
        req = utils.currentRequest();
    }
    var values = this.values;

    if (create_defaults) {
        values = _.defaults(
            values, fieldset.createDefaults(this.fields, req)
        );
    } else if (!values) {
        values = fieldset.createDefaults(this.fields, req);
    }

    renderer_class = (renderer_class || render.defaultRenderer());
    var renderer = new renderer_class();
    return (
        renderer.start(errsWithoutFields(this.errors)) +
        this.renderFields(
            renderer, this.fields,
                values, this.raw, this.errors, [], (options || {})
        ) +
        renderer.end() +
        render.scriptTagForEvent('renderFinish')
    );
};

/**
 * Filters an array of errors, returning only those below a specific field path
 *
 * @param {Array} errs
 * @param {Array} path
 * @returns {Array}
 */

var errsBelowPath = function (errs, path) {
    return _.filter(errs, function (e) {
        for (var i = 0, len = path.length; i < len; ++i) {
            if (path[i] !== e.field[i]) {
                return false;
            }
        }
        return true;
    });
};

/**
 * Iterates over fields and sub-objects calling the correct renderer function on
 * each. Returns a HTML representation of the fields. Used internally by the
 * toHTML method, you should not need to call this function directly.
 *
 * @name Form.renderFields(renderer, fields, values, raw, err, path)
 * @param {Object} renderer
 * @param {Object} fields
 * @param {Object} values
 * @param {Array} errs
 * @param {Array} path
 * @param {Object} options An object containing widget options, which
 *          will ultimately be provided to each widget's toHTML method.
 * @returns {String}
 * @api public
 */

Form.prototype.renderFields = function (renderer, fields, values,
                                        raw, errs, path, options) {
    fields = fields || {};
    values = values || {};
    raw = raw || {};
    errs = errs || [];
    path = path || [];

    var that = this;
    var excludes = this.options.exclude;
    var field_subset = this.options.fields;
    var keys = _.keys(fields);

    var fields_module = require('./fields');

    return _.reduce(keys, function (html, k) {

        var f_path = path.concat([k]);

        if (excludes) {
            if (_.indexOf(excludes, f_path.join('.')) !== -1) {
                return html;
            }
        }
        if (field_subset) {
            if (_.indexOf(field_subset, f_path.join('.')) === -1) {
                return html;
            }
        }

        var f_errs = errsBelowPath(errs, f_path);
        var f = fields[k];

        if (f instanceof fields_module.Field ||
            f instanceof fields_module.Embedded ||
            f instanceof fields_module.EmbeddedList) {

            return html + renderer.field(
                f,
                f_path,
                values[k],
                (raw[k] === undefined) ? values[k]: raw[k],
                f_errs,
                (options || {})
            );
        }
        else if (f instanceof Object) {
            return html + (k ? renderer.beginGroup(f_path) : '') +
                that.renderFields(
                    renderer,
                    f,
                    values[k],
                    (raw[k] === undefined) ? values[k]: raw[k],
                    errs,
                    f_path,
                    (options || {})
                ) + (k ? renderer.endGroup(f_path) : '');
        } else {
            throw new Error(
                'The field type `' + (typeof f) + '` is not supported.'
            );
        }
    }, '');
};

/**
 * Transforms a flat object from a request query to a proper
 * hierarchy of properties.
 *
 *
{'one.two': 'val'} --> {one: {two: 'val'}}

 *
 * @name formValuesToTree(form)
 * @param {Object} query
 * @api public
 */

exports.formValuesToTree = function (form) {
    var tree = {};
    for (var k in form) {
        utils.setPropertyPath(tree, k.split('.'), form[k]);
    }
    return tree;
};

/**
 * Transforms a raw query object from formValuesToTree to a
 * document which follows the schema for the given type.
 *
 * @name parseRaw(fields, raw)
 * @param {Type} type
 * @param {Object} raw
 * @returns {Object}
 * @api public
 */

exports.parseRaw = function (fields, raw) {
    var doc = {};
    raw = raw || {};
    var fields_module = require('./fields');

    for (var k in fields) {
        var f = fields[k];
        var r = raw[k];

        if (f instanceof fields_module.Field) {
            if (!f.isEmpty(r)) {
                doc[k] = f.parse(r);
            }
            else if (!f.omit_empty) {
                doc[k] = undefined;
            }
        }
        else if (f instanceof fields_module.Embedded) {
            if (!f.isEmpty(r)) {
                if (typeof r === 'string') {
                    if (r !== '') {
                        doc[k] = JSON.parse(r);
                    }
                }
                else {
                    doc[k] = exports.parseRaw(f.type.fields, r);
                }
            }
        }
        else if (f instanceof fields_module.EmbeddedList) {
            doc[k] = [];
            for (var i in r) {
                var val;
                if (typeof r[i] === 'string') {
                    if (r[i] !== '') {
                        val = JSON.parse(r[i]);
                    }
                }
                else {
                    val = exports.parseRaw(f.type.fields, r[i]);
                }
                if (!f.isEmpty(val)) {
                    doc[k][i] = val;
                }
            }
            if (!doc[k].length && f.omit_empty) {
                delete doc[k];
            }
        }
        else if (f instanceof Object) {
            doc[k] = exports.parseRaw(f, r);
        } else {
            throw new Error(
                'The field type `' + (typeof f) + '` is not supported.'
            );
        }
    }
    return doc;
};

<commit_msg>Resolve issue #100 re: programmer error -- provide a useful diagnostic message if a type in the app's lib/types.js is misconfigured (i.e. is not an instance of `Type`).<commit_after>/**
 * Functions for the rendering, parsing and validation of forms.
 *
 * @module
 */

/**
 * Module dependencies
 */

var core = require('./core'),
    utils = require('./utils'),
    fieldset = require('./fieldset'),
    render = require('./render'),
    _ = require('./underscore')._;

/**
 * Form object, presents fields and parses responses.
 *
 * #### Options ####
 *
 *

 *

 *      exclude
 *      Array
 *      a list of field names to exclude
 *

 *

 *      fields
 *      Array
 *
 *          a subset of fields to use (inverse of excluded)
 *
 *

 *

 *
 * @name Form(fields | type, [doc])
 * @param {Object} fields  - an object literal containing fields or a Type
 * @param {Object} doc     - (optional) the original document being edited
 * @param {Object} options - (optional) see available options above
 * @constructor
 * @api public
 */

var Form = exports.Form = function Form(fields, doc, options) {
    this.options = options || {};

    this.values = null;
    if (doc) {
        this.values = JSON.parse(JSON.stringify(doc)); /* Copy */
        this.initial_doc = doc;
    }
    if (fields && fields.fields) {
        this.type = fields;
        this.fields = this.type.fields;
    }
    else {
        this.fields = fields;
    }
    /*if (utils.constructorName(fields) === 'Type') {
        this.type = fields;
        this.fields = this.type.field;
    }
    else {
        this.fields = fields;
    }*/
};

/**
 * Overrides values in doc_a with values in doc_b, only when a field is present
 * for that value. This means properties not in fields (or in excluded fields)
 * are retained, while properties which are covered by the fieldset are
 * replaced.
 *
 * This is used when updating the form's values with a request when its been
 * initiated with a previous document. You shouldn't normally need to call this
 * directly.
 *
 * Returns the updated doc_a object.
 *
 * @name override(excludes, field_subset, fields, doc_a, doc_b, path)
 * @param {Array | null} excludes
 * @param {Array | null} field_subset
 * @param {Object} Fields
 * @param {Object} doc_a
 * @param {Object} doc_b
 * @param {Array} path
 * @returns {Object}
 * @api public
 */

exports.override = function (excludes, field_subset, fields, doc_a, doc_b, path) {
    fields = fields || {};
    doc_a = doc_a || {};

    var fields_module = require('./fields');
    var exclude_paths = (excludes || []).map(function (p) {
        return p.split('.');
    });
    var subset_paths = (field_subset || []).map(function (p) {
        return p.split('.');
    });

    var keys = _.keys(doc_b);

    _.each(keys, function (k) {
        var f = fields[k];
        var b = doc_b[k];
        var f_path = path.concat([k]);

        if (typeof b !== 'object' ||
            f instanceof fields_module.Field ||
            f instanceof fields_module.Embedded ||
            f instanceof fields_module.EmbeddedList) {

            if (excludes) {
                for (var i = 0; i < exclude_paths.length; i++) {
                    if (utils.isSubPath(exclude_paths[i], f_path)) {
                        return;
                    }
                }
            }
            if (field_subset) {
                var in_subset = false;
                for (var j = 0; j < subset_paths.length; j++) {
                    if (utils.isSubPath(subset_paths[j], f_path)) {
                        in_subset = true;
                    }
                }
                if (!in_subset) {
                    return;
                }
            }
            doc_a[k] = b;
        }
        else {
            doc_a[k] = exports.override(
                excludes, field_subset, fields[k], doc_a[k], b, f_path
            );
        }
    });
    return doc_a;
};

/**
 * Parses a request and validates the result, binding values and errors to
 * the form instance.
 *
 * @name Form.validate(req)
 * @param {Object} req
 * @returns {Form}
 * @api public
 */

Form.prototype.validate = function (/*optional*/req) {
    if (!req) {
        req = utils.currentRequest();
    }

    var type_class = require('./types').Type;
    var tree = exports.formValuesToTree(this.raw);

    this.raw = req.form || {};
    this.values = exports.override(
        this.options.exclude,
        this.options.fields,
        this.fields,
        this.values || fieldset.createDefaults(this.fields, req) || {},
        exports.parseRaw(this.fields, tree),
        []
    );

    this.errors = fieldset.validate(
        this.fields, this.values, this.values, this.raw, [], false
    );

    if (this.type) {
        if (this.type instanceof type_class) {
            // run top level permissions first
            var type_errs = this.type.authorizeTypeLevel(
                this.values, this.initial_doc, req.userCtx
            );
            if (type_errs.length) {
                this.errors = this.errors.concat(type_errs);
            }
            else {
                // if no top-level permissions errors, check each field
                this.errors = this.errors.concat(
                    this.type.authorize(
                        this.values, this.initial_doc, req.userCtx
                    )
                );
            }
        } else {
            /* Programmer error: display a useful diagnostic message */
            throw new Error(
                'Encountered a type object that is not an instance of' +
                    ' `Type`; check lib/types.js for proper instansiation'
            );
        }

    }
    else {
        this.errors = this.errors.concat(fieldset.authFieldSet(
            this.fields, this.values, this.initial_doc, this.values,
            this.initial_doc, req.userCtx, [], true
        ));
    }

    // clear field properties on errors for excluded fields
    var excludes = this.options.exclude;
    if (excludes) {
        var excl_paths = _.map(excludes, function (p) {
            return p.split('.');
        });
        this.errors = _.map(this.errors, function (e) {
            if (!e.field) {
                return e;
            }
            for (var i = 0, len = excl_paths.length; i < len; i++) {
                var path = excl_paths[i];
                if (utils.isSubPath(path, e.field)) {
                    e.message = e.field.join('.') + ': ' + (
                        e.message || e.toString()
                    );
                    delete e.field;
                    return e;
                }
            }
            return e;
        });
    }

    // clear field properties on errors not in fields subset
    var field_subset = this.options.fields;
    if (field_subset) {
        var subset_paths = _.map(field_subset, function (p) {
            return p.split('.');
        });
        this.errors = _.map(this.errors, function (e) {
            if (!e.field) {
                return e;
            }
            for (var i = 0, len = subset_paths.length; i < len; i++) {
                var path = subset_paths[i];
                if (!utils.isSubPath(path, e.field)) {
                    e.message = e.field.join('.') + ': ' + (
                        e.message || e.toString()
                    );
                    delete e.field;
                    return e;
                }
            }
            return e;
        });
    }

    return this;
};

/**
 * After a form has called validate, this function will return true if the form
 * is valid, false otherwise.
 *
 * @name Form.isValid()
 * @returns {Boolean}
 * @api public
 */

Form.prototype.isValid = function () {
    return !(this.errors && this.errors.length);
};

/**
 * Filters an array of errors, returning only those below a specific field path
 *
 * @param {Array} errs
 * @param {Array} path
 * @returns {Array}
 */

var errsBelowPath = function (errs, path) {
    if (!path || !path.length) {
        return errs;
    }
    return _.filter(errs, function (e) {
        if (!e.field) {
            return false;
        }
        return utils.isSubPath(path, e.field);
    });
};

/**
 * Filters a list of errors, returning only those without a field property.
 * This is used to populate the errors at the top of the form, which apply
 * generally, or cannot be attributed to a single field.
 *
 * @param {Array} errs
 * @returns {Array}
 */

var errsWithoutFields = function (errs) {
    return _.filter(errs, function (e) {
        return !e.field;
    });
};

/**
 * Converts current form to a HTML string, using an optional renderer class.
 *
 * @name Form.toHTML(req, [RendererClass])
 * @param {Object} req Kanso request object; null for most recent. (optional)
 * @param {Renderer} renderer_class (optional)
 * @param {Object} options An object containing widget options, which
 *          will ultimately be provided to each widget's toHTML method.
 * @param {Boolean} create_defaults (optional) Set this to true if you've
 *          provided a document in {doc}, but would still like default
 *          values to be merged in to it via createDefaults. For a field f,
 *          the default value is added to {doc} if and only if doc[f]
 *          is undefined, null, or not present. Defaults to off.
 * @returns {String}
 * @returns {String}
 * @api public
 */

Form.prototype.toHTML = function (/* optional */ req,
                                  /* optional */ renderer_class,
                                  /* optional */ options,
                                  /* optional */ create_defaults) {
    if (!req) {
        req = utils.currentRequest();
    }
    var values = this.values;

    if (create_defaults) {
        values = _.defaults(
            values, fieldset.createDefaults(this.fields, req)
        );
    } else if (!values) {
        values = fieldset.createDefaults(this.fields, req);
    }

    renderer_class = (renderer_class || render.defaultRenderer());
    var renderer = new renderer_class();
    return (
        renderer.start(errsWithoutFields(this.errors)) +
        this.renderFields(
            renderer, this.fields,
                values, this.raw, this.errors, [], (options || {})
        ) +
        renderer.end() +
        render.scriptTagForEvent('renderFinish')
    );
};

/**
 * Filters an array of errors, returning only those below a specific field path
 *
 * @param {Array} errs
 * @param {Array} path
 * @returns {Array}
 */

var errsBelowPath = function (errs, path) {
    return _.filter(errs, function (e) {
        for (var i = 0, len = path.length; i < len; ++i) {
            if (path[i] !== e.field[i]) {
                return false;
            }
        }
        return true;
    });
};

/**
 * Iterates over fields and sub-objects calling the correct renderer function on
 * each. Returns a HTML representation of the fields. Used internally by the
 * toHTML method, you should not need to call this function directly.
 *
 * @name Form.renderFields(renderer, fields, values, raw, err, path)
 * @param {Object} renderer
 * @param {Object} fields
 * @param {Object} values
 * @param {Array} errs
 * @param {Array} path
 * @param {Object} options An object containing widget options, which
 *          will ultimately be provided to each widget's toHTML method.
 * @returns {String}
 * @api public
 */

Form.prototype.renderFields = function (renderer, fields, values,
                                        raw, errs, path, options) {
    fields = fields || {};
    values = values || {};
    raw = raw || {};
    errs = errs || [];
    path = path || [];

    var that = this;
    var excludes = this.options.exclude;
    var field_subset = this.options.fields;
    var keys = _.keys(fields);

    var fields_module = require('./fields');

    return _.reduce(keys, function (html, k) {

        var f_path = path.concat([k]);

        if (excludes) {
            if (_.indexOf(excludes, f_path.join('.')) !== -1) {
                return html;
            }
        }
        if (field_subset) {
            if (_.indexOf(field_subset, f_path.join('.')) === -1) {
                return html;
            }
        }

        var f_errs = errsBelowPath(errs, f_path);
        var f = fields[k];

        if (f instanceof fields_module.Field ||
            f instanceof fields_module.Embedded ||
            f instanceof fields_module.EmbeddedList) {

            return html + renderer.field(
                f,
                f_path,
                values[k],
                (raw[k] === undefined) ? values[k]: raw[k],
                f_errs,
                (options || {})
            );
        }
        else if (f instanceof Object) {
            return html + (k ? renderer.beginGroup(f_path) : '') +
                that.renderFields(
                    renderer,
                    f,
                    values[k],
                    (raw[k] === undefined) ? values[k]: raw[k],
                    errs,
                    f_path,
                    (options || {})
                ) + (k ? renderer.endGroup(f_path) : '');
        } else {
            throw new Error(
                'The field type `' + (typeof f) + '` is not supported.'
            );
        }
    }, '');
};

/**
 * Transforms a flat object from a request query to a proper
 * hierarchy of properties.
 *
 *
{'one.two': 'val'} --> {one: {two: 'val'}}

 *
 * @name formValuesToTree(form)
 * @param {Object} query
 * @api public
 */

exports.formValuesToTree = function (form) {
    var tree = {};
    for (var k in form) {
        utils.setPropertyPath(tree, k.split('.'), form[k]);
    }
    return tree;
};

/**
 * Transforms a raw query object from formValuesToTree to a
 * document which follows the schema for the given type.
 *
 * @name parseRaw(fields, raw)
 * @param {Type} type
 * @param {Object} raw
 * @returns {Object}
 * @api public
 */

exports.parseRaw = function (fields, raw) {
    var doc = {};
    raw = raw || {};
    var fields_module = require('./fields');

    for (var k in fields) {
        var f = fields[k];
        var r = raw[k];

        if (f instanceof fields_module.Field) {
            if (!f.isEmpty(r)) {
                doc[k] = f.parse(r);
            }
            else if (!f.omit_empty) {
                doc[k] = undefined;
            }
        }
        else if (f instanceof fields_module.Embedded) {
            if (!f.isEmpty(r)) {
                if (typeof r === 'string') {
                    if (r !== '') {
                        doc[k] = JSON.parse(r);
                    }
                }
                else {
                    doc[k] = exports.parseRaw(f.type.fields, r);
                }
            }
        }
        else if (f instanceof fields_module.EmbeddedList) {
            doc[k] = [];
            for (var i in r) {
                var val;
                if (typeof r[i] === 'string') {
                    if (r[i] !== '') {
                        val = JSON.parse(r[i]);
                    }
                }
                else {
                    val = exports.parseRaw(f.type.fields, r[i]);
                }
                if (!f.isEmpty(val)) {
                    doc[k][i] = val;
                }
            }
            if (!doc[k].length && f.omit_empty) {
                delete doc[k];
            }
        }
        else if (f instanceof Object) {
            doc[k] = exports.parseRaw(f, r);
        } else {
            throw new Error(
                'The field type `' + (typeof f) + '` is not supported.'
            );
        }
    }
    return doc;
};

<|endoftext|>


<commit_before>let fs = require("fs");
let path = require("path");
let yaml = require("js-yaml");

//Front matter regex
let frontMatter = /^-{3}(?:[^\r\n]*?)(?:\r?\n)([\s\S]*?)^-{3}(?:[\s\S]*?)(?:\r?\n)/m;

//Generate vfile path
let getVFilePath = function (vfile) {
    return path.format({
        "root": "/",
        "dir": vfile.dirname,
        "name": vfile.filename,
        "ext": vfile.extname
    });
};

//Read the content of the viftual-file
let readVFile = function (vfile) {
    vfile.content = fs.readFileSync(getVFilePath(vfile), "utf8");
    //Check if file starts with three '-'
    if (vfile.content.indexOf("---") === 0) {
        //Overwrite the file content and parse the front matter
        vfile.content = vfile.content.replace(frontMatter, function (match, block) {
            vfile.data = Object.assign({}, yaml.safeLoad(block));
            return ""; //Remove the front-matter section
        });
    }
    return vfile;
};

//Write a vfile
let writeVFile = function (vfile) {
    return fs.writeFileSync(getVFilePath(vfile), vfile.content, "utf8");
};

//Create a new virtual file object
module.exports = function (filePath) {
    //Initialize the virtual file object
    return Object.assign({}, {
        "dirname": path.dirname(filePath),
        "filename": path.basename(filePath, path.extname(filePath)),
        "extname": path.extname(filePath),
        "data": {},
        "content": null
    });
};

//Export utility methods
module.exports.path = getVFilePath;
module.exports.read = readVFile;
module.exports.write = writeVFile;

<commit_msg>commons: check if the dirname of the virtual file exists before writting the virtual file<commit_after>let fs = require("fs");
let path = require("path");
let yaml = require("js-yaml");

//Front matter regex
let frontMatter = /^-{3}(?:[^\r\n]*?)(?:\r?\n)([\s\S]*?)^-{3}(?:[\s\S]*?)(?:\r?\n)/m;

//Generate vfile path
let getVFilePath = function (vfile) {
    return path.format({
        "root": "/",
        "dir": vfile.dirname,
        "name": vfile.filename,
        "ext": vfile.extname
    });
};

//Read the content of the viftual-file
let readVFile = function (vfile) {
    vfile.content = fs.readFileSync(getVFilePath(vfile), "utf8");
    //Check if file starts with three '-'
    if (vfile.content.indexOf("---") === 0) {
        //Overwrite the file content and parse the front matter
        vfile.content = vfile.content.replace(frontMatter, function (match, block) {
            vfile.data = Object.assign({}, yaml.safeLoad(block));
            return ""; //Remove the front-matter section
        });
    }
    return vfile;
};

//Write a vfile
let writeVFile = function (vfile) {
    if (fs.existsSync(vfile.dirname) === false) {
        fs.mkdirSync(vfile.dirname, {
            "recursive": true
        });
    }
    //Write the file content
    return fs.writeFileSync(getVFilePath(vfile), vfile.content, "utf8");
};

//Create a new virtual file object
module.exports = function (filePath) {
    //Initialize the virtual file object
    return Object.assign({}, {
        "dirname": path.dirname(filePath),
        "filename": path.basename(filePath, path.extname(filePath)),
        "extname": path.extname(filePath),
        "data": {},
        "content": null
    });
};

//Export utility methods
module.exports.path = getVFilePath;
module.exports.read = readVFile;
module.exports.write = writeVFile;

<|endoftext|>


<commit_before>/**
 * @namespace hs
 */

/**
 * @namespace hs.core
 * @memberOf hs
 */
require.config({
    paths: {
        angular: hsl_path + 'bower_components/angular/angular',
        ngcookies: hsl_path + 'bower_components/angular-cookies/angular-cookies',
        bootstrap: hsl_path + 'bower_components/bootstrap/dist/js/bootstrap',
        ol: requirejs.s.contexts._.config.paths.ol || hsl_path + 'node_modules/openlayers/dist/ol',
        drag: hsl_path + 'components/drag/drag',
        map: hsl_path + 'components/map/map',
        styles: hsl_path + 'components/styles/styles',
        'angular-sanitize': hsl_path + 'bower_components/angular-sanitize/angular-sanitize',
        'angular-gettext': hsl_path + 'bower_components/angular-gettext/dist/angular-gettext',
        compositions: hsl_path + 'components/compositions/compositions',
        permalink: requirejs.s.contexts._.config.paths.permalink || hsl_path + 'components/permalink/permalink',
        utils: hsl_path + 'components/utils',
        status_creator: hsl_path + 'components/status_creator/status_creator',
        xml2json: requirejs.s.contexts._.config.paths.xml2json || hsl_path + 'bower_components/xml2json/xml2json.min',
        customhtml: requirejs.s.contexts._.config.paths.customhtml || hsl_path + 'components/customhtml/customhtml',
        d3: requirejs.s.contexts._.config.paths.d3 || hsl_path + 'bower_components/d3/d3.min',
        proj4: requirejs.s.contexts._.config.paths.proj4 || hsl_path + 'bower_components/proj4/dist/proj4',
        crossfilter: requirejs.s.contexts._.config.paths.crossfilter || hsl_path + 'bower_components/crossfilter/crossfilter.min',
        dc: requirejs.s.contexts._.config.paths.dc || '//cdnjs.cloudflare.com/ajax/libs/dc/1.7.0/dc',
        api: requirejs.s.contexts._.config.paths.api || hsl_path + 'components/api/api',
        translations: requirejs.s.contexts._.config.paths.translations || hsl_path + 'components/translations/js/translations',
        sidebar: requirejs.s.contexts._.config.paths.sidebar || hsl_path + 'components/sidebar/sidebar',
        geojson: requirejs.s.contexts._.config.paths.geojson || hsl_path + 'components/layers/hs.source.GeoJSON',
        mobile_toolbar: requirejs.s.contexts._.config.paths.mobile_toolbar || hsl_path + 'components/mobile_toolbar/mobile_toolbar',
        SparqlJson: requirejs.s.contexts._.config.paths.SparqlJson || hsl_path + 'components/layers/hs.source.SparqlJson',
        WFSCapabilities: requirejs.s.contexts._.config.paths.WFSCapabilities || hsl_path + 'components/format/hs.format.WFSCapabilities',
        WfsSource: requirejs.s.contexts._.config.paths.WfsSource || hsl_path + 'components/layers/hs.source.Wfs',
        'ows.wfs': requirejs.s.contexts._.config.paths.['ows.wfs']|| hsl_path + 'components/ows/ows_wfs',
    },
    shim: {
        'angular': {
            'exports': 'angular'
        },
        'angular-sanitize': {
            deps: ['angular'],
        },
        'angular-gettext': {
            deps: ['angular'],
        },
        ngcookies: {
            deps: ['angular'],
        },
        translations: {
            deps: ['angular-gettext'],
        }
    },
    priority: [
        "angular"
    ]
});

define(['angular', 'angular-gettext', 'translations', 'ol', 'map', 'drag', 'api', 'proj4'],
    function(angular, proj4) {
        angular.module('hs.core', ['hs.map', 'gettext', 'gettext', 'hs.drag', 'hs.api'])
            .service("Core", ['$rootScope', '$controller', '$window', 'hs.map.service', 'gettextCatalog', 'config', '$templateCache',
                function($rootScope, $controller, $window, OlMap, gettextCatalog, config, $templateCache) {
                    var me = {
                        config: config,
                        scopes_registered: [],
                        mainpanel: "",
                        defaultPanel: "",
                        sidebarExpanded: false,
                        sidebarRight: true,
                        sidebarLabels: true,
                        sidebarToggleable: true,
                        sidebarButtons: true,
                        singleDatasources: false,
                        embededEnabled: true,
                        panel_statuses: {},
                        _exist_cache: {},
                        setMainPanel: function(which, by_gui) {
                            if (which == me.mainpanel && by_gui) {
                                which = "";
                                if (me.sidebarExpanded == true) {
                                    me.sidebarLabels = true;
                                }
                            } else {
                                me.sidebarExpanded = true;
                                me.sidebarLabels = false;
                            }
                            me.mainpanel = which;
                            if (!$rootScope.$$phase) $rootScope.$digest();
                            $rootScope.$broadcast('core.mainpanel_changed');
                        },
                        setDefaultPanel: function(which) {
                            me.defaultPanel = which;
                            me.setMainPanel(which);
                        },
                        updateMapSize: function(open) {
                            var w = angular.element($window);
                            var map = $("#map");
                            var sidebarElem = $('.panelspace');
                            if (w.width() != sidebarElem.width()) {
                                map.width(w.width() - sidebarElem.width());
                            } else {
                                map.width(w.width());
                            }
                            OlMap.map.updateSize();
                        },

                        panelVisible: function(which, scope) {
                            if (angular.isDefined(scope))
                                if (angular.isUndefined(scope.panel_name)) scope.panel_name = which;
                            if (angular.isDefined(me.panel_statuses[which])) {
                                return me.panel_statuses[which];
                            }
                            return me.mainpanel == which || (angular.isDefined(scope) && scope.unpinned);
                        },
                        hidePanels: function() {
                            me.mainpanel = '';
                            me.sidebarLabels = true;
                            if (!me.exists('hs.sidebar.controller')) {
                                me.sidebarExpanded = false
                            }
                            if (!$rootScope.$$phase) $rootScope.$digest();
                            $rootScope.$broadcast('core.mainpanel_changed');
                        },
                        closePanel: function(which) {
                            if (which.unpinned) {
                                which.drag_panel.appendTo($(which.original_container));
                                which.drag_panel.css({
                                    top: 'auto',
                                    left: 'auto',
                                    position: 'relative'
                                });
                            }
                            which.unpinned = false;
                            if (which.panel_name == me.mainpanel) {
                                if (me.defaultPanel != '') {
                                    me.setMainPanel(me.defaultPanel)
                                } else {
                                    me.mainpanel = '';
                                    me.sidebarLabels = true;
                                }
                                if (!me.exists('hs.sidebar.controller')) {
                                    me.sidebarExpanded = false
                                }

                            }

                            $rootScope.$broadcast('core.mainpanel_changed');
                        },
                        exists: function(controllerName) {
                            if (angular.isDefined(me._exist_cache[controllerName])) return true;
                            if (typeof window[controllerName] == 'function') {
                                return true;
                            }
                            try {
                                $controller(controllerName);
                                me._exist_cache[controllerName] = true;
                                return true;
                            } catch (error) {
                                var t = !(error instanceof TypeError);
                                if (t) me._exist_cache[controllerName] = true;
                                return t;
                            }
                        },
                        fullScreenMap: function(element) {
                            var w = angular.element($window);
                            w.bind('resize', function() {
                                $("html").css('overflow', 'hidden');
                                $("html").css('height', '100%');
                                $('body').css('height', '100%');
                                element[0].style.height = w.height() + "px";
                                element[0].style.width = w.width() + "px";
                                $("#map").height(w.height());
                                me.updateMapSize();
                                OlMap.map.updateSize();
                            });
                            w.resize();
                        },
                        setLanguage: function(lang) {
                            switch (lang) {
                                case "cs_CZ":
                                    lang = 'cs';
                                    break;
                                case "nl_BE":
                                    lang = 'nl';
                                    break;
                            }
                            gettextCatalog.setCurrentLanguage(lang);
                        },
                        getAllScopes: function() {
                            var getScopes = function(root) {
                                var scopes = [];

                                function visit(scope) {
                                    scopes.push(scope);
                                }

                                function traverse(scope) {
                                    visit(scope);
                                    if (scope.$$nextSibling)
                                        traverse(scope.$$nextSibling);
                                    if (scope.$$childHead)
                                        traverse(scope.$$childHead);
                                }

                                traverse(root);
                                return scopes;
                            }
                            return getScopes($rootScope);
                        },
                        openStatusCreator: function() {
                            //me.panel_statuses.status_creator = true;
                            hslayers_api.gui.StatusCreator.open();
                        },
                        searchVisible: function(is) {
                            if (arguments.length > 0) {
                                me.panel_statuses['search'] = is;
                            }
                            return me.panel_statuses['search']
                        },
                        isAuthorized: function() {
                            if (angular.isDefined(window.getLRUser) && window.getLRUser() != 'guest') {
                                return true;
                            }
                            return false;
                        },
                        resetMap: function() {
                            OlMap.reset();
                            $rootScope.$broadcast('core.map_reset', {});
                        },
                        isMobile: function() {
                            if (screen.width < 800) {
                                return "mobile";
                            } else {
                                return "";
                            }
                        }
                    };

                    $templateCache.removeAll();

                    if (me.exists('hs.sidebar.controller')) {
                        me.sidebarExpanded = true;
                    }

                    if (me.defaultPanel != '') {
                        me.setMainPanel(me.defaultPanel);
                    }

                    /* HACK: https://github.com/openlayers/ol3/issues/3990 */
                    try {
                        if (typeof require('proj4') != undefined) {
                            require(['proj4'], function() {
                                window.proj4 = proj4
                            });
                        }
                    } catch (ex) {
                        require(['proj4'], function() {
                            window.proj4 = proj4
                        });
                    }

                    return me;
                },

            ]);

    })
<commit_msg>extra point<commit_after>/**
 * @namespace hs
 */

/**
 * @namespace hs.core
 * @memberOf hs
 */
require.config({
    paths: {
        angular: hsl_path + 'bower_components/angular/angular',
        ngcookies: hsl_path + 'bower_components/angular-cookies/angular-cookies',
        bootstrap: hsl_path + 'bower_components/bootstrap/dist/js/bootstrap',
        ol: requirejs.s.contexts._.config.paths.ol || hsl_path + 'node_modules/openlayers/dist/ol',
        drag: hsl_path + 'components/drag/drag',
        map: hsl_path + 'components/map/map',
        styles: hsl_path + 'components/styles/styles',
        'angular-sanitize': hsl_path + 'bower_components/angular-sanitize/angular-sanitize',
        'angular-gettext': hsl_path + 'bower_components/angular-gettext/dist/angular-gettext',
        compositions: hsl_path + 'components/compositions/compositions',
        permalink: requirejs.s.contexts._.config.paths.permalink || hsl_path + 'components/permalink/permalink',
        utils: hsl_path + 'components/utils',
        status_creator: hsl_path + 'components/status_creator/status_creator',
        xml2json: requirejs.s.contexts._.config.paths.xml2json || hsl_path + 'bower_components/xml2json/xml2json.min',
        customhtml: requirejs.s.contexts._.config.paths.customhtml || hsl_path + 'components/customhtml/customhtml',
        d3: requirejs.s.contexts._.config.paths.d3 || hsl_path + 'bower_components/d3/d3.min',
        proj4: requirejs.s.contexts._.config.paths.proj4 || hsl_path + 'bower_components/proj4/dist/proj4',
        crossfilter: requirejs.s.contexts._.config.paths.crossfilter || hsl_path + 'bower_components/crossfilter/crossfilter.min',
        dc: requirejs.s.contexts._.config.paths.dc || '//cdnjs.cloudflare.com/ajax/libs/dc/1.7.0/dc',
        api: requirejs.s.contexts._.config.paths.api || hsl_path + 'components/api/api',
        translations: requirejs.s.contexts._.config.paths.translations || hsl_path + 'components/translations/js/translations',
        sidebar: requirejs.s.contexts._.config.paths.sidebar || hsl_path + 'components/sidebar/sidebar',
        geojson: requirejs.s.contexts._.config.paths.geojson || hsl_path + 'components/layers/hs.source.GeoJSON',
        mobile_toolbar: requirejs.s.contexts._.config.paths.mobile_toolbar || hsl_path + 'components/mobile_toolbar/mobile_toolbar',
        SparqlJson: requirejs.s.contexts._.config.paths.SparqlJson || hsl_path + 'components/layers/hs.source.SparqlJson',
        WFSCapabilities: requirejs.s.contexts._.config.paths.WFSCapabilities || hsl_path + 'components/format/hs.format.WFSCapabilities',
        WfsSource: requirejs.s.contexts._.config.paths.WfsSource || hsl_path + 'components/layers/hs.source.Wfs',
        'ows.wfs': requirejs.s.contexts._.config.paths['ows.wfs']|| hsl_path + 'components/ows/ows_wfs',
    },
    shim: {
        'angular': {
            'exports': 'angular'
        },
        'angular-sanitize': {
            deps: ['angular'],
        },
        'angular-gettext': {
            deps: ['angular'],
        },
        ngcookies: {
            deps: ['angular'],
        },
        translations: {
            deps: ['angular-gettext'],
        }
    },
    priority: [
        "angular"
    ]
});

define(['angular', 'angular-gettext', 'translations', 'ol', 'map', 'drag', 'api', 'proj4'],
    function(angular, proj4) {
        angular.module('hs.core', ['hs.map', 'gettext', 'gettext', 'hs.drag', 'hs.api'])
            .service("Core", ['$rootScope', '$controller', '$window', 'hs.map.service', 'gettextCatalog', 'config', '$templateCache',
                function($rootScope, $controller, $window, OlMap, gettextCatalog, config, $templateCache) {
                    var me = {
                        config: config,
                        scopes_registered: [],
                        mainpanel: "",
                        defaultPanel: "",
                        sidebarExpanded: false,
                        sidebarRight: true,
                        sidebarLabels: true,
                        sidebarToggleable: true,
                        sidebarButtons: true,
                        singleDatasources: false,
                        embededEnabled: true,
                        panel_statuses: {},
                        _exist_cache: {},
                        setMainPanel: function(which, by_gui) {
                            if (which == me.mainpanel && by_gui) {
                                which = "";
                                if (me.sidebarExpanded == true) {
                                    me.sidebarLabels = true;
                                }
                            } else {
                                me.sidebarExpanded = true;
                                me.sidebarLabels = false;
                            }
                            me.mainpanel = which;
                            if (!$rootScope.$$phase) $rootScope.$digest();
                            $rootScope.$broadcast('core.mainpanel_changed');
                        },
                        setDefaultPanel: function(which) {
                            me.defaultPanel = which;
                            me.setMainPanel(which);
                        },
                        updateMapSize: function(open) {
                            var w = angular.element($window);
                            var map = $("#map");
                            var sidebarElem = $('.panelspace');
                            if (w.width() != sidebarElem.width()) {
                                map.width(w.width() - sidebarElem.width());
                            } else {
                                map.width(w.width());
                            }
                            OlMap.map.updateSize();
                        },

                        panelVisible: function(which, scope) {
                            if (angular.isDefined(scope))
                                if (angular.isUndefined(scope.panel_name)) scope.panel_name = which;
                            if (angular.isDefined(me.panel_statuses[which])) {
                                return me.panel_statuses[which];
                            }
                            return me.mainpanel == which || (angular.isDefined(scope) && scope.unpinned);
                        },
                        hidePanels: function() {
                            me.mainpanel = '';
                            me.sidebarLabels = true;
                            if (!me.exists('hs.sidebar.controller')) {
                                me.sidebarExpanded = false
                            }
                            if (!$rootScope.$$phase) $rootScope.$digest();
                            $rootScope.$broadcast('core.mainpanel_changed');
                        },
                        closePanel: function(which) {
                            if (which.unpinned) {
                                which.drag_panel.appendTo($(which.original_container));
                                which.drag_panel.css({
                                    top: 'auto',
                                    left: 'auto',
                                    position: 'relative'
                                });
                            }
                            which.unpinned = false;
                            if (which.panel_name == me.mainpanel) {
                                if (me.defaultPanel != '') {
                                    me.setMainPanel(me.defaultPanel)
                                } else {
                                    me.mainpanel = '';
                                    me.sidebarLabels = true;
                                }
                                if (!me.exists('hs.sidebar.controller')) {
                                    me.sidebarExpanded = false
                                }

                            }

                            $rootScope.$broadcast('core.mainpanel_changed');
                        },
                        exists: function(controllerName) {
                            if (angular.isDefined(me._exist_cache[controllerName])) return true;
                            if (typeof window[controllerName] == 'function') {
                                return true;
                            }
                            try {
                                $controller(controllerName);
                                me._exist_cache[controllerName] = true;
                                return true;
                            } catch (error) {
                                var t = !(error instanceof TypeError);
                                if (t) me._exist_cache[controllerName] = true;
                                return t;
                            }
                        },
                        fullScreenMap: function(element) {
                            var w = angular.element($window);
                            w.bind('resize', function() {
                                $("html").css('overflow', 'hidden');
                                $("html").css('height', '100%');
                                $('body').css('height', '100%');
                                element[0].style.height = w.height() + "px";
                                element[0].style.width = w.width() + "px";
                                $("#map").height(w.height());
                                me.updateMapSize();
                                OlMap.map.updateSize();
                            });
                            w.resize();
                        },
                        setLanguage: function(lang) {
                            switch (lang) {
                                case "cs_CZ":
                                    lang = 'cs';
                                    break;
                                case "nl_BE":
                                    lang = 'nl';
                                    break;
                            }
                            gettextCatalog.setCurrentLanguage(lang);
                        },
                        getAllScopes: function() {
                            var getScopes = function(root) {
                                var scopes = [];

                                function visit(scope) {
                                    scopes.push(scope);
                                }

                                function traverse(scope) {
                                    visit(scope);
                                    if (scope.$$nextSibling)
                                        traverse(scope.$$nextSibling);
                                    if (scope.$$childHead)
                                        traverse(scope.$$childHead);
                                }

                                traverse(root);
                                return scopes;
                            }
                            return getScopes($rootScope);
                        },
                        openStatusCreator: function() {
                            //me.panel_statuses.status_creator = true;
                            hslayers_api.gui.StatusCreator.open();
                        },
                        searchVisible: function(is) {
                            if (arguments.length > 0) {
                                me.panel_statuses['search'] = is;
                            }
                            return me.panel_statuses['search']
                        },
                        isAuthorized: function() {
                            if (angular.isDefined(window.getLRUser) && window.getLRUser() != 'guest') {
                                return true;
                            }
                            return false;
                        },
                        resetMap: function() {
                            OlMap.reset();
                            $rootScope.$broadcast('core.map_reset', {});
                        },
                        isMobile: function() {
                            if (screen.width < 800) {
                                return "mobile";
                            } else {
                                return "";
                            }
                        }
                    };

                    $templateCache.removeAll();

                    if (me.exists('hs.sidebar.controller')) {
                        me.sidebarExpanded = true;
                    }

                    if (me.defaultPanel != '') {
                        me.setMainPanel(me.defaultPanel);
                    }

                    /* HACK: https://github.com/openlayers/ol3/issues/3990 */
                    try {
                        if (typeof require('proj4') != undefined) {
                            require(['proj4'], function() {
                                window.proj4 = proj4
                            });
                        }
                    } catch (ex) {
                        require(['proj4'], function() {
                            window.proj4 = proj4
                        });
                    }

                    return me;
                },

            ]);

    })
<|endoftext|>


<commit_before>import React from 'react'
import Head from 'next/head'

import reset from 'semantic-ui-css/components/reset.min.css'
import site from 'semantic-ui-css/components/site.min.css'

const Meta = () => (
  <Head>
    <meta charSet='utf-8' />
    <meta name='viewport' content='width=device-width, initial-scale=1' />

    <meta name='theme-color' content='#ffffff' />

    <link rel='apple-touch-icon' sizes='180x180' href='/static/favicons/apple-icon-180x180.png' />
    <link rel='icon' type='image/png' sizes='16x16' href='/static/favicons/favicon-16x16.png' />
    <link rel='icon' type='image/png' sizes='32x32' href='/static/favicons/favicon-32x32.png' />
    <link rel='manifest' href='/static/favicons/manifest.json' />
    <link rel='mask-icon' href='/static/favicons/safari-pinned-tab.svg' color='#5bbad5' />

    {/* Global style */}
    <style dangerouslySetInnerHTML={{ __html: reset }} />
    <style dangerouslySetInnerHTML={{ __html: site }} />
  </Head>
)

export default Meta
<commit_msg>Remove semantic’s site CSS<commit_after>import React from 'react'
import Head from 'next/head'

import reset from 'semantic-ui-css/components/reset.min.css'

const Meta = () => (
  <Head>
    <meta charSet='utf-8' />
    <meta name='viewport' content='width=device-width, initial-scale=1' />

    <meta name='theme-color' content='#ffffff' />

    <link rel='apple-touch-icon' sizes='180x180' href='/static/favicons/apple-icon-180x180.png' />
    <link rel='icon' type='image/png' sizes='16x16' href='/static/favicons/favicon-16x16.png' />
    <link rel='icon' type='image/png' sizes='32x32' href='/static/favicons/favicon-32x32.png' />
    <link rel='manifest' href='/static/favicons/manifest.json' />
    <link rel='mask-icon' href='/static/favicons/safari-pinned-tab.svg' color='#5bbad5' />

    {/* Global style */}
    <style dangerouslySetInnerHTML={{ __html: reset }} />
  </Head>
)

export default Meta
<|endoftext|>


<commit_before>Prism.languages.sql= {
	'comment': {
		pattern: /(^|[^\\])(\/\*[\w\W]*?\*\/|((--)|(\/\/)|#).*?(\r?\n|$))/g,
		lookbehind: true
	},
	'string' : /("|')(\\?(.|\n))*?\1/g,
	'keyword' : /\b(ACTION|ADD|AFTER|ALGORITHM|ALTER|ANALYZE|APPLY|AS|ASC|AUTHORIZATION|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADE|CASCADED|CASE|CHAIN|CHAR VARYING|CHARACTER VARYING|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLUMN|COLUMNS|COMMENT|COMMIT|COMMITTED|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATA|DATABASE|DATABASES|DATETIME|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DOUBLE PRECISION|DROP|DUMMY|DUMP|DUMPFILE|DUPLICATE KEY|ELSE|ENABLE|ENCLOSED BY|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPE|ESCAPED BY|EXCEPT|EXEC|EXECUTE|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR|FOR EACH ROW|FORCE|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GEOMETRY|GEOMETRYCOLLECTION|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|IDENTITY|IDENTITY_INSERT|IDENTITYCOL|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTO|INVOKER|ISOLATION LEVEL|JOIN|KEY|KEYS|KILL|LANGUAGE SQL|LAST|LEFT|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONGBLOB|LONGTEXT|MATCH|MATCHED|MEDIUMBLOB|MEDIUMINT|MEDIUMTEXT|MERGE|MIDDLEINT|MODIFIES SQL DATA|MODIFY|MULTILINESTRING|MULTIPOINT|MULTIPOLYGON|NATIONAL|NATIONAL CHAR VARYING|NATIONAL CHARACTER|NATIONAL CHARACTER VARYING|NATIONAL VARCHAR|NATURAL|NCHAR|NCHAR VARCHAR|NEXT|NO|NO SQL|NOCHECK|NOCYCLE|NONCLUSTERED|NULLIF|NUMERIC|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPTIMIZE|OPTION|OPTIONALLY|ORDER|OUT|OUTER|OUTFILE|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREV|PRIMARY|PRINT|PRIVILEGES|PROC|PROCEDURE|PUBLIC|PURGE|QUICK|RAISERROR|READ|READS SQL DATA|READTEXT|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEATABLE|REPLICATION|REQUIRE|RESTORE|RESTRICT|RETURN|RETURNS|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROWCOUNT|ROWGUIDCOL|ROWS?|RTREE|RULE|SAVE|SAVEPOINT|SCHEMA|SELECT|SERIAL|SERIALIZABLE|SESSION|SESSION_USER|SET|SETUSER|SHARE MODE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|START|STARTING BY|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLE|TABLES|TABLESPACE|TEMPORARY|TEMPTABLE|TERMINATED BY|TEXT|TEXTSIZE|THEN|TIMESTAMP|TINYBLOB|TINYINT|TINYTEXT|TO|TOP|TRAN|TRANSACTION|TRANSACTIONS|TRIGGER|TRUNCATE|TSEQUAL|TYPE|TYPES|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNPIVOT|UPDATE|UPDATETEXT|USAGE|USE|USER|USING|VALUE|VALUES|VARBINARY|VARCHAR|VARCHARACTER|VARYING|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH|WITH ROLLUP|WITHIN|WORK|WRITE|WRITETEXT)\b/gi,
	'boolean' : /\b(TRUE|FALSE|NULL)\b/gi,
	'number' : /\b-?(0x)?\d*\.?[\da-f]+\b/g,
	'operator' : /\b(ALL|AND|ANY|BETWEEN|EXISTS|IN|LIKE|NOT|OR|IS|UNIQUE|CHARACTER SET|COLLATE|DIV|OFFSET|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b|[-+]{1}|!|=?<|=?>|={1}|(&){1,2}|\|?\||\?|\*|\//gi,
	'ignore' : /&(lt|gt|amp);/gi,
	'punctuation' : /[;[\]()`,.]/g
};
<commit_msg>Update prism-sql.js<commit_after>Prism.languages.sql= {
	'comment': {
		pattern: /(^|[^\\])(\/\*[\w\W]*?\*\/|((--)|(\/\/)|#).*?(\r?\n|$))/g,
		lookbehind: true
	},
	'string' : /("|')(\\?[\s\S])*?\1/g,
	'keyword' : /\b(ACTION|ADD|AFTER|ALGORITHM|ALTER|ANALYZE|APPLY|AS|ASC|AUTHORIZATION|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADE|CASCADED|CASE|CHAIN|CHAR VARYING|CHARACTER VARYING|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLUMN|COLUMNS|COMMENT|COMMIT|COMMITTED|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATA|DATABASE|DATABASES|DATETIME|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DOUBLE PRECISION|DROP|DUMMY|DUMP|DUMPFILE|DUPLICATE KEY|ELSE|ENABLE|ENCLOSED BY|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPE|ESCAPED BY|EXCEPT|EXEC|EXECUTE|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR|FOR EACH ROW|FORCE|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GEOMETRY|GEOMETRYCOLLECTION|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|IDENTITY|IDENTITY_INSERT|IDENTITYCOL|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTO|INVOKER|ISOLATION LEVEL|JOIN|KEY|KEYS|KILL|LANGUAGE SQL|LAST|LEFT|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONGBLOB|LONGTEXT|MATCH|MATCHED|MEDIUMBLOB|MEDIUMINT|MEDIUMTEXT|MERGE|MIDDLEINT|MODIFIES SQL DATA|MODIFY|MULTILINESTRING|MULTIPOINT|MULTIPOLYGON|NATIONAL|NATIONAL CHAR VARYING|NATIONAL CHARACTER|NATIONAL CHARACTER VARYING|NATIONAL VARCHAR|NATURAL|NCHAR|NCHAR VARCHAR|NEXT|NO|NO SQL|NOCHECK|NOCYCLE|NONCLUSTERED|NULLIF|NUMERIC|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPTIMIZE|OPTION|OPTIONALLY|ORDER|OUT|OUTER|OUTFILE|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREV|PRIMARY|PRINT|PRIVILEGES|PROC|PROCEDURE|PUBLIC|PURGE|QUICK|RAISERROR|READ|READS SQL DATA|READTEXT|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEATABLE|REPLICATION|REQUIRE|RESTORE|RESTRICT|RETURN|RETURNS|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROWCOUNT|ROWGUIDCOL|ROWS?|RTREE|RULE|SAVE|SAVEPOINT|SCHEMA|SELECT|SERIAL|SERIALIZABLE|SESSION|SESSION_USER|SET|SETUSER|SHARE MODE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|START|STARTING BY|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLE|TABLES|TABLESPACE|TEMPORARY|TEMPTABLE|TERMINATED BY|TEXT|TEXTSIZE|THEN|TIMESTAMP|TINYBLOB|TINYINT|TINYTEXT|TO|TOP|TRAN|TRANSACTION|TRANSACTIONS|TRIGGER|TRUNCATE|TSEQUAL|TYPE|TYPES|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNPIVOT|UPDATE|UPDATETEXT|USAGE|USE|USER|USING|VALUE|VALUES|VARBINARY|VARCHAR|VARCHARACTER|VARYING|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH|WITH ROLLUP|WITHIN|WORK|WRITE|WRITETEXT)\b/gi,
	'boolean' : /\b(TRUE|FALSE|NULL)\b/gi,
	'number' : /\b-?(0x)?\d*\.?[\da-f]+\b/g,
	'operator' : /\b(ALL|AND|ANY|BETWEEN|EXISTS|IN|LIKE|NOT|OR|IS|UNIQUE|CHARACTER SET|COLLATE|DIV|OFFSET|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b|[-+]{1}|!|=?<|=?>|={1}|(&){1,2}|\|?\||\?|\*|\//gi,
	'ignore' : /&(lt|gt|amp);/gi,
	'punctuation' : /[;[\]()`,.]/g
};
<|endoftext|>


<commit_before>'use strict';

//live

var unirest = require('unirest');
//ip of clockwork
var ip = '10.38.156.86';
var id = 0;
var index = 0;
var interval = null;
var line = 0;

var tail = function() {

    var error = 0;
    var finished = 0;

    unirest.get('http://' + ip + ':3000/hourly-comscore/tail/' + id + '/' + index)
    .end(function(result) {
        if (result.status === 200) {
            var last = result.body.length - 1;

            if (result.body[last] && result.body[last].line) {
                index = result.body[last].line;
            } else {
                index = 0;
            }

            if (Array.isArray(result.body)) {
                result.body.forEach(function(row){

                    if (line !== row.line) {
                        console.log('Line ' + row.line + ': ' + row.message);
                        line = row.line;
                    }

                    if (row.status === 'finished') {
                        finished++;
                    }

                    if (row.status === 'error') {
                        console.log('error:', row);
                        error++;
                    }

                });

                if (error > 0) {
                    clearInterval(interval);
                    console.log('exit with 1');
                    process.exit(1);
                }

                if (finished > 0) {
                    clearInterval(interval);
                    console.log('exit with 0');
                    process.exit(0);
                }

            } else {

                console.log('Line ' + result.body.line + ':' + result.body.message);

                if (result.body.status === 'finished') {
                    clearInterval(interval);
                    console.log('exit with 0');
                    process.exit(0);
                }

                 if (result.body.status === 'error') {
                    clearInterval(interval);
                    console.log('exit with 1');
                    process.exit(1);
                }
            }
        }
    });
};

unirest.get('http://' + ip +':3000/hourly-comscore/start')
.end(function(result) {
    if (result.status === 200) {
        id = result.body.id;
        interval = setInterval(tail, 2000);
    } else {
        console.log('exit with 1');
        process.exit(1);
    }
});

<commit_msg>elb update<commit_after>'use strict';

//live

var unirest = require('unirest');
//ip of clockwork
var ip = 'internal-live-cloc-Componen-A0S56IYQFT5B-1619225976.eu-west-1.elb.amazonaws.com';
var id = 0;
var index = 0;
var interval = null;
var line = 0;

var tail = function() {

    var error = 0;
    var finished = 0;

    unirest.get('http://' + ip + ':3000/hourly-comscore/tail/' + id + '/' + index)
    .end(function(result) {
        if (result.status === 200) {
            var last = result.body.length - 1;

            if (result.body[last] && result.body[last].line) {
                index = result.body[last].line;
            } else {
                index = 0;
            }

            if (Array.isArray(result.body)) {
                result.body.forEach(function(row){

                    if (line !== row.line) {
                        console.log('Line ' + row.line + ': ' + row.message);
                        line = row.line;
                    }

                    if (row.status === 'finished') {
                        finished++;
                    }

                    if (row.status === 'error') {
                        console.log('error:', row);
                        error++;
                    }

                });

                if (error > 0) {
                    clearInterval(interval);
                    console.log('exit with 1');
                    process.exit(1);
                }

                if (finished > 0) {
                    clearInterval(interval);
                    console.log('exit with 0');
                    process.exit(0);
                }

            } else {

                console.log('Line ' + result.body.line + ':' + result.body.message);

                if (result.body.status === 'finished') {
                    clearInterval(interval);
                    console.log('exit with 0');
                    process.exit(0);
                }

                 if (result.body.status === 'error') {
                    clearInterval(interval);
                    console.log('exit with 1');
                    process.exit(1);
                }
            }
        }
    });
};

unirest.get('http://' + ip +':3000/hourly-comscore/start')
.end(function(result) {
    if (result.status === 200) {
        id = result.body.id;
        interval = setInterval(tail, 2000);
    } else {
        console.log('exit with 1');
        process.exit(1);
    }
});

<|endoftext|>


<commit_before>import knexPostgis from 'knex-postgis'

module.exports = bookshelf.Model.extend({
  tableName: 'saved_searches',

  boundingBox: async function() {
    const st = knexPostgis(bookshelf.knex)
    const data = await bookshelf.knex('saved_searches').where({ id: this.id }).select(st.asGeoJSON('bounding_box', 4326))
    const coordinates = JSON.parse(data[0].bounding_box).coordinates[0]
    const boundingBox = [
      {lat: coordinates[0][1], lng: coordinates[0][0]},
      {lat: coordinates[2][1], lng: coordinates[2][0]}
    ]
    return boundingBox
  },

  community: async function () {
    return this.get('context') === 'community' ? await Community.find(this.get('context_id')) : null
  },

  network: async function () {
    return this.get('context') === 'network' ? await Network.find(this.get('context_id')) : null
  },

  topics: async function () {
    const searchId = this.id
    const query = `select t.* from saved_search_topics sst
    left join tags as t on sst.tag_id = t.id
    where sst.saved_search_id = ${searchId}`
    const result = await bookshelf.knex.raw(query)
    return result.rows
  }
}, {
  create: async function (params) {
    const { boundingBox, communitySlug, context, lastPostId, name, networkSlug, postTypes, searchText, topicIds, userId } = params

    let community, network, context_id

    const validContexts = ['all', 'public', 'network', 'community']
    if (!validContexts.includes(context)) throw new Error(`Invalid context: ${context}`)

    if (context === 'community') {
      community = await Community.find(communitySlug)
      context_id = community.id
    }

    if (context === 'network') {
      network = await Network.find(networkSlug)
      context_id = network.id
    }

    const st = knexPostgis(bookshelf.knex)
    const bounding_box = st.geomFromText('POLYGON((' + boundingBox[0].lng + ' ' + boundingBox[0].lat + ', ' + boundingBox[0].lng + ' ' + boundingBox[1].lat + ', ' + boundingBox[1].lng + ' ' + boundingBox[1].lat + ', ' + boundingBox[1].lng + ' ' + boundingBox[0].lat + ', ' + boundingBox[0].lng + ' ' + boundingBox[0].lat +  '))', 4326)

    const attributes = {
      user_id: userId,
      name,
      created_at: new Date(),
      context_id,
      context,
      active: true,
      search_text: searchText,
      post_types: postTypes,
      bounding_box,
      last_post_id: lastPostId,
    }

    const search = await this.forge(attributes).save()

    topicIds.forEach(tag_id => SavedSearchTopic.create({ tag_id, saved_search_id: search.id }))

    return search
  },

  delete: async function(id) {
    await SavedSearch.query().where({ id }).update({ active: false })
    return id
  }
})
<commit_msg>add new posts method to SavedSearch model<commit_after>import knexPostgis from 'knex-postgis'
import { get } from 'lodash'

module.exports = bookshelf.Model.extend({
  tableName: 'saved_searches',

  boundingBox: async function() {
    const st = knexPostgis(bookshelf.knex)
    const data = await bookshelf.knex('saved_searches').where({ id: this.id }).select(st.asGeoJSON('bounding_box', 4326))
    const coordinates = JSON.parse(data[0].bounding_box).coordinates[0]
    const boundingBox = [
      {lat: coordinates[0][1], lng: coordinates[0][0]},
      {lat: coordinates[2][1], lng: coordinates[2][0]}
    ]
    return boundingBox
  },

  community: async function () {
    return this.get('context') === 'community' ? await Community.find(this.get('context_id')) : null
  },

  network: async function () {
    return this.get('context') === 'network' ? await Network.find(this.get('context_id')) : null
  },

  topics: async function () {
    const searchId = this.id
    const query = `select t.* from saved_search_topics sst
    left join tags as t on sst.tag_id = t.id
    where sst.saved_search_id = ${searchId}`
    const result = await bookshelf.knex.raw(query)
    return result.rows
  },

  getPostsInContext: function (userId) {
    const context = this.get('context')
    const lastPostId = this.get('last_post_id')

    let query
    let result

    switch (context) {
      case 'all':
        query = `
          select * from posts p
          left join communities_posts cp on p.id = cp.post_id
          left join communities_users cu on cu.community_id = cp.community_id
          where cu.user_id=${userId}
          and p.id > ${lastPostId}
        `
        break
      case 'public':
        return
      case 'community':
        query = `
          select * from posts p
          left join communities_posts cp on p.id = cp.post_id
          where cp.community_id=${this.get('context_id')}
          and p.id > ${lastPostId}
        `
        break
      case 'network':
        query = `
          select * from posts p
          left join networks_posts np on p.id = np.post_id
          where np.network_id=${this.get('context_id')}
          and p.id > ${lastPostId}
        `
        break
    }

    result = await bookshelf.knex.raw(query)

    return (result.rows || []).reduce((map, p) => {
      map[p.id] = true
      return map
    }, {})
  }
}, {
  create: async function (params) {
    const { boundingBox, communitySlug, context, lastPostId, name, networkSlug, postTypes, searchText, topicIds, userId } = params

    let community, network, context_id

    const validContexts = ['all', 'public', 'network', 'community']
    if (!validContexts.includes(context)) throw new Error(`Invalid context: ${context}`)

    if (context === 'community') {
      community = await Community.find(communitySlug)
      context_id = community.id
    }

    if (context === 'network') {
      network = await Network.find(networkSlug)
      context_id = network.id
    }

    const st = knexPostgis(bookshelf.knex)
    const bounding_box = st.geomFromText('POLYGON((' + boundingBox[0].lng + ' ' + boundingBox[0].lat + ', ' + boundingBox[0].lng + ' ' + boundingBox[1].lat + ', ' + boundingBox[1].lng + ' ' + boundingBox[1].lat + ', ' + boundingBox[1].lng + ' ' + boundingBox[0].lat + ', ' + boundingBox[0].lng + ' ' + boundingBox[0].lat +  '))', 4326)

    const attributes = {
      user_id: userId,
      name,
      created_at: new Date(),
      context_id,
      context,
      active: true,
      search_text: searchText,
      post_types: postTypes,
      bounding_box,
      last_post_id: lastPostId,
    }

    const search = await this.forge(attributes).save()

    topicIds.forEach(tag_id => SavedSearchTopic.create({ tag_id, saved_search_id: search.id }))

    return search
  },

  delete: async function(id) {
    await SavedSearch.query().where({ id }).update({ active: false })
    return id
  },

  newPosts: async function(search_id, user_id) {
    // Query all posts within the bounding box of the saved search that were created after the last_post_id
    const query = `
    with posts_with_locations as (
      select p.id, p.description, p.name, p.type, p.is_public, loc.center as location, array_agg(t.id) as tag_ids from posts p
      left join locations loc on p.location_id = loc.id
      left join posts_tags t on p.id = t.post_id
      where loc.id is not null
      group by p.id, p.description, p.name, p.type, p.is_public, loc.center
    ),
    search as (
      select s.bounding_box, s.last_post_id, CONCAT('%',search_text,'%') as search_text, s.post_types, array_agg(sst.tag_id)::integer[] as tag_ids from saved_searches s
      left join saved_search_topics sst on s.id = sst.saved_search_id
      where s.id=${search_id}
      group by s.id
    )
    select p.id, p.description, p.name, p.type, p.is_public, p.tag_ids from posts_with_locations p
    where ST_Within(p.location, (select bounding_box from search limit 1))=true
    and p.id > (select last_post_id from search)
    and (p.name ilike (select search_text from search) or p.description ilike (select search_text from search))
    and p.tag_ids && (select tag_ids from search)
    and CONCAT('{',p.type,'}')::varchar[] && (select post_types from search)
    order by p.id desc
    `
    const result = await bookshelf.knex.raw(query)
    const posts = result.rows || []
    if (!posts.length) return

    // Get contextual info
    const context = this.get('context')
    const map = this.getPostsInContext(user_id)
    return posts.filter(p => {
      if (context === 'public') return p.is_public === true
      else return map[p.id] === true
    })
  },

  updateLastPost: async function(id, last_post_id) {
    // Maybe move the below to the digest function
    // const lastPostId = get(posts[0], 'id')
    // if (lastPostId) {
    //   await SavedSearch.updateLastPost(search_id, lastPostId)
    //   return posts
    // }
    await SavedSearch.query().where({ id }).update({ last_post_id })
    return id
  }
})
<|endoftext|>