<commit_before>'use strict';

const log = require('util').log;
const path = require('path');
const async = require('async');
const fse = require('fs-extra');
const spawn = require('child_process').spawn;

const config = require('../config.js');
const utils = require('../utils.js');
const ssl = require('./lib/certs.js');
const conf = require('./lib/conf.js');
const sites = require('./lib/sites.js');
const importer = require('./lib/importer.js');

/**
 * Function that runs nginx service and prints logs to stdout
 * @param  {Function} cb Callback Function
 *
 */
function startNginx(cb) {
    const nginx = spawn('service', [ 'nginx', 'start' ], { stdio: 'inherit' });

    nginx.on('data', (data) => {
        console.log(data.toString());
    });

    nginx.on('close', (code) => {
        log(`Nginx process exited with code: ${code}`);
        return cb();
    });
    nginx.on('error', (error) => {
        log(`Nginx process failed with error: ${error}`);
        return cb(error);
    });
}

/**
 * Function that clones UI passed as environment variables only (not sites.json config)
 * @param  {Object}   options Object that contains the type of the UI module and its git information
 * @param  {Function} cb      Callback Function
 *
 */
function getUI(options, cb) {
    let gitInfo = {};
    // if requested UI is dashboard ui, check if valid before cloning it
    if (options.type === 'dashboard') {
        if (!process.env.SOAJS_ENV && process.env.SOAJS_ENV.toLowerCase() !== 'dashboard') return cb();
        if (!process.env.SOAJS_GIT_DASHBOARD_BRANCH || process.env.SOAJS_GIT_DASHBOARD_BRANCH === '') return cb();

        gitInfo = config.dashboard.git;
    }
    else {
        if (!process.env.SOAJS_GIT_OWNER || !process.env.SOAJS_GIT_REPO) {
            log('No or missing git information for custom UI, no custom UI to clone ...');
            return cb();
        }

        gitInfo = {
            provider: process.env.SOAJS_GIT_PROVIDER || 'github',
            domain: process.env.SOAJS_GIT_DOMAIN || 'github.com',
            owner: process.env.SOAJS_GIT_OWNER,
            repo: process.env.SOAJS_GIT_REPO,
            branch: process.env.SOAJS_GIT_BRANCH || 'master',
            path: process.env.SOAJS_GIT_PATH || '/'
        };
    }

    // clone ui
    let cloneOptions = {
        repo: {
            git: {
                provider: gitInfo.provider,
                domain: gitInfo.domain,
                owner: gitInfo.owner,
                repo: gitInfo.repo,
                branch: gitInfo.branch
            }
        },
        clonePath: config.paths.tempFolders.temp.path
    };

    log(`Cloning ${gitInfo.owner}/${gitInfo.repo} ...`);
    utils.clone(cloneOptions, (error) => {
        if (error) throw new Error(error);

        let source = path.join(config.paths.tempFolders.temp.path, gitInfo.path || '/');
        let destination = path.join (config.nginx.siteLocation, '/');
        fse.copy(source, destination, { overwrite: true }, (error) => {
            if (error) {
                log(`Unable to move contents of ${gitInfo.owner}/${gitInfo.repo} to ${destination} ...`);
                throw new Error(error);
            }

            // delete contents of temp before cloning a new repository into it
            fse.remove(config.paths.tempFolders.temp.path, (error) => {
                if (error) throw new Error(error);

                log(`${gitInfo.owner}/${gitInfo.repo} cloned successfully ...`);
                return setTimeout(cb, 100);
            });
        });
    });
}

const exp = {

    deploy(options, cb) {
        ssl.init(options, () => {
            conf.write(options, () => {
                let nxOs = options.nginx.os;

                options.type = 'upstream';
                options.targetDir = options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/conf.d/" : "/nginx/");
                options.isDirectory = true;
                importer.import(options, () => {
                    options.type = 'sites-enabled';
                    options.targetDir = options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/sites-enabled/" : "/nginx/");
                    options.isDirectory = true;
                    importer.import(options, () => {
                        options.type = 'conf';
                        options.targetDir = options.nginx.location;
                        options.isDirectory = false;
                        importer.import(options, () => {
                            // Get dashboard UI if dashboard nginx, check for validity is done in the getUI() function
                            getUI({ type: 'dashboard' }, () => {
                                //Get custom UI module if user specified source as environment variables (this is not related to sites.json config)
                                getUI({ type: 'custom' }, () => {
                                    // Get custom UI sites if any
                                    sites.getSites(options, () => {
                                        // Start nginx
                                        startNginx(cb);
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    }

};

module.exports = exp;
<commit_msg>bug fix<commit_after>'use strict';

const log = require('util').log;
const path = require('path');
const async = require('async');
const fse = require('fs-extra');
const spawn = require('child_process').spawn;

const config = require('../config.js');
const utils = require('../utils.js');
const ssl = require('./lib/certs.js');
const conf = require('./lib/conf.js');
const sites = require('./lib/sites.js');
const importer = require('./lib/importer.js');

/**
 * Function that runs nginx service and prints logs to stdout
 * @param  {Function} cb Callback Function
 *
 */
function startNginx(cb) {
    const nginx = spawn('service', [ 'nginx', 'start' ], { stdio: 'inherit' });

    nginx.on('data', (data) => {
        console.log(data.toString());
    });

    nginx.on('close', (code) => {
        log(`Nginx process exited with code: ${code}`);
        return cb();
    });
    nginx.on('error', (error) => {
        log(`Nginx process failed with error: ${error}`);
        return cb(error);
    });
}

/**
 * Function that clones UI passed as environment variables only (not sites.json config)
 * @param  {Object}   options Object that contains the type of the UI module and its git information
 * @param  {Function} cb      Callback Function
 *
 */
function getUI(options, cb) {
    let gitInfo = {};
    // if requested UI is dashboard ui, check if valid before cloning it
    if (options.type === 'dashboard') {
        if (process.env.SOAJS_ENV && process.env.SOAJS_ENV.toLowerCase() !== 'dashboard') return cb();
        if (!process.env.SOAJS_GIT_DASHBOARD_BRANCH || process.env.SOAJS_GIT_DASHBOARD_BRANCH === '') return cb();

        gitInfo = config.dashboard.git;
    }
    else {
        if (!process.env.SOAJS_GIT_OWNER || !process.env.SOAJS_GIT_REPO) {
            log('No or missing git information for custom UI, no custom UI to clone ...');
            return cb();
        }

        gitInfo = {
            provider: process.env.SOAJS_GIT_PROVIDER || 'github',
            domain: process.env.SOAJS_GIT_DOMAIN || 'github.com',
            owner: process.env.SOAJS_GIT_OWNER,
            repo: process.env.SOAJS_GIT_REPO,
            branch: process.env.SOAJS_GIT_BRANCH || 'master',
            path: process.env.SOAJS_GIT_PATH || '/'
        };
    }

    // clone ui
    let cloneOptions = {
        repo: {
            git: {
                provider: gitInfo.provider,
                domain: gitInfo.domain,
                owner: gitInfo.owner,
                repo: gitInfo.repo,
                branch: gitInfo.branch
            }
        },
        clonePath: config.paths.tempFolders.temp.path
    };

    log(`Cloning ${gitInfo.owner}/${gitInfo.repo} ...`);
    utils.clone(cloneOptions, (error) => {
        if (error) throw new Error(error);

        let source = path.join(config.paths.tempFolders.temp.path, gitInfo.path || '/');
        let destination = path.join (config.nginx.siteLocation, '/');
        fse.copy(source, destination, { overwrite: true }, (error) => {
            if (error) {
                log(`Unable to move contents of ${gitInfo.owner}/${gitInfo.repo} to ${destination} ...`);
                throw new Error(error);
            }

            // delete contents of temp before cloning a new repository into it
            fse.remove(config.paths.tempFolders.temp.path, (error) => {
                if (error) throw new Error(error);

                log(`${gitInfo.owner}/${gitInfo.repo} cloned successfully ...`);
                return setTimeout(cb, 100);
            });
        });
    });
}

const exp = {

    deploy(options, cb) {
        ssl.init(options, () => {
            conf.write(options, () => {
                let nxOs = options.nginx.os;

                options.type = 'upstream';
                options.targetDir = options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/conf.d/" : "/nginx/");
                options.isDirectory = true;
                importer.import(options, () => {
                    options.type = 'sites-enabled';
                    options.targetDir = options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/sites-enabled/" : "/nginx/");
                    options.isDirectory = true;
                    importer.import(options, () => {
                        options.type = 'conf';
                        options.targetDir = options.nginx.location;
                        options.isDirectory = false;
                        importer.import(options, () => {
                            // Get dashboard UI if dashboard nginx, check for validity is done in the getUI() function
                            getUI({ type: 'dashboard' }, () => {
                                //Get custom UI module if user specified source as environment variables (this is not related to sites.json config)
                                getUI({ type: 'custom' }, () => {
                                    // Get custom UI sites if any
                                    sites.getSites(options, () => {
                                        // Start nginx
                                        startNginx(cb);
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    }

};

module.exports = exp;
<|endoftext|>


<commit_before>askaway.controller('AnswerFormCtrl', ['$scope', '$http', function($scope, $http) {
  $scope.addAnswer = function() {
    $http.post(this.question.path + '/answers', {
      answer: {
        body: this.question.answerText
      }
    })
      .success(function(question) {
        $scope.question.answers = question.answers;
        $scope.question.answers_count = question.answers_count;
        $scope.question.can_answer = question.can_answer;
      })
      .error(function(data, status) {
        if (Math.floor(status / 100) === 4) {
          $('#login-modal').modal('show');
        }
      });
  };
}]);
<commit_msg>Only catch 422s for answers.<commit_after>askaway.controller('AnswerFormCtrl', ['$scope', '$http', function($scope, $http) {
  $scope.addAnswer = function() {
    $http.post(this.question.path + '/answers', {
      answer: {
        body: this.question.answerText
      }
    })
      .success(function(question) {
        $scope.question.answers = question.answers;
        $scope.question.answers_count = question.answers_count;
        $scope.question.can_answer = question.can_answer;
      })
      .error(function(data, status) {
        if (status === 422) {
          $scope.question.error_message = data.message;
        }
      });
  };
}]);
<|endoftext|>


<commit_before>/**
 * UpdatesController
 *
 * @description :: Server-side logic for managing Telegram's BOT Updates
 * @author      :: Alejandro González - algope@github
 * @licence     :: The MIT License (MIT)
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 *
 */

var Mixpanel = require('mixpanel');
var mixpanel = Mixpanel.init('2ac0d6d54c481e7dea88d065874c806f');

module.exports = {

    update: function (req, res) {
        var update = req.body;
        var userId = update.message.from.id;
        var userName = update.message.from.first_name;
        var userLast = update.message.from.last_name;
        var userAlias = update.message.from.username;
        if (update.message.text) {
            var text = update.message.text;
            var command = commands.processIt(text);
        } else command = false;

        /**
         * Creates a new entry into Updates table
         */
        Updates.create(req.body, function (ko, ok) {
            if (ko) {
                sails.log.error("[DB] - Updates.create error: ", err);
            }
            if (ok) {
                mixpanel.track("Update", {
                    distinct_id: update.update_id,
                    from: userId,
                    user_id: userAlias,
                    text: update.message.text,
                    photo: update.message.photo
                });
            }
        });

        /**
         * Let's look for a previous user, otherwise we create a new one
         */
        stages.findOrCreateEntry({user_id: userId}, {user_id: userId, stage: 1}).then(
            function (user) {
                mixpanel.people.set(userId, {
                    "$first_name": userName,
                    "$last_name": userLast,
                    "user_name": userAlias,
                    "$created": user.createdAt,
                    "stage": user.stage,
                    "contributions": 0
                });

                /**
                 * STAGE 1 > First stage, no commands executed.
                 */
                if (user.stage == 1) { //Initial stage

                    if (update.message.photo || command.commandId == 0 || !command) {
                        answers.answeringError(userId, update, userAlias, user);
                    } else if (command.commandType == 1) {
                        answers.answeringCommandsS1(command, userId, userName)
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }

                    /**
                     * STAGE 2 > Second stage, command /enviar_info executed
                     */
                } else if (user.stage == 2) { //Command /enviar_info

                    if (update.message.photo || command.commandId == 0 || !command) {
                        answers.answeringError(userId, update, userAlias, user);
                    } else if (command.commandType == 1) {
                        answers.answeringCommandsS2(command, userId, userName);
                    } else if (command.commandType == 3) {
                        answers.answeringTextOrImage(command, userId);
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }

                    /**
                     * STAGE 3 > Third stage, the user had selected datatype
                     */
                } else if (user.stage == 3) { //Data type selected

                    if (command && command.commandType == 1) {
                        answers.answeringCommandsS3(command, userId, userName);
                    } else if (update.message.photo && user.data_type_selected == 2) {
                        answers.answeringLabelingS3(1, update, userId);
                    } else if (update.message.text && user.data_type_selected == 1) {
                        answers.answeringLabelingS3(2, update, userId);
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }

                    /**
                     * STAGE 4 > Fourth stage, the bot had recieved the media
                     */
                } else if (user.stage == 4) { //Data recieved, not labeled

                    sails.log.debug("commandID: ", command.commandId);
                    if (update.message.photo || command.commandId == 0 || !command) {
                        answers.answeringError(userId, update, userAlias, user);
                    } else if (command.commandType == 1) {
                        answers.answeringCommandsS4(command, userId, userName);
                    } else if (command.commandType == 2) {
                        answers.answeringThanksS4(userId, command, update);
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }

                    /**
                     * STAGE 10 > Tenth stage (no regular), FeedBack Stage
                     */
                } else if (user.stage == 10) { //FeedBack

                    if (update.message.photo || command.commandId == 0) {
                        answers.answeringError(userId, update, userAlias, user);
                    } else if (command && command.commandType == 1) {
                        answers.answeringCommandsS10(command, userId ,userName);
                    } else if (update.message.text) {
                        answers.answeringThanksS10(userId, update, userAlias);
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }
                }
            }
        );
        res.ok();
    }
};

<commit_msg>Test-Mongo<commit_after>/**
 * UpdatesController
 *
 * @description :: Server-side logic for managing Telegram's BOT Updates
 * @author      :: Alejandro González - algope@github
 * @licence     :: The MIT License (MIT)
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 *
 */

var Mixpanel = require('mixpanel');
var mixpanel = Mixpanel.init('2ac0d6d54c481e7dea88d065874c806f');

module.exports = {

    update: function (req, res) {
        var update = req.body;
        var userId = update.message.from.id;
        var userName = update.message.from.first_name;
        var userLast = update.message.from.last_name;
        var userAlias = update.message.from.username;
        if (update.message.text) {
            var text = update.message.text;
            var command = commands.processIt(text);
        } else command = false;

        /**
         * Creates a new entry into Updates table
         */

        sails.log.debug("UPDATE: : : : : "+update);
        Updates.create(req.body, function (ko, ok) {
            if (ko) {
                sails.log.error("[DB] - Updates.create error: ", err);
            }
            if (ok) {
                mixpanel.track("Update", {
                    distinct_id: update.update_id,
                    from: userId,
                    user_id: userAlias,
                    text: update.message.text,
                    photo: update.message.photo
                });
            }
        });

        /**
         * Let's look for a previous user, otherwise we create a new one
         */
        stages.findOrCreateEntry({user_id: userId}, {user_id: userId, stage: 1}).then(
            function (user) {
                mixpanel.people.set(userId, {
                    "$first_name": userName,
                    "$last_name": userLast,
                    "user_name": userAlias,
                    "$created": user.createdAt,
                    "stage": user.stage,
                    "contributions": 0
                });

                /**
                 * STAGE 1 > First stage, no commands executed.
                 */
                if (user.stage == 1) { //Initial stage

                    if (update.message.photo || command.commandId == 0 || !command) {
                        answers.answeringError(userId, update, userAlias, user);
                    } else if (command.commandType == 1) {
                        answers.answeringCommandsS1(command, userId, userName)
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }

                    /**
                     * STAGE 2 > Second stage, command /enviar_info executed
                     */
                } else if (user.stage == 2) { //Command /enviar_info

                    if (update.message.photo || command.commandId == 0 || !command) {
                        answers.answeringError(userId, update, userAlias, user);
                    } else if (command.commandType == 1) {
                        answers.answeringCommandsS2(command, userId, userName);
                    } else if (command.commandType == 3) {
                        answers.answeringTextOrImage(command, userId);
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }

                    /**
                     * STAGE 3 > Third stage, the user had selected datatype
                     */
                } else if (user.stage == 3) { //Data type selected

                    if (command && command.commandType == 1) {
                        answers.answeringCommandsS3(command, userId, userName);
                    } else if (update.message.photo && user.data_type_selected == 2) {
                        answers.answeringLabelingS3(1, update, userId);
                    } else if (update.message.text && user.data_type_selected == 1) {
                        answers.answeringLabelingS3(2, update, userId);
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }

                    /**
                     * STAGE 4 > Fourth stage, the bot had recieved the media
                     */
                } else if (user.stage == 4) { //Data recieved, not labeled

                    sails.log.debug("commandID: ", command.commandId);
                    if (update.message.photo || command.commandId == 0 || !command) {
                        answers.answeringError(userId, update, userAlias, user);
                    } else if (command.commandType == 1) {
                        answers.answeringCommandsS4(command, userId, userName);
                    } else if (command.commandType == 2) {
                        answers.answeringThanksS4(userId, command, update);
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }

                    /**
                     * STAGE 10 > Tenth stage (no regular), FeedBack Stage
                     */
                } else if (user.stage == 10) { //FeedBack

                    if (update.message.photo || command.commandId == 0) {
                        answers.answeringError(userId, update, userAlias, user);
                    } else if (command && command.commandType == 1) {
                        answers.answeringCommandsS10(command, userId ,userName);
                    } else if (update.message.text) {
                        answers.answeringThanksS10(userId, update, userAlias);
                    } else {
                        answers.answeringError(userId, update, userAlias, user);
                    }
                }
            }
        );
        res.ok();
    }
};

<|endoftext|>


<commit_before>// ==UserScript==
// @name        UserScript-Webhallen-filter
// @namespace   webhallen-filter
// @description Simple Webhallen filter
// @version     1.0.0
// @include     *
// ==/UserScript==

!function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var n={};e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=5)}([function(t,e,n){var r=n(1);"string"==typeof r&&(r=[[t.i,r,""]]);var o={};o.transform=void 0;n(3)(r,o);r.locals&&(t.exports=r.locals)},function(t,e,n){e=t.exports=n(2)(void 0),e.push([t.i,"/* Add custom CSS rules to be injected into pages here. */",""])},function(t,e){function n(t,e){var n=t[1]||"",o=t[3];if(!o)return n;if(e&&"function"==typeof btoa){var i=r(o);return[n].concat(o.sources.map(function(t){return"/*# sourceURL="+o.sourceRoot+t+" */"})).concat([i]).join("\n")}return[n].join("\n")}function r(t){return"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(t))))+" */"}t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var r=n(e,t);return e[2]?"@media "+e[2]+"{"+r+"}":r}).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},o=0;o<this.length;o++){var i=this[o][0];"number"==typeof i&&(r[i]=!0)}for(o=0;o<t.length;o++){var s=t[o];"number"==typeof s[0]&&r[s[0]]||(n&&!s[2]?s[2]=n:n&&(s[2]="("+s[2]+") and ("+n+")"),e.push(s))}},e}},function(t,e,n){function r(t,e){for(var n=0;n<t.length;n++){var r=t[n],o=v[r.id];if(o){o.refs++;for(var i=0;i<o.parts.length;i++)o.parts[i](r.parts[i]);for(;i<r.parts.length;i++)o.parts.push(f(r.parts[i],e))}else{for(var s=[],i=0;i<r.parts.length;i++)s.push(f(r.parts[i],e));v[r.id]={id:r.id,refs:1,parts:s}}}}function o(t,e){for(var n=[],r={},o=0;o<t.length;o++){var i=t[o],s=e.base?i[0]+e.base:i[0],a=i[1],u=i[2],c=i[3],f={css:a,media:u,sourceMap:c};r[s]?r[s].parts.push(f):n.push(r[s]={id:s,parts:[f]})}return n}function i(t,e){var n=b(t.insertInto);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");var r=g[g.length-1];if("top"===t.insertAt)r?r.nextSibling?n.insertBefore(e,r.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),g.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function s(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t);var e=g.indexOf(t);e>=0&&g.splice(e,1)}function a(t){var e=document.createElement("style");return t.attrs.type="text/css",c(e,t.attrs),i(t,e),e}function u(t){var e=document.createElement("link");return t.attrs.type="text/css",t.attrs.rel="stylesheet",c(e,t.attrs),i(t,e),e}function c(t,e){Object.keys(e).forEach(function(n){t.setAttribute(n,e[n])})}function f(t,e){var n,r,o,i;if(e.transform&&t.css){if(!(i=e.transform(t.css)))return function(){};t.css=i}if(e.singleton){var c=y++;n=m||(m=a(e)),r=l.bind(null,n,c,!1),o=l.bind(null,n,c,!0)}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=u(e),r=d.bind(null,n,e),o=function(){s(n),n.href&&URL.revokeObjectURL(n.href)}):(n=a(e),r=p.bind(null,n),o=function(){s(n)});return r(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;r(t=e)}else o()}}function l(t,e,n,r){var o=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=w(e,o);else{var i=document.createTextNode(o),s=t.childNodes;s[e]&&t.removeChild(s[e]),s.length?t.insertBefore(i,s[e]):t.appendChild(i)}}function p(t,e){var n=e.css,r=e.media;if(r&&t.setAttribute("media",r),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}function d(t,e,n){var r=n.css,o=n.sourceMap,i=void 0===e.convertToAbsoluteUrls&&o;(e.convertToAbsoluteUrls||i)&&(r=x(r)),o&&(r+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */");var s=new Blob([r],{type:"text/css"}),a=t.href;t.href=URL.createObjectURL(s),a&&URL.revokeObjectURL(a)}var v={},h=function(t){var e;return function(){return void 0===e&&(e=t.apply(this,arguments)),e}}(function(){return window&&document&&document.all&&!window.atob}),b=function(t){var e={};return function(n){return void 0===e[n]&&(e[n]=t.call(this,n)),e[n]}}(function(t){return document.querySelector(t)}),m=null,y=0,g=[],x=n(4);t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");e=e||{},e.attrs="object"==typeof e.attrs?e.attrs:{},e.singleton||(e.singleton=h()),e.insertInto||(e.insertInto="head"),e.insertAt||(e.insertAt="bottom");var n=o(t,e);return r(n,e),function(t){for(var i=[],s=0;s<n.length;s++){var a=n[s],u=v[a.id];u.refs--,i.push(u)}if(t){r(o(t,e),e)}for(var s=0;s<i.length;s++){var u=i[s];if(0===u.refs){for(var c=0;c<u.parts.length;c++)u.parts[c]();delete v[u.id]}}}};var w=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e){t.exports=function(t){var e="undefined"!=typeof window&&window.location;if(!e)throw new Error("fixUrls requires window.location");if(!t||"string"!=typeof t)return t;var n=e.protocol+"//"+e.host,r=n+e.pathname.replace(/\/[^\/]*$/,"/");return t.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,function(t,e){var o=e.trim().replace(/^"(.*)"$/,function(t,e){return e}).replace(/^'(.*)'$/,function(t,e){return e});if(/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(o))return t;var i;return i=0===o.indexOf("//")?o:0===o.indexOf("/")?n+o:r+o.replace(/^\.\//,""),"url("+JSON.stringify(i)+")"})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),n(0);console.log("Hello world!")}]);<commit_msg>Added working filter script<commit_after>// ==UserScript==
// @name        UserScript-Webhallen-filter
// @namespace   webhallen-filter
// @description Simple Webhallen filter
// @version     1.0.0
// @include     https://www.webhallen.com/se-sv/medlem/*/erbjudanden
// @include     https://www.webhallen.com/medlem/*/erbjudanden/mest_salda/alla/*
// ==/UserScript==

!function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var n={};e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=5)}([function(t,e,n){var r=n(1);"string"==typeof r&&(r=[[t.i,r,""]]);var o={};o.transform=void 0;n(3)(r,o);r.locals&&(t.exports=r.locals)},function(t,e,n){e=t.exports=n(2)(void 0),e.push([t.i,"/* Add custom CSS rules to be injected into pages here. */",""])},function(t,e){function n(t,e){var n=t[1]||"",o=t[3];if(!o)return n;if(e&&"function"==typeof btoa){var i=r(o);return[n].concat(o.sources.map(function(t){return"/*# sourceURL="+o.sourceRoot+t+" */"})).concat([i]).join("\n")}return[n].join("\n")}function r(t){return"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(t))))+" */"}t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var r=n(e,t);return e[2]?"@media "+e[2]+"{"+r+"}":r}).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},o=0;o<this.length;o++){var i=this[o][0];"number"==typeof i&&(r[i]=!0)}for(o=0;o<t.length;o++){var s=t[o];"number"==typeof s[0]&&r[s[0]]||(n&&!s[2]?s[2]=n:n&&(s[2]="("+s[2]+") and ("+n+")"),e.push(s))}},e}},function(t,e,n){function r(t,e){for(var n=0;n<t.length;n++){var r=t[n],o=v[r.id];if(o){o.refs++;for(var i=0;i<o.parts.length;i++)o.parts[i](r.parts[i]);for(;i<r.parts.length;i++)o.parts.push(f(r.parts[i],e))}else{for(var s=[],i=0;i<r.parts.length;i++)s.push(f(r.parts[i],e));v[r.id]={id:r.id,refs:1,parts:s}}}}function o(t,e){for(var n=[],r={},o=0;o<t.length;o++){var i=t[o],s=e.base?i[0]+e.base:i[0],a=i[1],u=i[2],c=i[3],f={css:a,media:u,sourceMap:c};r[s]?r[s].parts.push(f):n.push(r[s]={id:s,parts:[f]})}return n}function i(t,e){var n=m(t.insertInto);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");var r=g[g.length-1];if("top"===t.insertAt)r?r.nextSibling?n.insertBefore(e,r.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),g.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function s(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t);var e=g.indexOf(t);e>=0&&g.splice(e,1)}function a(t){var e=document.createElement("style");return t.attrs.type="text/css",c(e,t.attrs),i(t,e),e}function u(t){var e=document.createElement("link");return t.attrs.type="text/css",t.attrs.rel="stylesheet",c(e,t.attrs),i(t,e),e}function c(t,e){Object.keys(e).forEach(function(n){t.setAttribute(n,e[n])})}function f(t,e){var n,r,o,i;if(e.transform&&t.css){if(!(i=e.transform(t.css)))return function(){};t.css=i}if(e.singleton){var c=y++;n=b||(b=a(e)),r=l.bind(null,n,c,!1),o=l.bind(null,n,c,!0)}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=u(e),r=d.bind(null,n,e),o=function(){s(n),n.href&&URL.revokeObjectURL(n.href)}):(n=a(e),r=p.bind(null,n),o=function(){s(n)});return r(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;r(t=e)}else o()}}function l(t,e,n,r){var o=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=x(e,o);else{var i=document.createTextNode(o),s=t.childNodes;s[e]&&t.removeChild(s[e]),s.length?t.insertBefore(i,s[e]):t.appendChild(i)}}function p(t,e){var n=e.css,r=e.media;if(r&&t.setAttribute("media",r),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}function d(t,e,n){var r=n.css,o=n.sourceMap,i=void 0===e.convertToAbsoluteUrls&&o;(e.convertToAbsoluteUrls||i)&&(r=w(r)),o&&(r+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */");var s=new Blob([r],{type:"text/css"}),a=t.href;t.href=URL.createObjectURL(s),a&&URL.revokeObjectURL(a)}var v={},h=function(t){var e;return function(){return void 0===e&&(e=t.apply(this,arguments)),e}}(function(){return window&&document&&document.all&&!window.atob}),m=function(t){var e={};return function(n){return void 0===e[n]&&(e[n]=t.call(this,n)),e[n]}}(function(t){return document.querySelector(t)}),b=null,y=0,g=[],w=n(4);t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");e=e||{},e.attrs="object"==typeof e.attrs?e.attrs:{},e.singleton||(e.singleton=h()),e.insertInto||(e.insertInto="head"),e.insertAt||(e.insertAt="bottom");var n=o(t,e);return r(n,e),function(t){for(var i=[],s=0;s<n.length;s++){var a=n[s],u=v[a.id];u.refs--,i.push(u)}if(t){r(o(t,e),e)}for(var s=0;s<i.length;s++){var u=i[s];if(0===u.refs){for(var c=0;c<u.parts.length;c++)u.parts[c]();delete v[u.id]}}}};var x=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e){t.exports=function(t){var e="undefined"!=typeof window&&window.location;if(!e)throw new Error("fixUrls requires window.location");if(!t||"string"!=typeof t)return t;var n=e.protocol+"//"+e.host,r=n+e.pathname.replace(/\/[^\/]*$/,"/");return t.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,function(t,e){var o=e.trim().replace(/^"(.*)"$/,function(t,e){return e}).replace(/^'(.*)'$/,function(t,e){return e});if(/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(o))return t;var i;return i=0===o.indexOf("//")?o:0===o.indexOf("/")?n+o:r+o.replace(/^\.\//,""),"url("+JSON.stringify(i)+")"})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),n(0);var r=function(){function t(){}return t.prototype.run=function(){var t=this;this.getLinksByTexts("global").forEach(function(e){var n=t.closestParentByClass(".prod_list_row",e);null!=n&&n.parentElement.removeChild(n)})},t.prototype.getLinksByTexts=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];for(var n=[],r=document.querySelectorAll(".prod_list_row a"),o=0;o<r.length;o++)!function(){var e=r[o],i=e.innerText.toLowerCase();t.some(function(t){return-1!==i.indexOf(t.toLowerCase())})&&n.push(e)}();return n},t.prototype.closestParentByClass=function(t,e){for(var n=e.parentElement;null!=n;){if(n.matches(t))return n;n=n.parentElement}return null},t}();e.FilterScript=r;var o=new r;window.addEventListener("load",function(){return o.run()},!1)}]);<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
<commit_msg>removing unnecessary file<commit_after><|endoftext|>


<commit_before>/**
 * Module dependencies
 */
var _ = require('lodash');

/**
 * Interpret and validate command-line arguments.
 * Then take the appropriate action.
 *
 * Calls one of:
 *		- handler.sails
 *		- handler.console
 *		- handler.lift
 *		- handler.generate
 *		- handler.new
 *		- handler.run
 *		- handler.version
 */

module.exports = function interpretArguments ( argv, handlers ) {

	if ( !_.isObject(argv) ) return handlers.invalid();
	if ( !_.isArray(argv._) ) return handlers.invalid();
	if ( !argv._.length ) return handlers.sails();

	var first	= argv._[0] || '',
		second	= argv._[1] || '',
		third	= argv._[2] || '',
		fourth	= argv._[3] || '',
		fifth	= argv._[4] || '',
		all		= _.map(argv._, function (arg) {return arg + '';});

	var isLift		= _.contains(['lift', 'raise', 'start', 'server', 's', 'l'], first),
		isConsole	= _.contains(['console'], first),
		isGenerate	= _.contains(['generate'], first),
		isNew		= _.contains(['new'], first),
		isVersion	= _.contains(['version'], first),
		isWWW		= _.contains(['www', 'build'], first),
		isRun		= _.contains(['run','issue'], first);

	// Interpret/validate arguments to `sails generate`
	if ( isGenerate ) {

		// Second argument is the type of module to generate
		var module = second;

		// Third argument is the id of the module we're creating
		var id = third;

		// If the module or id is invalid, or doesn't exist,
		// we have a usage error on our hands.
		if ( !module ) {
			return handlers.invalid(
				'What type of module would you like to generate?'
			);
		}

		var knownGenerators = [
			'controller',
			'model',
			'view',
			'api',
			'adapter',
			'policy'
		];

		// Check for unknown generators
		// (this will be removed eventually)
		if ( !_.contains(knownGenerators, module) ) {
			return handlers.error(
				'Sorry, I don\'t have a "' + second + '" generator.  ' +
				'Did you mean: `sails generate api '+second+'`?'
			);
		}

		// Check for todo/not-yet-supported generators
		switch ( module ) {
			case 'view':
			case 'policy':
			case 'adapter':
				return handlers.error(
				'Sorry, `sails generate ' + second + '` ' +
				'is currently out of commission.');
		}

		// If no id argument exists, this is a usage error
		// TODO: support `sails generate` again
		// 		 (for creating a model AND controller at the same time)
		if ( !id ) {
			return handlers.invalid(
				'Please specify the name for the new ' + module + '.'
			);
		}
		if ( !id.match(/^[a-z]([a-z]|[0-9])*$/i) ) {
			return handlers.invalid(
				'Sorry, "' + id + '" is not a valid name for a ' + module + '.',
				'Only letters and numbers are allowed, and it must start with a letter.',
				'(Sails ' + module + 's are case-insensitive.)'
			);
		}

		// Allow cli user to specify `FooController` and really mean `foo`
		if (module === 'controller') {
			id = id.replace(/Controller$/, '');
		}

		// Figure out whether subsequent cmdline args are
		// supposed to be controller actions or model attributes.
		var arrayOfArgs = argv._.splice(3);
		var argsLookLikeAttributes = ( arrayOfArgs[0] && arrayOfArgs[0].match(/:/) );

		// If module === 'model', args ALWAYS "lookLikeAttributes"
		if ( module==='model' ) { argsLookLikeAttributes = true; }

		var actions = argsLookLikeAttributes ? [] : arrayOfArgs;
		var attributes = argsLookLikeAttributes ? arrayOfArgs : [];

		// Build options
		var options = _.extend({}, argv, {
			id: id,
			module: second,
			actions:  actions,
			attributes: attributes
		});

		handlers.generate(options);
		return;
	}

	/**
	 * `sails new <APPNAME>`
	 *
	 * Asset auto-"linker" is enabled by default
	 */
	if ( isNew ) {

		var linkerExplicitlyDisabled = (argv['linker'] === false) || (argv['linker'] === 'false');

		handlers['new']({
			appName: second,
			assetLinker: {
				enabled: linkerExplicitlyDisabled ? false : true,
				src: argv['linker-src'] || 'assets/linker/**/*'
			},
			dry : argv.dry
		});
		return;
	}

	if ( isLift )		return handlers.lift();
	if ( isConsole )	return handlers.console();
	if ( isVersion )	return handlers.version();
	if ( isRun )		return handlers.run();
	if ( isWWW )		return handlers.www();

	// Unknown action
	return handlers.invalid( { first: first } );
};
<commit_msg>allow 'sails c' as an alias to 'sails console'<commit_after>/**
 * Module dependencies
 */
var _ = require('lodash');

/**
 * Interpret and validate command-line arguments.
 * Then take the appropriate action.
 *
 * Calls one of:
 *		- handler.sails
 *		- handler.console
 *		- handler.lift
 *		- handler.generate
 *		- handler.new
 *		- handler.run
 *		- handler.version
 */

module.exports = function interpretArguments ( argv, handlers ) {

	if ( !_.isObject(argv) ) return handlers.invalid();
	if ( !_.isArray(argv._) ) return handlers.invalid();
	if ( !argv._.length ) return handlers.sails();

	var first	= argv._[0] || '',
		second	= argv._[1] || '',
		third	= argv._[2] || '',
		fourth	= argv._[3] || '',
		fifth	= argv._[4] || '',
		all		= _.map(argv._, function (arg) {return arg + '';});

	var isLift		= _.contains(['lift', 'raise', 'start', 'server', 's', 'l'], first),
		isConsole	= _.contains(['console', 'c'], first),
		isGenerate	= _.contains(['generate'], first),
		isNew		= _.contains(['new'], first),
		isVersion	= _.contains(['version'], first),
		isWWW		= _.contains(['www', 'build'], first),
		isRun		= _.contains(['run','issue'], first);

	// Interpret/validate arguments to `sails generate`
	if ( isGenerate ) {

		// Second argument is the type of module to generate
		var module = second;

		// Third argument is the id of the module we're creating
		var id = third;

		// If the module or id is invalid, or doesn't exist,
		// we have a usage error on our hands.
		if ( !module ) {
			return handlers.invalid(
				'What type of module would you like to generate?'
			);
		}

		var knownGenerators = [
			'controller',
			'model',
			'view',
			'api',
			'adapter',
			'policy'
		];

		// Check for unknown generators
		// (this will be removed eventually)
		if ( !_.contains(knownGenerators, module) ) {
			return handlers.error(
				'Sorry, I don\'t have a "' + second + '" generator.  ' +
				'Did you mean: `sails generate api '+second+'`?'
			);
		}

		// Check for todo/not-yet-supported generators
		switch ( module ) {
			case 'view':
			case 'policy':
			case 'adapter':
				return handlers.error(
				'Sorry, `sails generate ' + second + '` ' +
				'is currently out of commission.');
		}

		// If no id argument exists, this is a usage error
		// TODO: support `sails generate` again
		// 		 (for creating a model AND controller at the same time)
		if ( !id ) {
			return handlers.invalid(
				'Please specify the name for the new ' + module + '.'
			);
		}
		if ( !id.match(/^[a-z]([a-z]|[0-9])*$/i) ) {
			return handlers.invalid(
				'Sorry, "' + id + '" is not a valid name for a ' + module + '.',
				'Only letters and numbers are allowed, and it must start with a letter.',
				'(Sails ' + module + 's are case-insensitive.)'
			);
		}

		// Allow cli user to specify `FooController` and really mean `foo`
		if (module === 'controller') {
			id = id.replace(/Controller$/, '');
		}

		// Figure out whether subsequent cmdline args are
		// supposed to be controller actions or model attributes.
		var arrayOfArgs = argv._.splice(3);
		var argsLookLikeAttributes = ( arrayOfArgs[0] && arrayOfArgs[0].match(/:/) );

		// If module === 'model', args ALWAYS "lookLikeAttributes"
		if ( module==='model' ) { argsLookLikeAttributes = true; }

		var actions = argsLookLikeAttributes ? [] : arrayOfArgs;
		var attributes = argsLookLikeAttributes ? arrayOfArgs : [];

		// Build options
		var options = _.extend({}, argv, {
			id: id,
			module: second,
			actions:  actions,
			attributes: attributes
		});

		handlers.generate(options);
		return;
	}

	/**
	 * `sails new <APPNAME>`
	 *
	 * Asset auto-"linker" is enabled by default
	 */
	if ( isNew ) {

		var linkerExplicitlyDisabled = (argv['linker'] === false) || (argv['linker'] === 'false');

		handlers['new']({
			appName: second,
			assetLinker: {
				enabled: linkerExplicitlyDisabled ? false : true,
				src: argv['linker-src'] || 'assets/linker/**/*'
			},
			dry : argv.dry
		});
		return;
	}

	if ( isLift )		return handlers.lift();
	if ( isConsole )	return handlers.console();
	if ( isVersion )	return handlers.version();
	if ( isRun )		return handlers.run();
	if ( isWWW )		return handlers.www();

	// Unknown action
	return handlers.invalid( { first: first } );
};
<|endoftext|>


<commit_before>/**
 * UpdatesController
 *
 * @description :: Server-side logic for managing Updates
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {

    update: function (req, res) {
        var update = req.body;
        var userId = update.message.from.id;
        var userName = update.message.from.first_name;
        if (update.message.text) {
            var text = update.message.text;

            sails.log.debug("Message: ", update.message.text);
            var command = commands.processIt(text);
            sails.log.debug("Command: ", command);

            if (command) {
                telegram.sendMessage(userId, "Comando procesado correctamente, commandID: " + command).then(
                    function (response) {

                    }, function (error) {
                        sails.log.error("Failed", error);
                    }
                );
            }

        } else if (update.message.photo) {
            sails.log.info("Photo content: ", update.message.photo);
            telegram.sendMessage(userId, "Ahora clasifica la foto...", "", true, null, null).then(
                function (response) {
                    sails.log.debug("Message Sent", response);
                }, function (error) {
                    sails.log.error("Failed", error);
                }
            ).then(
                telegram.sendMessage(userId, "Si la información está relacionada con:\n"+
                    "Reducción de las desigualdades y la exclusión social, pulsa A\n"+
                    "Transparencia, participación ciudadanía o rendición de cuentas, pulsa B\n"+
                    "Acceso y permanencia en el sistema educativo o con el Tercer Sector, pulsa C\n"+
                    "Campañas de comunicación institucionales o con medios de comunicación, pulsa D\n","", true, null, keyboards.createKeyboard()).then(
                    function (response) {
                        sails.log.debug("Message Sent", response);
                    }, function (error) {
                        sails.log.error("Failed", error);
                    }
                )
            );
        } else {
            telegram.sendMessage(userId, "Ups, eso no me lo esperaba... ¿Te has equivocado?").then(
                function (response) {

                }, function (error) {
                    sails.log.error("Failed", error);
                }
            );
        }
        res.json(200);

        /*
         Updates.create(req.body).exec(function(err, message){
         if (err) {
         sails.log.error("Web Hook --> Error", err)
         }
         if (message) {
         sails.log("OK");
         }
         })
         */
    }
};

<commit_msg>Fixes<commit_after>/**
 * UpdatesController
 *
 * @description :: Server-side logic for managing Updates
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {

    update: function (req, res) {
        var update = req.body;
        var userId = update.message.from.id;
        var userName = update.message.from.first_name;
        if (update.message.text) {
            var text = update.message.text;

            sails.log.debug("Message: ", update.message.text);
            var command = commands.processIt(text);
            sails.log.debug("Command: ", command);

            if (command) {
                telegram.sendMessage(userId, "Comando procesado correctamente, commandID: " + command).then(
                    function (response) {

                    }, function (error) {
                        sails.log.error("Failed", error);
                    }
                );
            }

        } else if (update.message.photo) {
            sails.log.info("Photo content: ", update.message.photo);
            telegram.sendMessage(userId, "Ahora clasifica la foto...\n"+
                "Si la información está relacionada con:\n"+
                "Reducción de las desigualdades y la exclusión social, pulsa A\n"+
                "Transparencia, participación ciudadanía o rendición de cuentas, pulsa B\n"+
                "Acceso y permanencia en el sistema educativo o con el Tercer Sector, pulsa C\n"+
                "Campañas de comunicación institucionales o con medios de comunicación, pulsa D\n", "", true, null, null).then(
                function (response) {
                    sails.log.debug("Message Sent", response);
                }, function (error) {
                    sails.log.error("Failed", error);
                }
            );
        } else {
            telegram.sendMessage(userId, "Ups, eso no me lo esperaba... ¿Te has equivocado?").then(
                function (response) {

                }, function (error) {
                    sails.log.error("Failed", error);
                }
            );
        }
        res.json(200);

        /*
         Updates.create(req.body).exec(function(err, message){
         if (err) {
         sails.log.error("Web Hook --> Error", err)
         }
         if (message) {
         sails.log("OK");
         }
         })
         */
    }
};

<|endoftext|>


<commit_before>import Default from './autocomplete/default'
import Work from './autocomplete/work'
import LinkedData from './autocomplete/linked_data'

export default class Autocomplete {
  /**
   * Setup for the autocomplete field.
   * @param {jQuery} element - The input field to add autocompete to
   # @param {string} fieldName - The name of the field (e.g. 'based_near')
   # @param {string} url - The url for the autocompete search endpoint
   */
  setup (element, fieldName, url) {
    console.log(`setting up ${fieldName}`)
    switch (fieldName) {
      case 'work':
        new Work(
          element,
          url,
          element.data('id')
        )
        break
      case 'based_near':
        new LinkedData(element, url)
      default:
        new Default(element, url)
        break
    }
  }
}
<commit_msg>Remove unnecessary logging<commit_after>import Default from './autocomplete/default'
import Work from './autocomplete/work'
import LinkedData from './autocomplete/linked_data'

export default class Autocomplete {
  /**
   * Setup for the autocomplete field.
   * @param {jQuery} element - The input field to add autocompete to
   # @param {string} fieldName - The name of the field (e.g. 'based_near')
   # @param {string} url - The url for the autocompete search endpoint
   */
  setup (element, fieldName, url) {
    switch (fieldName) {
      case 'work':
        new Work(
          element,
          url,
          element.data('id')
        )
        break
      case 'based_near':
        new LinkedData(element, url)
      default:
        new Default(element, url)
        break
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var self = deleteById;
module.exports = self;

var async = require('async');
var _ = require('underscore');
var envHandler = require('../../common/envHandler.js');
var VaultAdapter = require('../../common/VaultAdapter.js');

function deleteById(req, res) {
  var bag = {
    inputParams: req.params,
    resBody: {},
    vaultTokenEnv: 'VAULT_TOKEN'
  };

  bag.who = util.format('systemIntegrations|%s| ' +
    'systemIntegrationId:%s', self.name,
    bag.inputParams.systemIntegrationId);
  logger.info(bag.who, 'Starting');

  async.series([
      _checkInputParams.bind(null, bag),
      _getVaultURL.bind(null, bag),
      _getVaultToken.bind(null, bag),
      _deleteById.bind(null, bag),
      _deleteByIdInVault.bind(null, bag)
    ],
    function (err) {
      logger.info(bag.who, 'Completed');
      if (err)
        return respondWithError(res, err);
      sendJSONResponse(res, bag.resBody);
    }
  );
}

function _checkInputParams(bag, next) {
  var who = bag.who + '|' + _checkInputParams.name;
  logger.verbose(who, 'Inside');

  if (!bag.inputParams.systemIntegrationId)
    return next(
      new ActErr(who, ActErr.ParamNotFound,
        'Route parameter not found :systemIntegrationId')
    );
  bag.systemIntegrationId = bag.inputParams.systemIntegrationId;
  return next();
}

function _getVaultURL(bag, next) {
  var who = bag.who + '|' + _getVaultURL.name;
  logger.verbose(who, 'Inside');

  var query = 'SELECT "vaultUrl", secrets from "systemConfigs"';
  global.config.client.query(query,
    function (err, systemConfigs) {
      if (err)
        return next(
          new ActErr(who, ActErr.DBOperationFailed, err)
        );

      if (!_.isEmpty(systemConfigs.rows) &&
        !_.isEmpty(systemConfigs.rows[0].vaultUrl)) {
        logger.debug('Found vault URL');

        bag.vaultUrl = systemConfigs.rows[0].vaultUrl;

        if (bag.vaultUrl.indexOf('http') !== 0)
          bag.vaultUrl = 'http://' + bag.vaultUrl;

        if (systemConfigs.rows[0].secrets) {
          var secretsConfig = JSON.parse(systemConfigs.rows[0].secrets);
          bag.vaultUrl = bag.vaultUrl + ':' + secretsConfig.port;
        }
        return next();
      }

      return next(
        new ActErr(who, ActErr.DataNotFound,
          'No vault URL found in configs')
      );
    }
  );
}

function _getVaultToken(bag, next) {
  var who = bag.who + '|' + _getVaultURL.name;
  logger.verbose(who, 'Inside');

  envHandler.get(bag.vaultTokenEnv,
    function (err, value) {
      if (err)
        return next(
          new ActErr(who, ActErr.OperationFailed,
            'Cannot get env: ' + bag.vaultTokenEnv)
        );

      if (_.isEmpty(value)) {
        return next(
          new ActErr(who, ActErr.DataNotFound,
            'No vault token found')
        );
      }

      logger.debug('Found vault token');
      bag.vaultToken = value;
      return next();
    }
  );
}

function _deleteById(bag, next) {
  var who = bag.who + '|' + _deleteById.name;
  logger.verbose(who, 'Inside');

  var query =
    util.format('DELETE from "systemIntegrations" where id=\'%s\';',
      bag.systemIntegrationId);

  global.config.client.query(query,
    function (err) {
      if (err)
        return next(
          new ActErr(who, mapSequelizeErr(err),
            'systemIntegrations.delete failed for id: ' +
            bag.systemIntegrationId + ' returned error: ' + err.message)
        );

      return next();
    }
  );
}

function _deleteByIdInVault(bag, next) {
  var who = bag.who + '|' + _deleteByIdInVault.name;
  logger.verbose(who, 'Inside');

  var vaultUrl = bag.vaultUrl;
  var shippableVaultToken = bag.vaultToken;
  var vaultAdapter = new VaultAdapter(vaultUrl, shippableVaultToken);

  var key = util.format('shippable/systemIntegrations/%s',
    bag.inputParams.systemIntegrationId);
  vaultAdapter.deleteSecret (key,
    function(err, body) {
      if (err)
        return next(
          new ActErr(who, ActErr.OperationFailed,
            'Failed to :deleteSecret for systemIntegrationId: ' +
            bag.inputParams.systemIntegrationId + ' with status code ' + err,
            body)
        );

      return next();
    }
  );
}
<commit_msg>syntax error fix<commit_after>'use strict';

var self = deleteById;
module.exports = self;

var async = require('async');
var _ = require('underscore');
var envHandler = require('../../common/envHandler.js');
var VaultAdapter = require('../../common/VaultAdapter.js');

function deleteById(req, res) {
  var bag = {
    inputParams: req.params,
    resBody: {},
    vaultTokenEnv: 'VAULT_TOKEN'
  };

  bag.who = util.format('systemIntegrations|%s| ' +
    'systemIntegrationId:%s', self.name,
    bag.inputParams.systemIntegrationId);
  logger.info(bag.who, 'Starting');

  async.series([
      _checkInputParams.bind(null, bag),
      _getVaultURL.bind(null, bag),
      _getVaultToken.bind(null, bag),
      _deleteById.bind(null, bag),
      _deleteByIdInVault.bind(null, bag)
    ],
    function (err) {
      logger.info(bag.who, 'Completed');
      if (err)
        return respondWithError(res, err);
      sendJSONResponse(res, bag.resBody);
    }
  );
}

function _checkInputParams(bag, next) {
  var who = bag.who + '|' + _checkInputParams.name;
  logger.verbose(who, 'Inside');

  if (!bag.inputParams.systemIntegrationId)
    return next(
      new ActErr(who, ActErr.ParamNotFound,
        'Route parameter not found :systemIntegrationId')
    );
  bag.systemIntegrationId = bag.inputParams.systemIntegrationId;
  return next();
}

function _getVaultURL(bag, next) {
  var who = bag.who + '|' + _getVaultURL.name;
  logger.verbose(who, 'Inside');

  var query = 'SELECT "vaultUrl", secrets from "systemConfigs"';
  global.config.client.query(query,
    function (err, systemConfigs) {
      if (err)
        return next(
          new ActErr(who, ActErr.DBOperationFailed, err)
        );

      if (!_.isEmpty(systemConfigs.rows) &&
        !_.isEmpty(systemConfigs.rows[0].vaultUrl)) {
        logger.debug('Found vault URL');

        bag.vaultUrl = systemConfigs.rows[0].vaultUrl;

        if (bag.vaultUrl.indexOf('http') !== 0)
          bag.vaultUrl = 'http://' + bag.vaultUrl;

        if (systemConfigs.rows[0].secrets) {
          var secretsConfig = JSON.parse(systemConfigs.rows[0].secrets);
          bag.vaultUrl = bag.vaultUrl + ':' + secretsConfig.port;
        }
        return next();
      }

      return next(
        new ActErr(who, ActErr.DataNotFound,
          'No vault URL found in configs')
      );
    }
  );
}

function _getVaultToken(bag, next) {
  var who = bag.who + '|' + _getVaultURL.name;
  logger.verbose(who, 'Inside');

  envHandler.get(bag.vaultTokenEnv,
    function (err, value) {
      if (err)
        return next(
          new ActErr(who, ActErr.OperationFailed,
            'Cannot get env: ' + bag.vaultTokenEnv)
        );

      if (_.isEmpty(value)) {
        return next(
          new ActErr(who, ActErr.DataNotFound,
            'No vault token found')
        );
      }

      logger.debug('Found vault token');
      bag.vaultToken = value;
      return next();
    }
  );
}

function _deleteById(bag, next) {
  var who = bag.who + '|' + _deleteById.name;
  logger.verbose(who, 'Inside');

  var query =
    util.format('DELETE from "systemIntegrations" where id=\'%s\';',
      bag.systemIntegrationId);

  global.config.client.query(query,
    function (err) {
      if (err)
        return next(
          new ActErr(who, mapSequelizeErr(err),
            'systemIntegrations.delete failed for id: ' +
            bag.systemIntegrationId + ' returned error: ' + err.message)
        );

      return next();
    }
  );
}

function _deleteByIdInVault(bag, next) {
  var who = bag.who + '|' + _deleteByIdInVault.name;
  logger.verbose(who, 'Inside');

  var vaultUrl = bag.vaultUrl;
  var shippableVaultToken = bag.vaultToken;
  var vaultAdapter = new VaultAdapter(vaultUrl, shippableVaultToken);

  var key = util.format('shippable/systemIntegrations/%s',
    bag.inputParams.systemIntegrationId);
  vaultAdapter.deleteSecret(key,
    function (err, body) {
      if (err)
        return next(
          new ActErr(who, ActErr.OperationFailed,
            'Failed to :deleteSecret for systemIntegrationId: ' +
            bag.inputParams.systemIntegrationId + ' with status code ' + err,
            body)
        );

      return next();
    }
  );
}
<|endoftext|>


<commit_before>/* globals $ Backbone */
(function(window) {
  /**
   * Splits a string at the first occurrance of a character.
   */
  function splitAtFirst(string, char) {
    var index = string.indexOf(char);

    if (index === -1) {
      return [string];
    }

    return [string.slice(0, index + 1), string.slice(index)];
  }

  /**
   * Renders an error message when ETEngine threw an exception and returned a
   * backtrace. Highlights lines referring to queries and inputs.
   */
  var TraceView = Backbone.View.extend({
    events: { 'click .expand': 'expand' },

    expand: function() {
      this.options.expanded = true;
      this.$el.empty();
      this.render();
    },

    render: function() {
      var message = this.options.message;
      var split = splitAtFirst(message, '\n');

      if (split[0].match(/\/(present|future)/)) {
        var title = split[0].trim().split('/', 2);
        title[0] = '' + title[0] + '';
        split[0] = title.join('/');
      } else if (split[0].slice(0, 11) == 'SyntaxError') {
        split[0] = split[0].replace(/in (\w+)/g, 'in $1');
      }

      this.$el.append($('
').html(split[0]), this.renderTrace(split[1]));

      return this.$el;
    },

    renderTrace: function(trace) {
      if (!trace || trace.trim().length === 0) {
        return null;
      }

      // Query syntax errors separate the error title from the backtrace with a
      // pipe character.
      var split = trace.trim().split(/\n/);
      var expander = null;

      if (!this.options.expanded) {
        expander = $('').html('···');
        split = split.slice(0, 8);
      }

      // Highlight substring in the first backtrace lines which refer to queries
      // or inputs.
      split = split.map(function(line) {
        return line.replace(
          /(etsource\/(?:inputs|gqueries).*?):/g,
          '$1:'
        );
      });

      return $('
').append(
        $('
').html(split.join('\n')),
        expander
      );
    }
  });

  /**
   * View which hides the ETM interface and shows the user a message describing
   * the error which occurred.
   */
  var ApiErrorView = Backbone.View.extend({
    id: 'api-error',

    events: {
      'click .refresh': function(event) {
        event.preventDefault();
        window.location = window.location; // eslint-disable-line no-self-assign
      }
    },

    render: function() {
      this.$el.append(
        $('
').append(
          $(''),
          ' ETEngine returned an error'
        )
      );

      this.$el.append(
        $('
').append(
          $('← Back to the home page'),
          $('Refresh and try again').attr(
            'href',
            location.pathname
          ),
          $('View scenario in ETEngine').attr(
            'href',
            this.options.scenarioURL
          )
        )
      );

      if (
        this.options.status >= 400 &&
        this.options.status < 500 &&
        this.options.responseJSON
      ) {
        this.$el.append(this.renderJSONErrors());
      } else {
        this.$el.append(
          $('
').text(this.options.responseText)
        );
      }

      return this.$el;
    },

    renderJSONErrors: function() {
      return $('
').append(
        this.options.responseJSON.errors.map(this.renderJSONError)
      );
    },

    renderJSONError: function(message) {
      var li = $('
');

      if (message.indexOf('|') || message.indexOf('\n')) {
        li.append(new TraceView({ message: message }).render());
      } else {
        li.text(message);
      }

      return li;
    }
  });

  window.ApiErrorView = ApiErrorView;
})(window);
<commit_msg>Add "Hide this message" to ApiError<commit_after>/* globals $ Backbone */
(function(window) {
  /**
   * Splits a string at the first occurrance of a character.
   */
  function splitAtFirst(string, char) {
    var index = string.indexOf(char);

    if (index === -1) {
      return [string];
    }

    return [string.slice(0, index + 1), string.slice(index)];
  }

  /**
   * Renders an error message when ETEngine threw an exception and returned a
   * backtrace. Highlights lines referring to queries and inputs.
   */
  var TraceView = Backbone.View.extend({
    events: { 'click .expand': 'expand' },

    expand: function() {
      this.options.expanded = true;
      this.$el.empty();
      this.render();
    },

    render: function() {
      var message = this.options.message;
      var split = splitAtFirst(message, '\n');

      if (split[0].match(/\/(present|future)/)) {
        var title = split[0].trim().split('/', 2);
        title[0] = '' + title[0] + '';
        split[0] = title.join('/');
      } else if (split[0].slice(0, 11) == 'SyntaxError') {
        split[0] = split[0].replace(/in (\w+)/g, 'in $1');
      }

      this.$el.append($('
').html(split[0]), this.renderTrace(split[1]));

      return this.$el;
    },

    renderTrace: function(trace) {
      if (!trace || trace.trim().length === 0) {
        return null;
      }

      // Query syntax errors separate the error title from the backtrace with a
      // pipe character.
      var split = trace.trim().split(/\n/);
      var expander = null;

      if (!this.options.expanded) {
        expander = $('').html('···');
        split = split.slice(0, 8);
      }

      // Highlight substring in the first backtrace lines which refer to queries
      // or inputs.
      split = split.map(function(line) {
        return line.replace(
          /(etsource\/(?:inputs|gqueries).*?):/g,
          '$1:'
        );
      });

      return $('
').append(
        $('
').html(split.join('\n')),
        expander
      );
    }
  });

  /**
   * View which hides the ETM interface and shows the user a message describing
   * the error which occurred.
   */
  var ApiErrorView = Backbone.View.extend({
    id: 'api-error',

    events: {
      'click .refresh': function(event) {
        event.preventDefault();
        window.location = window.location; // eslint-disable-line no-self-assign
      },
      'click .hide': function(event) {
        event.preventDefault();

        this.$el.remove();
        $('body').removeClass('has-api-error');
      }
    },

    render: function() {
      this.$el.append(
        $('
').append(
          $(''),
          ' ETEngine returned an error'
        )
      );

      this.$el.append(
        $('
').append(
          $('← Back to the home page'),
          $('Refresh and try again').attr(
            'href',
            location.pathname
          ),
          $('Hide this message').attr('href', '#'),
          $('View scenario in ETEngine').attr(
            'href',
            this.options.scenarioURL
          )
        )
      );

      if (
        this.options.status >= 400 &&
        this.options.status < 500 &&
        this.options.responseJSON
      ) {
        this.$el.append(this.renderJSONErrors());
      } else {
        this.$el.append(
          $('
').text(this.options.responseText)
        );
      }

      return this.$el;
    },

    renderJSONErrors: function() {
      return $('
').append(
        this.options.responseJSON.errors.map(this.renderJSONError)
      );
    },

    renderJSONError: function(message) {
      var li = $('
');

      if (message.indexOf('|') || message.indexOf('\n')) {
        li.append(new TraceView({ message: message }).render());
      } else {
        li.text(message);
      }

      return li;
    }
  });

  window.ApiErrorView = ApiErrorView;
})(window);
<|endoftext|>


<commit_before>/**
 * Borra registros anteriores y carga los nuevos
 * @param url
 */
var cargaRegistrosSnib = function(url)
{
    snibLayer = L.markerClusterGroup({ chunkedLoading: true, spiderfyDistanceMultiplier: 2,
        spiderLegPolylineOptions: { weight: 1.5, color: 'white', opacity: 0.5 }
    });

    borraRegistrosAnterioresSnib();
    geojsonSnib(url);
};

/**
 * Borra registros anteriores
 */
var borraRegistrosAnterioresSnib = function()
{
    if (map.hasLayer(snibLayer))
    {
        map.removeControl(legend_control);
        map.removeLayer(markersLayer);
        snibLayer = L.markerClusterGroup({ chunkedLoading: true, spiderfyDistanceMultiplier: 2,
            spiderLegPolylineOptions: { weight: 1.5, color: 'white', opacity: 0.5 }
        });
    } else {
        snibLayer = L.markerClusterGroup({
            chunkedLoading: true, spiderfyDistanceMultiplier: 2,
            spiderLegPolylineOptions: {weight: 1.5, color: 'white', opacity: 0.5}
        });
    }
};

/**
 * La simbologia dentro del mapa
 * @param con_conteo
 */
var leyendaSnib = function(con_conteo)
{
    if (con_conteo == undefined)
        var conteo_snib = "Registros del SNIB";
    else
        var conteo_snib = "Registros del SNIB " + registros_conteo + "";

    var overlays = {
        'Registros del SNIB
(museos, colectas y proyectos)': snibLayer,
        'Especímenes en colecciones': coleccionesLayer,
        'Observaciones de aVerAves': observacionesLayer,
        'Fósiles': fosilesLayer,
        /*"Localidad no de campo": coleccionesLayer,*/
    };

    legend_control = L.control.layers({}, overlays, {collapsed: false, position: 'bottomleft'}).addTo(map);
};

/**
 * Añade los puntos en forma de fuentes
 */
var aniadePuntosSnib = function()
{
    var geojsonFeature =  { "type": "FeatureCollection", "features": allowedPoints.values()};

    var colecciones = L.geoJson(geojsonFeature, {
        pointToLayer: function (feature, latlng) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                if (feature.properties.d[1] == 1)  // Este campos quiere decir que es el deafult de la coleccion
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib-default', html: ''})});
            } else {
                // Este campos quiere decir que es de aves aves
                if (!feature.properties.d.coleccion.toLowerCase().includes('averaves') && !feature.properties.d.coleccion.toLowerCase().includes('ebird')
                && feature.properties.d.ejemplarfosil != 'SI')
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib-default', html: ''})});
            }
        },
        onEachFeature: function (feature, layer) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                layer.on("click", function () {
                    ejemplarSnibGeojson(layer, feature.properties.d[0]);
                });
            } else
                layer.bindPopup(ejemplarSnib(feature.properties.d));
        }
    });

    var observaciones = L.geoJson(geojsonFeature, {
        pointToLayer: function (feature, latlng) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                if (feature.properties.d[1] == 2)  // Este campos quiere decir que es de aves aves
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: ''})});
            } else {
                if (feature.properties.d.coleccion.toLowerCase().includes('averaves') || feature.properties.d.coleccion.toLowerCase().includes('ebird'))  // Este campos quiere decir que es de aves aves
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: ''})});
            }
        },
        onEachFeature: function (feature, layer) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                layer.on("click", function () {
                    ejemplarSnibGeojson(layer, feature.properties.d[0]);
                });
            } else
                layer.bindPopup(ejemplarSnib(feature.properties.d));
        }
    });

    var fosiles = L.geoJson(geojsonFeature, {
        pointToLayer: function (feature, latlng) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                if (feature.properties.d[1] == 3) {
                    console.log('hay fosil');
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: ''})});
                } // Este campos quiere decir que es de fosiles

            } else {
                if (feature.properties.d.ejemplarfosil == 'SI')
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: ''})});
            }
        },
        onEachFeature: function (feature, layer) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                layer.on("click", function () {
                    ejemplarSnibGeojson(layer, feature.properties.d[0]);
                });
            } else
                layer.bindPopup(ejemplarSnib(feature.properties.d));
        }
    });

    coleccionesLayer = L.featureGroup.subGroup(snibLayer, colecciones);
    coleccionesLayer.addLayer(colecciones);
    observacionesLayer = L.featureGroup.subGroup(snibLayer, observaciones);
    observacionesLayer.addLayer(observaciones);
    fosilesLayer = L.featureGroup.subGroup(snibLayer, fosiles);
    fosilesLayer.addLayer(fosiles);

    map.addLayer(snibLayer);
    map.addLayer(coleccionesLayer);
    map.addLayer(observacionesLayer);
    map.addLayer(fosilesLayer);
    leyendaSnib(true);
};

/**
 * Hace una ajax request para la obtener la información de un taxon, esto es más rapido para muchos registros
 * */
var ejemplarSnibGeojson = function(layer, id)
{
    $.ajax({
        url: "/especies/" + opciones.taxon + "/ejemplar-snib/" + id,
        dataType : "json",
        success : function (res){
            if (res.estatus)
            {
                var contenido = ejemplarSnib(res.ejemplar);
                layer.bindPopup(contenido);
                layer.openPopup();
            }
            else
                console.log("Hubo un error al retraer el ejemplar: " + res.msg);
        },
        error: function( jqXHR ,  textStatus,  errorThrown ){
            console.log("error: " + textStatus);
            console.log(errorThrown);
            console.log(jqXHR.responseText);
        }
    });  // termina ajax
};

/**
 * Lanza el pop up con la inforamcion del taxon, ya esta cargado; este metodo es lento con muchos registros
 * */
var ejemplarSnib = function(prop)
{
    // Sustituye las etiquetas h5 por h4 y centra el texto
    var nombre_f = $('<textarea/>').html(opciones.nombre).text().replace(/<h5/g, "<h4 class='text-center'").replace(/<\/h5/g, "</h4");
    var contenido = "";

    contenido += "" + nombre_f + "";
    contenido += "
Localidad:

" + prop.localidad + "
";
    contenido += "
Municipio:

" + prop.municipiomapa + "
";
    contenido += "
Estado:

" + prop.estadomapa + "
";
    contenido += "
País:

" + prop.paismapa + "
";
    contenido += "
Fecha:

" + prop.fechacolecta + "
";
    contenido += "
Colector:

" + prop.colector + "
";
    contenido += "
Colección:

" + prop.coleccion + "
";
    contenido += "
Institución:

" + prop.institucion + "
";
    contenido += "
País de la colección:

" + prop.paiscoleccion + "
";

    if (prop.proyecto.length > 0 && prop.urlproyecto.length > 0)
        contenido += "
Proyecto:

" + prop.proyecto + "
";

    contenido += "
Más información:

consultar
";

    //Para enviar un comentario acerca de un registro en particular
    contenido += "
¿Tienes un comentario?:

redactar
";

    return "
" + contenido + "
" + "ID SNIB: " + prop.idejemplar;
};

/**
 * Carga el geojson para iterarlo
 * @param url
 */
var geojsonSnib = function(url)
{
    $.ajax({
        url: url,
        dataType : "json",
        success : function (d){
            registros_conteo = d.length;
            colecciones = 0;
            observaciones = 0;
            fosiles = 0;
            allowedPoints = d3.map([]);

            for(var i=0;i<d.length;i++)
            {
                var item_id = 'geo-' + i.toString();

                if (opciones.solo_coordenadas)
                {
                    allowedPoints.set(item_id, {
                        "type"      : "Feature",
                        "properties": {d: [d[i][2], d[i][3]]},
                        "geometry"  : {coordinates: [d[i][0], d[i][1]], type: "Point"}
                    });
                } else {
                    allowedPoints.set(item_id, {
                        "type"      : "Feature",
                        "properties": {d: d[i]},
                        "geometry"  : JSON.parse(d[i].json_geom)
                    });
                }
            }

            aniadePuntosSnib();
        },
        error: function( jqXHR ,  textStatus,  errorThrown ){
            console.log("error: " + textStatus);
            console.log(errorThrown);
            console.log(jqXHR.responseText);
        }
    });
};<commit_msg>acomodando la simbologia en la leyenda<commit_after>/**
 * Borra registros anteriores y carga los nuevos
 * @param url
 */
var cargaRegistrosSnib = function(url)
{
    snibLayer = L.markerClusterGroup({ chunkedLoading: true, spiderfyDistanceMultiplier: 2,
        spiderLegPolylineOptions: { weight: 1.5, color: 'white', opacity: 0.5 }
    });

    borraRegistrosAnterioresSnib();
    geojsonSnib(url);
};

/**
 * Borra registros anteriores
 */
var borraRegistrosAnterioresSnib = function()
{
    if (map.hasLayer(snibLayer))
    {
        map.removeControl(legend_control);
        map.removeLayer(markersLayer);
        snibLayer = L.markerClusterGroup({ chunkedLoading: true, spiderfyDistanceMultiplier: 2,
            spiderLegPolylineOptions: { weight: 1.5, color: 'white', opacity: 0.5 }
        });
    } else {
        snibLayer = L.markerClusterGroup({
            chunkedLoading: true, spiderfyDistanceMultiplier: 2,
            spiderLegPolylineOptions: {weight: 1.5, color: 'white', opacity: 0.5}
        });
    }
};

/**
 * La simbologia dentro del mapa
 * @param con_conteo
 */
var leyendaSnib = function()
{
    legend_control = L.control.layers({}, {}, {collapsed: false, position: 'bottomleft'}).addTo(map);

    legend_control.addOverlay(snibLayer,
        'Registros del SNIB
(museos, colectas y proyectos) ' + registros_conteo + ''
    );

    legend_control.addOverlay(coleccionesLayer,
        'Especímenes en colecciones'
    );

    legend_control.addOverlay(observacionesLayer,
        'Observaciones de aVerAves'
    );

    legend_control.addOverlay(fosilesLayer,
        'Fósiles'
    );

    legend_control.addOverlay(noCampoLayer,
        'Localidad no de campo'
    );
};

/**
 * Añade los puntos en forma de fuentes
 */
var aniadePuntosSnib = function()
{
    var geojsonFeature =  { "type": "FeatureCollection", "features": allowedPoints.values()};

    var colecciones = L.geoJson(geojsonFeature, {
        pointToLayer: function (feature, latlng) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                if (feature.properties.d[1] == 1)  // Este campos quiere decir que es el deafult de la coleccion
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib-default', html: ''})});
            } else {
                // Este campos quiere decir que es de aves aves
                if (!feature.properties.d.coleccion.toLowerCase().includes('averaves') && !feature.properties.d.coleccion.toLowerCase().includes('ebird')
                && feature.properties.d.ejemplarfosil != 'SI')
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib-default', html: ''})});
            }
        },
        onEachFeature: function (feature, layer) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                layer.on("click", function () {
                    ejemplarSnibGeojson(layer, feature.properties.d[0]);
                });
            } else
                layer.bindPopup(ejemplarSnib(feature.properties.d));
        }
    });

    var observaciones = L.geoJson(geojsonFeature, {
        pointToLayer: function (feature, latlng) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                if (feature.properties.d[1] == 2)  // Este campos quiere decir que es de aves aves
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: ''})});
            } else {
                if (feature.properties.d.coleccion.toLowerCase().includes('averaves') || feature.properties.d.coleccion.toLowerCase().includes('ebird'))  // Este campos quiere decir que es de aves aves
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: ''})});
            }
        },
        onEachFeature: function (feature, layer) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                layer.on("click", function () {
                    ejemplarSnibGeojson(layer, feature.properties.d[0]);
                });
            } else
                layer.bindPopup(ejemplarSnib(feature.properties.d));
        }
    });

    var fosiles = L.geoJson(geojsonFeature, {
        pointToLayer: function (feature, latlng) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                if (feature.properties.d[1] == 3)  // Este campos quiere decir que es de fosiles
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: ''})});
            } else {
                if (feature.properties.d.ejemplarfosil == 'SI')
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: ''})});
            }
        },
        onEachFeature: function (feature, layer) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                layer.on("click", function () {
                    ejemplarSnibGeojson(layer, feature.properties.d[0]);
                });
            } else
                layer.bindPopup(ejemplarSnib(feature.properties.d));
        }
    });

    var noCampo = L.geoJson(geojsonFeature, {
        pointToLayer: function (feature, latlng) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                if (feature.properties.d[1] == 4)  // Este campos quiere decir que es de locacion no de campo
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib-default', html: ''})});
            } else {
                if (feature.properties.d.ejemplarfosil == 'SI')
                    return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib-default', html: ''})});
            }
        },
        onEachFeature: function (feature, layer) {
            // Para distinguir si son solo las coordenadas
            if (opciones.solo_coordenadas)
            {
                layer.on("click", function () {
                    ejemplarSnibGeojson(layer, feature.properties.d[0]);
                });
            } else
                layer.bindPopup(ejemplarSnib(feature.properties.d));
        }
    });

    coleccionesLayer = L.featureGroup.subGroup(snibLayer, colecciones);
    coleccionesLayer.addLayer(colecciones);
    observacionesLayer = L.featureGroup.subGroup(snibLayer, observaciones);
    observacionesLayer.addLayer(observaciones);
    fosilesLayer = L.featureGroup.subGroup(snibLayer, fosiles);
    fosilesLayer.addLayer(fosiles);
    noCampoLayer = L.featureGroup.subGroup(snibLayer, noCampo);
    noCampoLayer.addLayer(noCampo);

    map.addLayer(snibLayer);
    map.addLayer(coleccionesLayer);
    map.addLayer(observacionesLayer);
    map.addLayer(fosilesLayer);
    leyendaSnib(true);
};

/**
 * Hace una ajax request para la obtener la información de un taxon, esto es más rapido para muchos registros
 * */
var ejemplarSnibGeojson = function(layer, id)
{
    $.ajax({
        url: "/especies/" + opciones.taxon + "/ejemplar-snib/" + id,
        dataType : "json",
        success : function (res){
            if (res.estatus)
            {
                var contenido = ejemplarSnib(res.ejemplar);
                layer.bindPopup(contenido);
                layer.openPopup();
            }
            else
                console.log("Hubo un error al retraer el ejemplar: " + res.msg);
        },
        error: function( jqXHR ,  textStatus,  errorThrown ){
            console.log("error: " + textStatus);
            console.log(errorThrown);
            console.log(jqXHR.responseText);
        }
    });  // termina ajax
};

/**
 * Lanza el pop up con la inforamcion del taxon, ya esta cargado; este metodo es lento con muchos registros
 * */
var ejemplarSnib = function(prop)
{
    // Sustituye las etiquetas h5 por h4 y centra el texto
    var nombre_f = $('<textarea/>').html(opciones.nombre).text().replace(/<h5/g, "<h4 class='text-center'").replace(/<\/h5/g, "</h4");
    var contenido = "";

    contenido += "" + nombre_f + "";
    contenido += "
Localidad:

" + prop.localidad + "
";
    contenido += "
Municipio:

" + prop.municipiomapa + "
";
    contenido += "
Estado:

" + prop.estadomapa + "
";
    contenido += "
País:

" + prop.paismapa + "
";
    contenido += "
Fecha:

" + prop.fechacolecta + "
";
    contenido += "
Colector:

" + prop.colector + "
";
    contenido += "
Colección:

" + prop.coleccion + "
";
    contenido += "
Institución:

" + prop.institucion + "
";
    contenido += "
País de la colección:

" + prop.paiscoleccion + "
";

    if (prop.proyecto.length > 0 && prop.urlproyecto.length > 0)
        contenido += "
Proyecto:

" + prop.proyecto + "
";

    contenido += "
Más información:

consultar
";

    //Para enviar un comentario acerca de un registro en particular
    contenido += "
¿Tienes un comentario?:

redactar
";

    return "
" + contenido + "
" + "ID SNIB: " + prop.idejemplar;
};

/**
 * Carga el geojson para iterarlo
 * @param url
 */
var geojsonSnib = function(url)
{
    $.ajax({
        url: url,
        dataType : "json",
        success : function (d){
            registros_conteo = d.length;
            colecciones = 0;
            observaciones = 0;
            fosiles = 0;
            allowedPoints = d3.map([]);

            for(var i=0;i<d.length;i++)
            {
                var item_id = 'geo-' + i.toString();

                if (opciones.solo_coordenadas)
                {
                    allowedPoints.set(item_id, {
                        "type"      : "Feature",
                        "properties": {d: [d[i][2], d[i][3]]},
                        "geometry"  : {coordinates: [d[i][0], d[i][1]], type: "Point"}
                    });
                } else {
                    allowedPoints.set(item_id, {
                        "type"      : "Feature",
                        "properties": {d: d[i]},
                        "geometry"  : JSON.parse(d[i].json_geom)
                    });
                }
            }

            aniadePuntosSnib();
        },
        error: function( jqXHR ,  textStatus,  errorThrown ){
            console.log("error: " + textStatus);
            console.log(errorThrown);
            console.log(jqXHR.responseText);
        }
    });
};<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";
var cliArgs = require("command-line-args");
var fs = require("fs");
var FileSet = require("file-set");
var cp = require("child_process");
var dope = require("console-dope");
var s = require("string-tools");
var alert = require("../lib/alert");

var cli = cliArgs([
    { name: "do", type: String, multiple: true },
    { name: "when", type: String, defaultOption: true },
    { name: "change", type: Boolean },
    { name: "speak", alias: "s", type: Boolean },
    { name: "poll-interval", alias: "p", type: Number, defaultValue: 1000 },
    { name: "help", alias: "h", type: Boolean },
    { name: "verbose", alias: "v", type: Boolean }
]);

var usage = cli.getUsage({
    title: "[bold]{baldrick}",
    description: "A general-purpose filesystem-watch-and-respond tool.",
    usage: {
        title: "[bold]{Usage}",
        forms: [
            "$ baldrick --do <command> --when <files> [--change] [--speak] [--poll-interval <number>]",
            "$ baldrick --help"
        ]
    },
    footer: "Project page: [underline]{https://github.com/75lb/baldrick}"
});

try {
    var options = cli.parse();
} catch(err){
    halt(err.message);
}

if (options.help){
    console.log(usage);
    process.exit(0);
}

validate();
watchFiles(options.when);

function runCommand(command){
    cp.exec(command, function(err, stdout, stderr){
        if (err){
            alert.bell();
            if (options.speak) alert.say("i fucked up!");
            dope.red.bold.log("%s fucked up", s.symbol.cross);
            dope.log(err.message);
        } else {
            if (options.speak) alert.say("my lord");
            dope.bold.green.log("%s work done", s.symbol.tick);
            if (stdout || stderr){
                dope.bold.log("\noutput");
                if (stdout) dope.log(stdout);
                if (stderr) dope.log(stderr);
            }
        }
    });
}

function watchFiles(whenExpression){
    var fileSet = new FileSet(whenExpression);

    fileSet.files.forEach(function(file){
        if (options.verbose){
            console.log(file);
        }

        fs.watchFile(file, { interval: options["poll-interval"] }, function(currStat, prevStat){
            dope.bold.underline.log("%s touched", file);
            if (options.change && (currStat.mtime.getTime() > prevStat.mtime.getTime())){
                options.do.forEach(runCommand);
            }
        });
    });
}
options.do.forEach(runCommand);

function halt(msg){
    dope.red.error("Error: " + msg);
    dope.log(usage);
    process.exit(1);
}

function validate(){
    if (!(options.do.length && options.when)) halt("Must specify --do and --when");
}
<commit_msg>{{file}} in --do<commit_after>#!/usr/bin/env node
"use strict";
var cliArgs = require("command-line-args");
var fs = require("fs");
var FileSet = require("file-set");
var cp = require("child_process");
var dope = require("console-dope");
var s = require("string-tools");
var alert = require("../lib/alert");

var cli = cliArgs([
    { name: "do", type: String, multiple: true },
    { name: "when", type: String, multiple: true, defaultOption: true },
    { name: "change", type: Boolean },
    { name: "speak", alias: "s", type: Boolean },
    { name: "poll-interval", alias: "p", type: Number, defaultValue: 1000 },
    { name: "help", alias: "h", type: Boolean },
    { name: "verbose", alias: "v", type: Boolean }
]);

var usage = cli.getUsage({
    title: "[bold]{baldrick}",
    description: "A general-purpose filesystem-watch-and-respond tool.",
    usage: {
        title: "[bold]{Usage}",
        forms: [
            "$ baldrick --do <command> --when <files> [--change] [--speak] [--poll-interval <number>]",
            "$ baldrick --help"
        ]
    },
    footer: "Project page: [underline]{https://github.com/75lb/baldrick}"
});

try {
    var options = cli.parse();
} catch(err){
    halt(err.message);
}

if (options.help){
    console.log(usage);
    process.exit(0);
}

validate();
watchFiles(options.when);

function runCommand(file, command){
    if (file){
        command = command.replace(/{{file}}/g, file);
    }
    if (/{{file}}/.test(command)) return;

    cp.exec(command, function(err, stdout, stderr){
        if (err){
            alert.bell();
            if (options.speak) alert.say("i fucked up!");
            dope.red.bold.log("%s fucked up", s.symbol.cross);
            dope.log(err.message);
        } else {
            if (options.speak) alert.say("my lord");
            dope.bold.green.log("%s work done", s.symbol.tick);
            if (stdout || stderr){
                dope.bold.log("\noutput");
                if (stdout) dope.log(stdout);
                if (stderr) dope.log(stderr);
            }
        }
    });
}

function watchFiles(whenExpression){
    var fileSet = new FileSet(whenExpression);

    fileSet.files.forEach(function(file){
        if (options.verbose){
            console.log(file);
        }

        fs.watchFile(file, { interval: options["poll-interval"] }, function(currStat, prevStat){
            dope.bold.underline.log("%s touched", file);
            if (options.change && (currStat.mtime.getTime() > prevStat.mtime.getTime())){
                options.do.forEach(runCommand.bind(null, file));
            }
        });
    });
}
options.do.forEach(runCommand.bind(null, null));

function halt(msg){
    dope.red.error("Error: " + msg);
    dope.log(usage);
    process.exit(1);
}

function validate(){
    if (!(options.do.length && options.when)) halt("Must specify --do and --when");
}
<|endoftext|>