<commit_before>/*globals require, process, __dirname, console, module*/
/**
 * NOTE: Expected to be run only under nodejs.
 *
 * @author kecso / https://github.com/kecso
 * @author ksmyth / https://github.com/ksmyth
 * @author lattmann / https://github.com/lattmann
 */

var requirejs = require('requirejs'),
    Q = require('q'),
    MongoURI = require('mongo-uri'),

    GMEAuth,
    config,

    main;

requirejs.config({
    nodeRequire: require,
    baseUrl: __dirname + '/..',
    paths: {
        'util': 'common/util',
        'auth': 'server/auth',
        'bin': 'bin'
    }
});

GMEAuth = requirejs('auth/gmeauth');
config = requirejs('bin/getconfig');

main = function () {
    'use strict';

    var program = require('commander'),
        auth,
        mainDeferred = Q.defer(),
        setupGMEAuth = function (databaseConnectionString) {
            var mongoConnectionInfo,
                uri;
            if (databaseConnectionString) {
                // this line throws a TypeError for invalid databaseConnectionString
                uri = MongoURI.parse(databaseConnectionString);

                mongoConnectionInfo = {
                    host: uri.hosts[0],
                    port: uri.ports[0] || 27017,
                    database: uri.database || 'multi'
                };
            } else {
                mongoConnectionInfo = {
                    host: config.mongoip,
                    port: config.mongoport,
                    database: config.mongodatabase
                };
            }

            console.log(mongoConnectionInfo);

            auth = new GMEAuth(mongoConnectionInfo);
        };

    program
        .version('0.1.0')
        .option('--db <database>', 'database connection string', 'mongodb://127.0.0.1:27017/multi');

    program
        .command('useradd <username> <email> <password>')
        .description('adds a new user')
        .option('-c, --canCreate', 'user can create a new project', false)
        .action(function (username, email, password, options) {
            setupGMEAuth(options.parent.db);

            // TODO: we may need to use a module like 'prompt' to get user password
            auth.addUser(username, email, password, options.canCreate, { overwrite: true})
                .then(mainDeferred.resolve)
                .catch(mainDeferred.reject)
                .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js useradd brubble brubble@example.com Password.123');
            console.log('    $ node usermanager.js useradd --canCreate brubble brubble@example.com Password.123');
            console.log();
        });

    program
        .command('userlist [username]')
        .description('lists all users or the specified user')
        .action(function (username, options) {
            setupGMEAuth(options.parent.db);

            return auth.getAllUserAuthInfo(username)
                .then(function (userObject) {
                    // TODO: pretty print users
                    console.log(userObject);
                    mainDeferred.resolve();
                })
                .catch(mainDeferred.reject)
                .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js userlist');
            console.log('    $ node usermanager.js userlist user23');
            console.log();
        });

    program
        .command('passwd <username> <password>')
        .description('updates the user')
        .action(function (username, password, options) {
            setupGMEAuth(options.parent.db);

            // TODO: we may need to use a module like 'prompt' to get user password
            return auth.getAllUserAuthInfo(username)
                .then(function (userObject) {
                    return auth.addUser(username, userObject.email, password, userObject.canCreate, { overwrite: true});
                })
                .then(mainDeferred.resolve)
                .catch(mainDeferred.reject)
                .finally(auth.unload);

        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js passwd brubble NewPass.123');
            console.log();
        });

    program
        .command('userdel <username>')
        .description('deletes a user')
        .action(function (username, options) {
            setupGMEAuth(options.parent.db);

            return auth.removeUserByUserId(username)
                .then(mainDeferred.resolve)
                .catch(mainDeferred.reject)
                .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js userdel brubble');
            console.log();
        });

    program
        .command('groupadd <groupname>')
        .description('adds a new group')
        .action(function (groupname, options) {
            setupGMEAuth(options.parent.db);

            console.log('TODO: add a new group ' + groupname);
            mainDeferred.reject('not implemented yet.');
            auth.unload();

            //return auth.addGroup(groupname)
            //    .then(mainDeferred.resolve)
            //    .catch(mainDeferred.reject)
            //    .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js groupadd newgroup');
            console.log();
        });

    program
        .command('groupdel <groupname>')
        .description('deletes an existing group')
        .action(function (groupname, options) {
            setupGMEAuth(options.parent.db);

            console.log('TODO: delete an existing group ' + groupname);
            mainDeferred.reject('not implemented yet.');
            auth.unload();

            //return auth.delGroup(groupname)
            //    .then(mainDeferred.resolve)
            //    .catch(mainDeferred.reject)
            //    .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js groupdel sample_group');
            console.log();
        });

    program
        .command('usermod_auth <username> <projectname>')
        .description('deletes an existing group')
        .option('-a, --authorize <mode>', 'mode is rwd, read, write, delete', 'rwd')
        .option('-d, --deauthorize', 'deauthorizes user', false)
        .action(function (username, projectname, options) {
            var rights = {
                read:   options.authorize.indexOf('r') !== -1,
                write:  options.authorize.indexOf('w') !== -1,
                delete: options.authorize.indexOf('d') !== -1
            };

            setupGMEAuth(options.parent.db);

            if (options.deauthorize) {
                // deauthorize
                rights = {};
            }

            // authorize
            return auth.authorizeByUserId(username, projectname, 'create', rights)
                .then(mainDeferred.resolve)
                .catch(mainDeferred.reject)
                .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js usermod_auth user23 project42');
            console.log('    $ node usermanager.js usermod_auth --authorize r user23 project42');
            console.log('    $ node usermanager.js usermod_auth --authorize rw user23 project42');
            console.log('    $ node usermanager.js usermod_auth -a rw user23 project42');
            console.log('    $ node usermanager.js usermod_auth --deauthorize user23 project42');
            console.log('    $ node usermanager.js usermod_auth -d user23 project42');
            console.log();
        });

    // TODO: usermod_group
    //node usermanager.js usermod_group --addgroup newgroup brubble
    //node usermanager.js usermod_group --delgroup newgroup brubble

    program.parse(process.argv);

    return mainDeferred.promise;
};

if (require.main === module) {

    main()
        .then(function () {
            'use strict';
            console.log('Done');
        })
        .catch(function (err) {
            'use strict';
            console.error('ERROR : ' + err);
        });

    //commands
    //function infoPrint(userName) {
    //    return gmeauth.getAllUserAuthInfo(userName)
    //        .then(function printUser(userObject) {
    //            var outstring = '',
    //                userProjects = userObject.projects,
    //                i,
    //                mode,
    //                end;
    //
    //            outstring += 'userName: ' + padString(userObject._id) + ' | ';
    //            outstring += 'canCreate: ' + userObject.canCreate + ' | ';
    //            outstring += 'projects: ';
    //
    //            for (i in userProjects) {
    //                mode = '';
    //                if (userProjects[i].read) {
    //                    mode += 'r';
    //                } else {
    //                    mode += '_';
    //                }
    //                if (userProjects[i].write) {
    //                    mode += 'w';
    //                } else {
    //                    mode += '_';
    //                }
    //                if (userProjects[i].delete) {
    //                    mode += 'd';
    //                } else {
    //                    mode += '_';
    //                }
    //                outstring += padString(i + '(' + mode + ')', 20) + ' ; ';
    //            }
    //
    //            end = outstring.lastIndexOf(';');
    //            if (end !== -1) {
    //                outstring = outstring.substring(0, end - 1);
    //            }
    //            return outstring;
    //        });
    //}
    //
    //function generateToken() {
    //    return gmeauth.generateTokenForUserId(userId)
    //        .then(console.log);
    //}
}<commit_msg>#177 placeholder for add/delete user to/from group<commit_after>/*globals require, process, __dirname, console, module*/
/**
 * NOTE: Expected to be run only under nodejs.
 *
 * @author kecso / https://github.com/kecso
 * @author ksmyth / https://github.com/ksmyth
 * @author lattmann / https://github.com/lattmann
 */

var requirejs = require('requirejs'),
    Q = require('q'),
    MongoURI = require('mongo-uri'),

    GMEAuth,
    config,

    main;

requirejs.config({
    nodeRequire: require,
    baseUrl: __dirname + '/..',
    paths: {
        'util': 'common/util',
        'auth': 'server/auth',
        'bin': 'bin'
    }
});

GMEAuth = requirejs('auth/gmeauth');
config = requirejs('bin/getconfig');

main = function () {
    'use strict';

    var program = require('commander'),
        auth,
        mainDeferred = Q.defer(),
        setupGMEAuth = function (databaseConnectionString) {
            var mongoConnectionInfo,
                uri;
            if (databaseConnectionString) {
                // this line throws a TypeError for invalid databaseConnectionString
                uri = MongoURI.parse(databaseConnectionString);

                mongoConnectionInfo = {
                    host: uri.hosts[0],
                    port: uri.ports[0] || 27017,
                    database: uri.database || 'multi'
                };
            } else {
                mongoConnectionInfo = {
                    host: config.mongoip,
                    port: config.mongoport,
                    database: config.mongodatabase
                };
            }

            console.log(mongoConnectionInfo);

            auth = new GMEAuth(mongoConnectionInfo);
        };

    program
        .version('0.1.0')
        .option('--db <database>', 'database connection string', 'mongodb://127.0.0.1:27017/multi');

    program
        .command('useradd <username> <email> <password>')
        .description('adds a new user')
        .option('-c, --canCreate', 'user can create a new project', false)
        .action(function (username, email, password, options) {
            setupGMEAuth(options.parent.db);

            // TODO: we may need to use a module like 'prompt' to get user password
            auth.addUser(username, email, password, options.canCreate, { overwrite: true})
                .then(mainDeferred.resolve)
                .catch(mainDeferred.reject)
                .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js useradd brubble brubble@example.com Password.123');
            console.log('    $ node usermanager.js useradd --canCreate brubble brubble@example.com Password.123');
            console.log();
        });

    program
        .command('userlist [username]')
        .description('lists all users or the specified user')
        .action(function (username, options) {
            setupGMEAuth(options.parent.db);

            return auth.getAllUserAuthInfo(username)
                .then(function (userObject) {
                    // TODO: pretty print users
                    console.log(userObject);
                    mainDeferred.resolve();
                })
                .catch(mainDeferred.reject)
                .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js userlist');
            console.log('    $ node usermanager.js userlist user23');
            console.log();
        });

    program
        .command('passwd <username> <password>')
        .description('updates the user')
        .action(function (username, password, options) {
            setupGMEAuth(options.parent.db);

            // TODO: we may need to use a module like 'prompt' to get user password
            return auth.getAllUserAuthInfo(username)
                .then(function (userObject) {
                    return auth.addUser(username, userObject.email, password, userObject.canCreate, { overwrite: true});
                })
                .then(mainDeferred.resolve)
                .catch(mainDeferred.reject)
                .finally(auth.unload);

        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js passwd brubble NewPass.123');
            console.log();
        });

    program
        .command('userdel <username>')
        .description('deletes a user')
        .action(function (username, options) {
            setupGMEAuth(options.parent.db);

            return auth.removeUserByUserId(username)
                .then(mainDeferred.resolve)
                .catch(mainDeferred.reject)
                .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js userdel brubble');
            console.log();
        });

    program
        .command('groupadd <groupname>')
        .description('adds a new group')
        .action(function (groupname, options) {
            setupGMEAuth(options.parent.db);

            console.log('TODO: add a new group ' + groupname);
            mainDeferred.reject('not implemented yet.');
            auth.unload();

            //return auth.addGroup(groupname)
            //    .then(mainDeferred.resolve)
            //    .catch(mainDeferred.reject)
            //    .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js groupadd newgroup');
            console.log();
        });

    program
        .command('groupdel <groupname>')
        .description('deletes an existing group')
        .action(function (groupname, options) {
            setupGMEAuth(options.parent.db);

            console.log('TODO: delete an existing group ' + groupname);
            mainDeferred.reject('not implemented yet.');
            auth.unload();

            //return auth.delGroup(groupname)
            //    .then(mainDeferred.resolve)
            //    .catch(mainDeferred.reject)
            //    .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js groupdel sample_group');
            console.log();
        });

    program
        .command('usermod_auth <username> <projectname>')
        .description('deletes an existing group')
        .option('-a, --authorize <mode>', 'mode is rwd, read, write, delete', 'rwd')
        .option('-d, --deauthorize', 'deauthorizes user', false)
        .action(function (username, projectname, options) {
            var rights = {
                read:   options.authorize.indexOf('r') !== -1,
                write:  options.authorize.indexOf('w') !== -1,
                delete: options.authorize.indexOf('d') !== -1
            };

            setupGMEAuth(options.parent.db);

            if (options.deauthorize) {
                // deauthorize
                rights = {};
            }

            // authorize
            return auth.authorizeByUserId(username, projectname, 'create', rights)
                .then(mainDeferred.resolve)
                .catch(mainDeferred.reject)
                .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js usermod_auth user23 project42');
            console.log('    $ node usermanager.js usermod_auth --authorize r user23 project42');
            console.log('    $ node usermanager.js usermod_auth --authorize rw user23 project42');
            console.log('    $ node usermanager.js usermod_auth -a rw user23 project42');
            console.log('    $ node usermanager.js usermod_auth --deauthorize user23 project42');
            console.log('    $ node usermanager.js usermod_auth -d user23 project42');
            console.log();
        });

    program
        .command('usermod_group_add <username> <groupname>')
        .description('adds a user to an existing group')
        .action(function (username, groupname, options) {
            setupGMEAuth(options.parent.db);

            console.log('add ' + username + ' to ' + groupname);
            mainDeferred.reject('not implemented yet.');
            auth.unload();

            //return auth.addUserToGroup(username, groupname)
            //    .then(mainDeferred.resolve)
            //    .catch(mainDeferred.reject)
            //    .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js usermod_group_add user23 group123');
            console.log();
        });

    program
        .command('usermod_group_del <username> <groupname>')
        .description('removes a user from an existing group')
        .action(function (username, groupname, options) {
            setupGMEAuth(options.parent.db);

            console.log('remove ' + username + ' from ' + groupname);
            mainDeferred.reject('not implemented yet.');
            auth.unload();

            //return auth.removeUserFromGroup(username, groupname)
            //    .then(mainDeferred.resolve)
            //    .catch(mainDeferred.reject)
            //    .finally(auth.unload);
        })
        .on('--help', function () {
            console.log('  Examples:');
            console.log();
            console.log('    $ node usermanager.js usermod_group_del user23 group123');
            console.log();
        });

    program.parse(process.argv);

    return mainDeferred.promise;
};

if (require.main === module) {

    main()
        .then(function () {
            'use strict';
            console.log('Done');
        })
        .catch(function (err) {
            'use strict';
            console.error('ERROR : ' + err);
        });

    //commands
    //function infoPrint(userName) {
    //    return gmeauth.getAllUserAuthInfo(userName)
    //        .then(function printUser(userObject) {
    //            var outstring = '',
    //                userProjects = userObject.projects,
    //                i,
    //                mode,
    //                end;
    //
    //            outstring += 'userName: ' + padString(userObject._id) + ' | ';
    //            outstring += 'canCreate: ' + userObject.canCreate + ' | ';
    //            outstring += 'projects: ';
    //
    //            for (i in userProjects) {
    //                mode = '';
    //                if (userProjects[i].read) {
    //                    mode += 'r';
    //                } else {
    //                    mode += '_';
    //                }
    //                if (userProjects[i].write) {
    //                    mode += 'w';
    //                } else {
    //                    mode += '_';
    //                }
    //                if (userProjects[i].delete) {
    //                    mode += 'd';
    //                } else {
    //                    mode += '_';
    //                }
    //                outstring += padString(i + '(' + mode + ')', 20) + ' ; ';
    //            }
    //
    //            end = outstring.lastIndexOf(';');
    //            if (end !== -1) {
    //                outstring = outstring.substring(0, end - 1);
    //            }
    //            return outstring;
    //        });
    //}
    //
    //function generateToken() {
    //    return gmeauth.generateTokenForUserId(userId)
    //        .then(console.log);
    //}
}<|endoftext|>


<commit_before>(function(top, module, define) {

function inferScriptType(filename) {
  var mime = mimeForFilename(filename);
  if (/^text\/x-pencilcode/.test(mime)) {
    mime = 'text/coffeescript';
  }
  // Script type attributes do not understand encoding.
  return mime.replace(/;.*$/, '');
}

function wrapTurtle(text, pragmasOnly, setupScript) {
  var result, j, scripts = [], script_pattern =
    /(?:^|\n)#[^\S\n]*@script[^\S\n<>]+(\S+|"[^"\n]*"|'[^'\n]*')/g;
  // Add the default turtle script.
  scripts.push(
    '


<commit_before>const router = require('express').Router()
const Orders = require('../db/models/order')

module.exports = require('express').Router()
 .get('/orders',
 (req, res, next) =>
  Orders.findAll({})
    .then((orders) => {
      if (!orders.length) {
        let error = new Error()
        error.status = 404
        throw error
      }
      res.send(orders)
    })
   .catch(next))
 .get('/order/:orderId',
    (req, res, next) => {
      Orders.findAll({
        where: {
          id: req.params.orderId
        }
      })
 .then((orders) => {
   if (!orders.length) {
     var error = new Error()
     error.status = 404
     throw error
   }
   res.send(orders)
 })
 .catch(next)
    })
 .get('/order/:userId',
  (req, res, next) =>
  Orders.findAll({
    where: {
      user_Id: req.params.userId
    }
  })
 .then((orders) => {
   if (!orders.length) {
     var error = new Error()
     error.status = 404
     throw error
   }
   res.send(orders)
 })
 .catch(next))

<commit_msg>updated order route<commit_after>const router = require('express').Router()
const Orders = require('../db/models/order')

module.exports = require('express').Router()
 .get('/',
 (req, res, next) =>
  Orders.findAll({})
    .then((orders) => {
      if (!orders.length) {
        let error = new Error()
        error.status = 404
        throw error
      }
      res.send(orders)
    })
   .catch(next))
 .get('/:orderId',
    (req, res, next) => {
      Orders.findAll({
        where: {
          id: req.params.orderId
        }
      })
 .then((orders) => {
   if (!orders.length) {
     var error = new Error()
     error.status = 404
     throw error
   }
   res.send(orders)
 })
 .catch(next)
    })
 .get('/:userId',
  (req, res, next) =>
  Orders.findAll({
    where: {
      user_Id: req.params.userId
    }
  })
 .then((orders) => {
   if (!orders.length) {
     var error = new Error()
     error.status = 404
     throw error
   }
   res.send(orders)
 })
 .catch(next))
 .get('/:status',
  (req, res, next) =>
   Orders.findAll({
     where: {
       status: req.params.status
     }
   })
 .then(orders => {
   if (!orders.length) {
     var error = new Error()
     error.status = 404
     throw error
   }
 })
 .catch(next))
  .put('/:status',
  (req, res, next) =>
   Orders.update({
     status: req.params.status
   })
 .then(orders => {
   if (!orders.length) {
     var error = new Error()
     error.status = 404
     throw error
   }
 })
 .catch(next))

<|endoftext|>


<commit_before>var _ = require('lodash');

function getNested (data, key, ids) {
  var result = {}
    _.each(ids, function (id) {
      var obj = {};
      obj[id] = data[key][id];
    _.extend(result, obj);
  });
  return result;
}

module.exports = function filterData(data, key, id) {
  var result = { experiments:{} };
  if (key === 'experiments') {
    var exp = data[key][id];
    result.experiments[id] = data[key][id];
    result.depVars = getNested(data, 'depVars', exp.depVars);
    // get all of the ids for the measures from all of the depVars on this experiment
    var measureIds = _.reduce(result.depVars, function (concatted, depVar) {
      return concatted.concat(depVar.measures);
    }, []);

    result.measures = getNested(data, 'measures', measureIds);
    result.indVars = getNested(data, 'indVars', exp.indVars);
    // var requestIds = _.reduce(result.depVars, function (concatted, depVar) {
    //   return concatted.concat(depVar.requests);
    // }, []);
    // result.requests = getNested(data, 'requests', exp.requests);
    // get all of the ids for the reminders from all of the indVars on this experiment
    // var reminderIds = _.reduce(result.indVars, function (concatted, indVar) {
    //   return concatted.concat(indVar.reminders);
    // });
    // result.reminders = getNested(data, 'reminders', reminderIds);
  } else {
    console.log('this filters out only for the experiment');
  }
  return result;
};
<commit_msg>Fix indenting and add missing semicolon<commit_after>var _ = require('lodash');

function getNested (data, key, ids) {
  var result = {};
  _.each(ids, function (id) {
    var obj = {};
    obj[id] = data[key][id];
    _.extend(result, obj);
  });
  return result;
}

module.exports = function filterData(data, key, id) {
  var result = { experiments:{} };
  if (key === 'experiments') {
    var exp = data[key][id];
    result.experiments[id] = data[key][id];
    result.depVars = getNested(data, 'depVars', exp.depVars);
    // get all of the ids for the measures from all of the depVars on this experiment
    var measureIds = _.reduce(result.depVars, function (concatted, depVar) {
      return concatted.concat(depVar.measures);
    }, []);

    result.measures = getNested(data, 'measures', measureIds);
    result.indVars = getNested(data, 'indVars', exp.indVars);
    // var requestIds = _.reduce(result.depVars, function (concatted, depVar) {
    //   return concatted.concat(depVar.requests);
    // }, []);
    // result.requests = getNested(data, 'requests', exp.requests);
    // get all of the ids for the reminders from all of the indVars on this experiment
    // var reminderIds = _.reduce(result.indVars, function (concatted, indVar) {
    //   return concatted.concat(indVar.reminders);
    // });
    // result.reminders = getNested(data, 'reminders', reminderIds);
  } else {
    console.log('this filters out only for the experiment');
  }
  return result;
};
<|endoftext|>


<commit_before><commit_msg>get instrmentcount from config.instrumentCollection<commit_after><|endoftext|>


<commit_before>/*
 Copyright (C) 2015-2017 GEM Foundation

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/agpl.html>.
 */

(function($, Backbone, _) {
    var calculation_table;

    var progressHandlingFunction = function(progress) {
        var percent = progress.loaded / progress.total * 100;
        $('.bar').css('width', percent + '%');
        if (percent == 100) {
            dialog.hide();
        }
    };

    var htmlEscape = function (record) {
        // record[3] is the log message
        record[3] = record[3].replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
        return record
    };

    var dialog = (function ()
                  {
                      var pleaseWaitDiv = $('

Processing...

');
                      return {
                          show: function(msg, progress) {
                              $('h1', pleaseWaitDiv).text(msg);
                              if (progress) {
                                  progressHandlingFunction({loaded: 0, total: 1});
                              } else {
                                  progressHandlingFunction({loaded: 1, total: 1});
                              }
                              pleaseWaitDiv.modal('show');
                          },
                          hide: function () {
                              pleaseWaitDiv.modal('hide');
                          }
                      };
                  })();

    var diaerror = (function ()
                  {
                      var errorDiv = $('
\

\

\

\

Calculation not accepted: traceback
\

\

\

\

\
                      <input type="checkbox" id="diaerror_scroll_enabled" checked>\
                      Auto Scroll   \
                      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>\

\

\

\

');
                      errorDiv.bind('hide', function() { calculation_table.hide_log(); });
                      return {
                          getdiv: function() {
                              return errorDiv;
                          },

                          show: function(is_large, title, msg) {
                              if (title != null) {
                                  $('.modal-title', errorDiv).html(title);
                              }
                              if (msg != null) {
                                  $('.modal-body-pre', errorDiv).html(msg);
                              }
                              if (is_large) {
                                  errorDiv.addClass("errorDialogLarge");
                              }
                              else {
                                  errorDiv.removeClass("errorDialogLarge");
                              }
                              errorDiv.modal('show');
                          },

                          append: function(title, msg) {
                              if (title != null) {
                                  $('.modal-title', errorDiv).html(title);
                              }
                              $( msg ).appendTo( $('.modal-body-pre', errorDiv) );
                          },

                          scroll_to_bottom: function(ctx) {
                              ctx.scrollTop(ctx[0].scrollHeight);
                          },

                          hide: function () {
                              errorDiv.modal('hide');
                          }
                      };
                  })();

    var CalculationTable = Backbone.View.extend(
        {
            /* the html element where the table is rendered */
            el: $('#my-calculations'),

            logXhr: null,
            logId: -1,
            logIsNew: false,
            logLinesAll: 0,
            logLines: 0,
            logTimeout: null,

            initialize: function(options) {

                /* whatever happens to any calculation, re-render the table */
                _.bindAll(this, 'render');
                this.calculations = options.calculations;
                this.calculations.bind('reset', this.render);
                this.calculations.bind('add', this.render);
                this.calculations.bind('remove', this.render);

                /* if false, it prevents the table to be refreshed */
                this.can_be_rendered = true;

                this.render();
            },

            events: {
                "click .btn-show-remove": "remove_calculation",
                "click .btn-danger": "show_modal_confirm_remove_calculation",
                "click .btn-hide-remove": "hide_modal_confirm_remove_calculation",
                "click .btn-traceback": "show_traceback",
                "click .btn-log": "show_log",
                "click .btn-file": "on_run_risk_clicked",
                "change .btn-file input": "on_run_risk_queued"
            },

            /* When an input dialog is opened, it is very important to not re-render the table */
            on_run_risk_clicked: function(e) {
                /* if a file input dialog has been opened do not refresh the calc table */
                this.can_be_rendered = false;
            },

            on_run_risk_queued: function(e) {
                this.can_be_rendered = true;
            },

            show_modal_confirm_remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');

                var show_or_back = (function(e) {
                    this.conf_show = $('#confirmDialog' + calc_id).show();
                    this.back_conf_show = $('.back_confirmDialog' + calc_id).show();
                    closeTimer();
                })();
            },

            hide_modal_confirm_remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');

                var hide_or_back = (function(e) {
                    this.conf_hide = $('#confirmDialog' + calc_id).hide();
                    this.back_conf_hide = $('.back_confirmDialog' + calc_id).hide();
                    setTimer();
                })();
            },

            remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var calc_desc = $(e.target).attr('data-calc-desc');
                var view = this;
                diaerror.show(false, "Removing calculation " + calc_id, "...");

                var hide_or_back = (function(e) {
                    this.conf_hide = $('#confirmDialog' + calc_id).hide();
                    this.back_conf_hide = $('.back_confirmDialog' + calc_id).hide();
                    setTimer();
                })();

                var myXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/remove",
                                    type: "POST",
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 403) {
                                            diaerror.show(false, "Error", "" + JSON.parse(jqXHR.responseText).error);
                                        }
                                    },
                                    success: function(data, textStatus, jqXHR) {
                                        err = data.error;
                                        if(!err) {
                                            err = "removed.";
                                        }
                                        diaerror.show(false, "Calculation removed", "Calculation:
(" + calc_id + ") " + calc_desc + " " + err );
                                        view.calculations.remove([view.calculations.get(calc_id)]);
                                    }});
            },

            show_traceback: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var myXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/traceback",
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 404) {
                                            diaerror.show(false, "Calculation " + calc_id + " not found.");
                                        }
                                        else {
                                            diaerror.show(false, "Error retrieving traceback for calculation " + calc_id, textStatus);
                                        }
                                        // alert("Error: " + textStatus);
                                    },
                                    success: function (data, textStatus, jqXHR) {
                                        if (data.length == 0) {
                                            diaerror.show(true, "Traceback not found for calculation " + calc_id, []);
                                        }
                                        else {
                                            var out = "";
                                            var ct = 0;
                                            for (s in data) {
                                                if (data[s] == "")
                                                    continue;
                                                out += '
' + data[s] + '
';
                                                ct++;
                                            }
                                            diaerror.show(true, "Traceback of calculation " + calc_id, out);
                                        }
                                        // alert("Success: " + textStatus);
                                    }});
            },

            _show_log_priv: function(is_new, calc_id, is_running, from) {
                var was_running = is_running;

                // TO CHECK hide_log method enable console.log and take a look
                // console.log("_show_log_priv: begin");
                if (this.logXhr != null) {
                    this.logXhr.abort();
                    this.logXhr = null;
                }
                if (is_new) {
                    if (this.logTimeout != null) {
                        window.clearTimeout(this.logTimeout);
                        this.logTimeout = null;
                    }
                }
                var obj = this;

                this.logXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/log/" + from + ":",
                                      error: function (jqXHR, textStatus, errorThrown) {
                                          if (jqXHR.status == 404) {
                                              diaerror.show(true, "Log of calculation " + calc_id + " not found.");
                                          }
                                          else {
                                              diaerror.show(true, "Error retrieving log for calculation " + calc_id, textStatus);
                                          }
                                          obj.logIsNew = false;
                                      },
                                      success: function (data, textStatus, jqXHR) {
                                          var delay = 250;

                                          if (is_new) {
                                              obj.logLines = 0;
                                              obj.logLinesAll = 0;
                                          }
                                          else {
                                              // if data is empty check if job is still running
                                              if (is_running) {
                                                  if (data.length == 0) {
                                                      var ajax, status;

                                                      delay = 1000;

                                                      ajax = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/status",
                                                                     async: false}).done(function (data) { status = data.is_running; });
                                                      if (status !== true) {
                                                          is_running = false;
                                                      }
                                                  }
                                              }
                                          }
                                          var out = "";

                                          for (s in data) {
                                              if (data[s] == "") {
                                                  obj.logLinesAll++;
                                                  continue;
                                              }
                                              out += '
' + htmlEscape(data[s]) + '
';
                                              obj.logLines++;
                                              obj.logLinesAll++;
                                          }

                                          var title;
                                          if (is_running) {
                                              var dt;
                                              dt = new Date();
                                              title = "Log of calculation " + calc_id + " - " + dt.toString();
                                          }
                                          else if (was_running != is_running) {
                                              title = "Log of calculation " + calc_id + " - finished";
                                          }
                                          else {
                                              title = "Log of calculation " + calc_id;
                                          }

                                          if (obj.logIsNew) {
                                              diaerror.show(true, title, out);
                                          }
                                          else {
                                              diaerror.append(title, out);
                                          }
                                          if ($("#diaerror_scroll_enabled").prop( "checked" ) || was_running == false) {
                                              diaerror.scroll_to_bottom($('.modal-body', diaerror.getdiv()));
                                          }

                                          if (is_running) {
                                              function log_update(obj)
                                              {
                                                  obj._show_log_priv(false, obj.logId, true, obj.logLinesAll);
                                              }

                                              obj.logTimeout = window.setTimeout(log_update, delay, obj);
                                          }
                                          else {
                                              $('#diaerror_scroll_enabled_box').hide();
                                          }

                                          obj.logIsNew = false;
                                      }});
            },

            show_log: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var is_running = ($(e.target).attr('is-running') == "true");

                this.logId = calc_id;
                this.logIsNew = true;

                if (is_running)
                    $('#diaerror_scroll_enabled_box', diaerror.getdiv()).show();
                else
                    $('#diaerror_scroll_enabled_box', diaerror.getdiv()).hide();

                this._show_log_priv(true, calc_id, is_running, "0");
            },

            hide_log: function(e) {
                if (this.logTimeout != null) {
                    window.clearTimeout(this.logTimeout);
                    this.logTimeout = null;
                }
                if (this.logXhr != null) {
                    this.logXhr.abort();
                    this.logXhr = null;
                }
                $('#diaerror_scroll_enabled_box').hide();
            },

            render: function() {
                if (!this.can_be_rendered) {
                    return;
                };
                this.$el.html(_.template($('#calculation-table-template').html(),
                                         { calculations: this.calculations.models }));
            }
        });

    var Calculation = Backbone.Model.extend({
        defaults: {
            map: null,
            layers: []
        }
    });

    var Calculations = Backbone.Collection.extend(
        {
            model: Calculation,
            url: gem_oq_server_url + "/v1/calc/list?relevant=true"
        });
    var calculations = new Calculations();

    var refresh_calcs;

    function setTimer() {
        refresh_calcs = setInterval(function() { calculations.fetch({reset: true}) }, 3000);
    }

    function closeTimer() {
        refresh_calcs = clearInterval(refresh_calcs);
    }

    /* classic event management */
    $(document).ready(
        function() {
            calculation_table = new CalculationTable({ calculations: calculations });
            calculations.fetch({reset: true});
            setTimer();

            /* XXX. Reset the input file value to ensure the change event
               will be always triggered */
            $(document).on("click", 'input[name=archive]',
                           function(e) { this.value = null; });
            $(document).on("change", 'input[name=archive]',
                           function(e) {
                               dialog.show('Uploading calculation', true);
                               var input = $(e.target);
                               var form = input.parents('form')[0];

                               $(form).ajaxSubmit(
                                   {
                                    xhr: function() {  // custom xhr to add progress bar management
                                        var myXhr = $.ajaxSettings.xhr();
                                        if(myXhr.upload){ // if upload property exists
                                            myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                                        }
                                        return myXhr;
                                    },
                                    success: function(data) {
                                        calculations.add(new Calculation(data), {at: 0});
                                    },
                                    error: function(xhr) {
                                        dialog.hide();
                                        var s, out, data = $.parseJSON(xhr.responseText);
                                        var out = "";
                                        var ct = 0;
                                        for (s in data) {
                                            if (data[s] == "")
                                                continue;
                                            out += '
' + data[s] + '
';
                                            ct++;
                                        }
                                        diaerror.show(false, "Calculation not accepted: traceback", out);
                                    }});
                           });

            $(document).on('hidden.bs.modal', 'div[id^=traceback-]',
                           function(e) {
                               setTimer();
                           });

        });
})($, Backbone, _, gem_oq_server_url);
<commit_msg>changed message for error remove calculation [skip CI]<commit_after>/*
 Copyright (C) 2015-2017 GEM Foundation

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/agpl.html>.
 */

(function($, Backbone, _) {
    var calculation_table;

    var progressHandlingFunction = function(progress) {
        var percent = progress.loaded / progress.total * 100;
        $('.bar').css('width', percent + '%');
        if (percent == 100) {
            dialog.hide();
        }
    };

    var htmlEscape = function (record) {
        // record[3] is the log message
        record[3] = record[3].replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
        return record
    };

    var dialog = (function ()
                  {
                      var pleaseWaitDiv = $('

Processing...

');
                      return {
                          show: function(msg, progress) {
                              $('h1', pleaseWaitDiv).text(msg);
                              if (progress) {
                                  progressHandlingFunction({loaded: 0, total: 1});
                              } else {
                                  progressHandlingFunction({loaded: 1, total: 1});
                              }
                              pleaseWaitDiv.modal('show');
                          },
                          hide: function () {
                              pleaseWaitDiv.modal('hide');
                          }
                      };
                  })();

    var diaerror = (function ()
                  {
                      var errorDiv = $('
\

\

\

\

Calculation not accepted: traceback
\

\

\

\

\
                      <input type="checkbox" id="diaerror_scroll_enabled" checked>\
                      Auto Scroll   \
                      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>\

\

\

\

');
                      errorDiv.bind('hide', function() { calculation_table.hide_log(); });
                      return {
                          getdiv: function() {
                              return errorDiv;
                          },

                          show: function(is_large, title, msg) {
                              if (title != null) {
                                  $('.modal-title', errorDiv).html(title);
                              }
                              if (msg != null) {
                                  $('.modal-body-pre', errorDiv).html(msg);
                              }
                              if (is_large) {
                                  errorDiv.addClass("errorDialogLarge");
                              }
                              else {
                                  errorDiv.removeClass("errorDialogLarge");
                              }
                              errorDiv.modal('show');
                          },

                          append: function(title, msg) {
                              if (title != null) {
                                  $('.modal-title', errorDiv).html(title);
                              }
                              $( msg ).appendTo( $('.modal-body-pre', errorDiv) );
                          },

                          scroll_to_bottom: function(ctx) {
                              ctx.scrollTop(ctx[0].scrollHeight);
                          },

                          hide: function () {
                              errorDiv.modal('hide');
                          }
                      };
                  })();

    var CalculationTable = Backbone.View.extend(
        {
            /* the html element where the table is rendered */
            el: $('#my-calculations'),

            logXhr: null,
            logId: -1,
            logIsNew: false,
            logLinesAll: 0,
            logLines: 0,
            logTimeout: null,

            initialize: function(options) {

                /* whatever happens to any calculation, re-render the table */
                _.bindAll(this, 'render');
                this.calculations = options.calculations;
                this.calculations.bind('reset', this.render);
                this.calculations.bind('add', this.render);
                this.calculations.bind('remove', this.render);

                /* if false, it prevents the table to be refreshed */
                this.can_be_rendered = true;

                this.render();
            },

            events: {
                "click .btn-show-remove": "remove_calculation",
                "click .btn-danger": "show_modal_confirm_remove_calculation",
                "click .btn-hide-remove": "hide_modal_confirm_remove_calculation",
                "click .btn-traceback": "show_traceback",
                "click .btn-log": "show_log",
                "click .btn-file": "on_run_risk_clicked",
                "change .btn-file input": "on_run_risk_queued"
            },

            /* When an input dialog is opened, it is very important to not re-render the table */
            on_run_risk_clicked: function(e) {
                /* if a file input dialog has been opened do not refresh the calc table */
                this.can_be_rendered = false;
            },

            on_run_risk_queued: function(e) {
                this.can_be_rendered = true;
            },

            show_modal_confirm_remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');

                var show_or_back = (function(e) {
                    this.conf_show = $('#confirmDialog' + calc_id).show();
                    this.back_conf_show = $('.back_confirmDialog' + calc_id).show();
                    closeTimer();
                })();
            },

            hide_modal_confirm_remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');

                var hide_or_back = (function(e) {
                    this.conf_hide = $('#confirmDialog' + calc_id).hide();
                    this.back_conf_hide = $('.back_confirmDialog' + calc_id).hide();
                    setTimer();
                })();
            },

            remove_calculation: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var calc_desc = $(e.target).attr('data-calc-desc');
                var view = this;
                diaerror.show(false, "Removing calculation " + calc_id, "...");

                var hide_or_back = (function(e) {
                    this.conf_hide = $('#confirmDialog' + calc_id).hide();
                    this.back_conf_hide = $('.back_confirmDialog' + calc_id).hide();
                    setTimer();
                })();

                var myXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/remove",
                                    type: "POST",
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 403) {
                                            diaerror.show(false, "Error", "
" + JSON.parse(jqXHR.responseText).error);
                                        }
                                    },
                                    success: function(data, textStatus, jqXHR) {
                                        err = data.error;
                                        if(!err) {
                                            err = "removed.";
                                        }
                                        diaerror.show(false, "Calculation removed", "
(" + calc_id + ") " + calc_desc + " " + err );
                                        view.calculations.remove([view.calculations.get(calc_id)]);
                                    }});
            },

            show_traceback: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var myXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/traceback",
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 404) {
                                            diaerror.show(false, "Calculation " + calc_id + " not found.");
                                        }
                                        else {
                                            diaerror.show(false, "Error retrieving traceback for calculation " + calc_id, textStatus);
                                        }
                                        // alert("Error: " + textStatus);
                                    },
                                    success: function (data, textStatus, jqXHR) {
                                        if (data.length == 0) {
                                            diaerror.show(true, "Traceback not found for calculation " + calc_id, []);
                                        }
                                        else {
                                            var out = "";
                                            var ct = 0;
                                            for (s in data) {
                                                if (data[s] == "")
                                                    continue;
                                                out += '
' + data[s] + '
';
                                                ct++;
                                            }
                                            diaerror.show(true, "Traceback of calculation " + calc_id, out);
                                        }
                                        // alert("Success: " + textStatus);
                                    }});
            },

            _show_log_priv: function(is_new, calc_id, is_running, from) {
                var was_running = is_running;

                // TO CHECK hide_log method enable console.log and take a look
                // console.log("_show_log_priv: begin");
                if (this.logXhr != null) {
                    this.logXhr.abort();
                    this.logXhr = null;
                }
                if (is_new) {
                    if (this.logTimeout != null) {
                        window.clearTimeout(this.logTimeout);
                        this.logTimeout = null;
                    }
                }
                var obj = this;

                this.logXhr = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/log/" + from + ":",
                                      error: function (jqXHR, textStatus, errorThrown) {
                                          if (jqXHR.status == 404) {
                                              diaerror.show(true, "Log of calculation " + calc_id + " not found.");
                                          }
                                          else {
                                              diaerror.show(true, "Error retrieving log for calculation " + calc_id, textStatus);
                                          }
                                          obj.logIsNew = false;
                                      },
                                      success: function (data, textStatus, jqXHR) {
                                          var delay = 250;

                                          if (is_new) {
                                              obj.logLines = 0;
                                              obj.logLinesAll = 0;
                                          }
                                          else {
                                              // if data is empty check if job is still running
                                              if (is_running) {
                                                  if (data.length == 0) {
                                                      var ajax, status;

                                                      delay = 1000;

                                                      ajax = $.ajax({url: gem_oq_server_url + "/v1/calc/" + calc_id + "/status",
                                                                     async: false}).done(function (data) { status = data.is_running; });
                                                      if (status !== true) {
                                                          is_running = false;
                                                      }
                                                  }
                                              }
                                          }
                                          var out = "";

                                          for (s in data) {
                                              if (data[s] == "") {
                                                  obj.logLinesAll++;
                                                  continue;
                                              }
                                              out += '
' + htmlEscape(data[s]) + '
';
                                              obj.logLines++;
                                              obj.logLinesAll++;
                                          }

                                          var title;
                                          if (is_running) {
                                              var dt;
                                              dt = new Date();
                                              title = "Log of calculation " + calc_id + " - " + dt.toString();
                                          }
                                          else if (was_running != is_running) {
                                              title = "Log of calculation " + calc_id + " - finished";
                                          }
                                          else {
                                              title = "Log of calculation " + calc_id;
                                          }

                                          if (obj.logIsNew) {
                                              diaerror.show(true, title, out);
                                          }
                                          else {
                                              diaerror.append(title, out);
                                          }
                                          if ($("#diaerror_scroll_enabled").prop( "checked" ) || was_running == false) {
                                              diaerror.scroll_to_bottom($('.modal-body', diaerror.getdiv()));
                                          }

                                          if (is_running) {
                                              function log_update(obj)
                                              {
                                                  obj._show_log_priv(false, obj.logId, true, obj.logLinesAll);
                                              }

                                              obj.logTimeout = window.setTimeout(log_update, delay, obj);
                                          }
                                          else {
                                              $('#diaerror_scroll_enabled_box').hide();
                                          }

                                          obj.logIsNew = false;
                                      }});
            },

            show_log: function(e) {
                e.preventDefault();
                var calc_id = $(e.target).attr('data-calc-id');
                var is_running = ($(e.target).attr('is-running') == "true");

                this.logId = calc_id;
                this.logIsNew = true;

                if (is_running)
                    $('#diaerror_scroll_enabled_box', diaerror.getdiv()).show();
                else
                    $('#diaerror_scroll_enabled_box', diaerror.getdiv()).hide();

                this._show_log_priv(true, calc_id, is_running, "0");
            },

            hide_log: function(e) {
                if (this.logTimeout != null) {
                    window.clearTimeout(this.logTimeout);
                    this.logTimeout = null;
                }
                if (this.logXhr != null) {
                    this.logXhr.abort();
                    this.logXhr = null;
                }
                $('#diaerror_scroll_enabled_box').hide();
            },

            render: function() {
                if (!this.can_be_rendered) {
                    return;
                };
                this.$el.html(_.template($('#calculation-table-template').html(),
                                         { calculations: this.calculations.models }));
            }
        });

    var Calculation = Backbone.Model.extend({
        defaults: {
            map: null,
            layers: []
        }
    });

    var Calculations = Backbone.Collection.extend(
        {
            model: Calculation,
            url: gem_oq_server_url + "/v1/calc/list?relevant=true"
        });
    var calculations = new Calculations();

    var refresh_calcs;

    function setTimer() {
        refresh_calcs = setInterval(function() { calculations.fetch({reset: true}) }, 3000);
    }

    function closeTimer() {
        refresh_calcs = clearInterval(refresh_calcs);
    }

    /* classic event management */
    $(document).ready(
        function() {
            calculation_table = new CalculationTable({ calculations: calculations });
            calculations.fetch({reset: true});
            setTimer();

            /* XXX. Reset the input file value to ensure the change event
               will be always triggered */
            $(document).on("click", 'input[name=archive]',
                           function(e) { this.value = null; });
            $(document).on("change", 'input[name=archive]',
                           function(e) {
                               dialog.show('Uploading calculation', true);
                               var input = $(e.target);
                               var form = input.parents('form')[0];

                               $(form).ajaxSubmit(
                                   {
                                    xhr: function() {  // custom xhr to add progress bar management
                                        var myXhr = $.ajaxSettings.xhr();
                                        if(myXhr.upload){ // if upload property exists
                                            myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                                        }
                                        return myXhr;
                                    },
                                    success: function(data) {
                                        calculations.add(new Calculation(data), {at: 0});
                                    },
                                    error: function(xhr) {
                                        dialog.hide();
                                        var s, out, data = $.parseJSON(xhr.responseText);
                                        var out = "";
                                        var ct = 0;
                                        for (s in data) {
                                            if (data[s] == "")
                                                continue;
                                            out += '
' + data[s] + '
';
                                            ct++;
                                        }
                                        diaerror.show(false, "Calculation not accepted: traceback", out);
                                    }});
                           });

            $(document).on('hidden.bs.modal', 'div[id^=traceback-]',
                           function(e) {
                               setTimer();
                           });

        });
})($, Backbone, _, gem_oq_server_url);
<|endoftext|>


<commit_before>const LyricBase = require('../include/lyric-base');

const keyword = 'lyrical-nonsense';

class Lyric extends LyricBase {
  get_json_lds(html) {
    const prefix = '';
    const json_lds = [];
    const first_json_ld = this.find_string_by_prefix_suffix(
      html,
      prefix,
      suffix,
      false
    );
    json_lds.push(first_json_ld);

    const pos = html.indexOf(first_json_ld);
    const after_first = html.slice(Math.max(0, pos + first_json_ld.length));

    json_lds.push(
      this.find_string_by_prefix_suffix(after_first, prefix, suffix, false)
    );

    return json_lds.map((value) => JSON.parse(value));
  }

  get_hash(url) {
    const my_url = new URL(url);
    if (my_url.hash[0] === '#') {
      return my_url.hash.slice(1);
    }
    return '';
  }

  get_lyric_content_block(url, html) {
    const hash = this.get_hash(url) || 'Lyrics';

    const prefix = `<div class="contents" id="${hash}">`;
    const suffix = '

';

    return this.find_string_by_prefix_suffix(html, prefix, suffix);
  }

  find_lyric(url, html) {
    const oneLine = html.replace(/[\n\r]/g, '');

    const block = this.get_lyric_content_block(url, oneLine);
    if (!block) {
      console.error(`Failed to get content block of url ${url}`);
      return false;
    }
    const prefix = '
';
    const suffix = '
';

    let lyric = this.find_string_by_prefix_suffix(block, prefix, suffix);
    if (!lyric) {
      return false;
    }

    lyric = lyric.replace(/<\/p>/g, '\n');
    lyric = lyric.replace(/
 ?/g, '\n');
    lyric = this.sanitize_html(lyric);

    this.lyric = lyric;

    return true;
  }

  find_info(url, html) {
    const prefix = '"@type": "MusicComposition",';
    const suffix = '"Lyrics" : {';

    const block = this.find_string_by_prefix_suffix(
      html,
      prefix,
      suffix,
      false
    );
    if (!block) {
      return;
    }

    const patterns = {
      title: '"name" : "(.+?)",',
      artist: '"byArtist".*?"name" : "(.+?)",',
      lyricist: '"lyricist".*?"name" : "(.+?)"',
      composer: '"composer".*?"name" : "(.+?)"',
    };

    const line = block.replace(/[\n\r]/g, '');
    this.fill_song_info(line, patterns);

    // some page does not have 曲名、歌手
    if (!this.title) {
      const pattern = { title: '
(.*?)
' };
      this.fill_song_info(html, pattern);
    }
    if (!this.artist) {
      const pattern = { artist: '
(.*?)
' };
      this.fill_song_info(html, pattern);
    }
  }

  async parse_page() {
    const { url } = this;

    const html = await this.get_html(url);
    await this.find_lyric(url, html);
    await this.find_info(url, html);

    return true;
  }
}

exports.keyword = keyword;
exports.Lyric = Lyric;

if (require.main === module) {
  (async () => {
    let url =
      'https://www.lyrical-nonsense.com/lyrics/minami-373/kawaki-wo-ameku/';
    if (process.argv.length > 2) {
      // eslint-disable-next-line prefer-destructuring
      url = process.argv[2];
    }
    const object = new Lyric(url);
    const lyric = await object.get();
    console.log(lyric);
  })();
}
<commit_msg>fix lyrical-nonsense get lyric content<commit_after>const LyricBase = require('../include/lyric-base');

const keyword = 'lyrical-nonsense';

class Lyric extends LyricBase {
  get_json_lds(html) {
    const prefix = '';
    const json_lds = [];
    const first_json_ld = this.find_string_by_prefix_suffix(
      html,
      prefix,
      suffix,
      false
    );
    json_lds.push(first_json_ld);

    const pos = html.indexOf(first_json_ld);
    const after_first = html.slice(Math.max(0, pos + first_json_ld.length));

    json_lds.push(
      this.find_string_by_prefix_suffix(after_first, prefix, suffix, false)
    );

    return json_lds.map((value) => JSON.parse(value));
  }

  get_hash(url) {
    const my_url = new URL(url);
    if (my_url.hash[0] === '#') {
      return my_url.hash.slice(1);
    }
    return '';
  }

  get_lyric_content_block(url, html) {
    const hash = this.get_hash(url) || 'Lyrics';

    const prefix = `<div class="contents" id="${hash}">`;
    const suffix = '

';

    return this.find_string_by_prefix_suffix(html, prefix, suffix);
  }

  find_lyric(url, html) {
    const oneLine = html.replace(/[\n\r]/g, '');

    const block = this.get_lyric_content_block(url, oneLine);
    if (!block) {
      console.error(`Failed to get content block of url ${url}`);
      return false;
    }
    const prefix = '
';
    const suffix = '
';

    let lyric = this.find_string_by_prefix_suffix(block, prefix, suffix);
    if (!lyric) {
      return false;
    }

    lyric = lyric.replace(/<\/p>/g, '\n');
    lyric = lyric.replace(/
 ?/g, '\n');
    lyric = this.sanitize_html(lyric);

    this.lyric = lyric;

    return true;
  }

  find_info(url, html) {
    const prefix = '"@type": "MusicComposition",';
    const suffix = '"Lyrics" : {';

    const block = this.find_string_by_prefix_suffix(
      html,
      prefix,
      suffix,
      false
    );
    if (!block) {
      return;
    }

    const patterns = {
      title: '"name" : "(.+?)",',
      artist: '"byArtist".*?"name" : "(.+?)",',
      lyricist: '"lyricist".*?"name" : "(.+?)"',
      composer: '"composer".*?"name" : "(.+?)"',
    };

    const line = block.replace(/[\n\r]/g, '');
    this.fill_song_info(line, patterns);

    // some page does not have 曲名、歌手
    if (!this.title) {
      const pattern = { title: '
(.*?)
' };
      this.fill_song_info(html, pattern);
    }
    if (!this.artist) {
      const pattern = { artist: '
(.*?)
' };
      this.fill_song_info(html, pattern);
    }
  }

  async parse_page() {
    const { url } = this;

    const html = await this.get_html(url);
    await this.find_lyric(url, html);
    await this.find_info(url, html);

    return true;
  }
}

exports.keyword = keyword;
exports.Lyric = Lyric;

if (require.main === module) {
  (async () => {
    let url =
      'https://www.lyrical-nonsense.com/lyrics/minami-373/kawaki-wo-ameku/';
    if (process.argv.length > 2) {
      // eslint-disable-next-line prefer-destructuring
      url = process.argv[2];
    }
    const object = new Lyric(url);
    const lyric = await object.get();
    console.log(lyric);
  })();
}
<|endoftext|>


<commit_before><commit_msg>Hide layers group first<commit_after><|endoftext|>


<commit_before>const https = require("https");

const propertyFieldTitles = {
    url: 'URL',
    statusCode: 'Status Code',
    errorMessage: 'Error',
    timeToFirstByte: { text: 'Time to First Byte', formatter: value => `${value}ms` },
    timeout: 'Timeout'
};

module.exports.sendToSlack = function (event, context, callback) {
    const result = JSON.parse(event.Records[0].Sns.Message);
    const slackWebhookPath = process.env.webhookUrl;

    const req = https.request({
        host: "hooks.slack.com",
        path: slackWebhookPath,
        method: "POST"
    }, () => {
        callback();
    });

    req.write(JSON.stringify({
        attachments: [
            {
                "fallback": "Site check result: ${result.url} ${result.success ? 'was successful' : 'failed'}. ${result.errorMessage}",
                "text": `Site check result: ${result.url} ${result.success ? 'was successful' : 'failed'}.`,
                "color": result.success ? "good" : "danger",
                "fields": Object.keys(propertyFieldTitles).reduce((fields, currentProperty) => {
                    if(!result[currentProperty]) {
                        return fields;
                    }

                    if(typeof(propertyFieldTitles[currentProperty]) === 'string') {
                        fields.push({
                            "title": propertyFieldTitles[currentProperty],
                            "value": result[currentProperty],
                            "short": true
                        });
                    }
                    else {
                        fields.push({
                            "title": propertyFieldTitles[currentProperty].text,
                            "value": propertyFieldTitles[currentProperty].formatter(result[currentProperty]),
                            "short": true
                        });
                    }

                    return fields;
                }, [])
            }
        ]
    }))
    req.end();
};
<commit_msg>log when we send to slack<commit_after>const https = require("https");

const propertyFieldTitles = {
    url: 'URL',
    statusCode: 'Status Code',
    errorMessage: 'Error',
    timeToFirstByte: { text: 'Time to First Byte', formatter: value => `${value}ms` },
    timeout: 'Timeout'
};

module.exports.sendToSlack = function (event, context, callback) {
    const result = JSON.parse(event.Records[0].Sns.Message);
    const slackWebhookPath = process.env.webhookUrl;

    const req = https.request({
        host: "hooks.slack.com",
        path: slackWebhookPath,
        method: "POST"
    }, () => {
        callback();
    });

    console.log(`Sending to slack path: "${slackWebhookPath}", message: "Site check result: ${result.url} ${result.success ? 'was successful' : 'failed'}"`);

    req.write(JSON.stringify({
        attachments: [
            {
                "fallback": "Site check result: ${result.url} ${result.success ? 'was successful' : 'failed'}. ${result.errorMessage}",
                "text": `Site check result: ${result.url} ${result.success ? 'was successful' : 'failed'}.`,
                "color": result.success ? "good" : "danger",
                "fields": Object.keys(propertyFieldTitles).reduce((fields, currentProperty) => {
                    if(!result[currentProperty]) {
                        return fields;
                    }

                    if(typeof(propertyFieldTitles[currentProperty]) === 'string') {
                        fields.push({
                            "title": propertyFieldTitles[currentProperty],
                            "value": result[currentProperty],
                            "short": true
                        });
                    }
                    else {
                        fields.push({
                            "title": propertyFieldTitles[currentProperty].text,
                            "value": propertyFieldTitles[currentProperty].formatter(result[currentProperty]),
                            "short": true
                        });
                    }

                    return fields;
                }, [])
            }
        ]
    }))
    req.end();
};
<|endoftext|>


<commit_before>import should from 'should';
import wiki from '../src/wiki';

const timeoutTime = 30000;

describe('Live tests', () => {
  it('should handle non existent pages properly', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('asdasdlkalskdjalsdjalskdalsdjasdasd')
      .catch(e => {
        e.message.should.equal('No article found');
        done();
      });
  });
  it('should return first foreign image as main', function(done) {
    this.timeout(timeoutTime);
    wiki({ apiUrl: 'https://de.wikipedia.org/w/api.php' })
      .page('Batman')
      .then(page => {
        page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/commons/0/07/Gotham_City_Saviour_%282430422247%29.jpg'
          );
          done();
        });
      });
  });
  it('should use different names for "image" for foreign wikis', function() {
    this.timeout(timeoutTime);
    return wiki({ apiUrl: 'https://es.wikipedia.org/w/api.php' })
      .page('Cristiano Ronaldo')
      .then(page => {
        return page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/commons/8/8c/Cristiano_Ronaldo_2018.jpg'
          );
        });
      });
  });
  it('should handle Issue #53', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('FC Copenhagen')
      .then(page => {
        page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/en/9/93/FC_K%C3%B8benhavn.svg'
          );
          done();
        });
      });
  });
  it('should handle Issue #54', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('FC Santa Coloma')
      .then(page => {
        page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/en/a/ab/Santa-Coloma1.png'
          );
          done();
        });
      });
  });
  it('should handle Issue #55', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://awoiaf.westeros.org/api.php',
      origin: null
    })
      .search('Winterfell')
      .should.eventually.have.property('results')
      .containEql('Crypt of Winterfell');
  });
  it('should handle Issue #57', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://oldschoolrunescape.wikia.com/api.php',
      origin: null
    })
      .search('Bob')
      .catch(e => e.message.should.equal('text search is disabled'));
  });
  it('should handle Issue #59', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('Batman')
      .then(page => {
        page.langlinks().then(links => {
          links.should.containEql({
            lang: 'ru',
            title: 'Бэтмен'
          });
          links.should.containEql({
            lang: 'az',
            title: 'Betmen'
          });
          done();
        });
      });
  });
  it('should handle Issue #62', function(done) {
    this.timeout(timeoutTime);
    const wi = wiki({
      apiUrl: 'http://fr.wikipedia.org/w/api.php'
    });
    wi.search('royan').then(data => {
      wi.page(data.results[0]).then(page => {
        page.mainImage().then(img => {
          img.should.equal(
            'https://upload.wikimedia.org/wikipedia/commons/1/18/Port_Royan.jpg'
          );
          done();
        });
      });
    });
  });
  it('should handle Issue #63', function() {
    this.timeout(timeoutTime);
    return wiki()
      .findById(250197)
      .then(page => {
        return page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/en/1/12/France_national_football_team_seal.svg'
          );
        });
      });
  });
  it('should handle Issue #64', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .findById(3165)
      .then(page => {
        page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/en/b/ba/ACF_Fiorentina_2.svg'
          );
          done();
        });
      });
  });
  it('should handle Issue #72', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('Java_Classloader')
      .then(page => {
        page.mainImage().then(mainImage => {
          should.equal(mainImage, undefined);
          done();
        });
      });
  });
  it('should handle Issue #74 -> make all infoboxes available', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('Cross_Game')
      .then(page => page.fullInfo())
      .then(info => {
        info.tvSeries.director.should.equal('Osamu Sekita');
        done();
      });
  });
  it('should handle Issue #80 -> implement find method (default behavior)', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .find('kylie jenner')
      .then(page => page.fullInfo())
      .then(info => {
        info.general.birthName.should.equal('Kylie Kristen Jenner');
        done();
      });
  });
  it('should handle Issue #80 -> implement find method with predicate', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .find('kylie jenner', results =>
        results.find(result => result.includes('Kim'))
      )
      .then(page => page.fullInfo())
      .then(info => {
        info.general.birthName.should.equal('Kimberly Noel Kardashian');
        done();
      });
  });
  it('should fetch all pages of wiki', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'http://batman.wikia.com/api.php'
    })
      .allPages()
      .then(pages => pages.length.should.be.above(7000));
  });
  it('should fetch all categories of wiki', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'http://batman.wikia.com/api.php'
    })
      .allCategories()
      .then(cats => cats.should.containEql('Characters'));
  });
  it('should fetch all pages in category', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'http://batman.wikia.com/api.php'
    })
      .pagesInCategory('Category:Characters')
      .then(pages => pages.should.containEql('Robin (Damian Wayne)'));
  });
  it('should handle issue #83', function() {
    this.timeout(timeoutTime);
    return wiki()
      .page('athena')
      .then(p => {
        return p.mainImage().then(name => {
          return name.should.equal(
            'https://upload.wikimedia.org/wikipedia/commons/2/22/Mattei_Athena_Louvre_Ma530_n2.jpg'
          );
        });
      });
  });
  it('should handle opensearch', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://lol.gamepedia.com/api.php'
    })
      .opensearch('Ashe')
      .then(titles => titles.should.containEql('Ashe/Old Lore'));
  });
  it('should use opensearch as backup when text search is disabled', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://lol.gamepedia.com/api.php'
    })
      .search('Ashe')
      .then(titles =>
        titles.should.have.property('results').containEql('Ashe/Old Lore')
      );
  });
  it('should fetch deep infoboxes [Issue #95]', function() {
    this.timeout(timeoutTime);
    return wiki()
      .page('Copper')
      .then(page =>
        page.info().should.eventually.have.property('symbol', 'Cu')
      );
  });
  it('should parse tables [Issue #94]', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://cod-esports.gamepedia.com/api.php'
    })
      .page('Team Envy')
      .then(page => page.tables())
      .then(tables => {
        tables[0].heading.should.equal('Player Roster');
        tables[0].subheading.should.equal('Active');
        tables[0].rows[0]
          .join(',')
          .should.equal('Huke,sa,Cuyler Garland,SMG Slayer,joined=2017-11-04');
      });
  });
});
<commit_msg>Fixed live test change<commit_after>import should from 'should';
import wiki from '../src/wiki';

const timeoutTime = 30000;

describe('Live tests', () => {
  it('should handle non existent pages properly', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('asdasdlkalskdjalsdjalskdalsdjasdasd')
      .catch(e => {
        e.message.should.equal('No article found');
        done();
      });
  });
  it('should return first foreign image as main', function(done) {
    this.timeout(timeoutTime);
    wiki({ apiUrl: 'https://de.wikipedia.org/w/api.php' })
      .page('Batman')
      .then(page => {
        page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/commons/2/2b/MCM_2013_-_Batman_%288979342250%29.jpg'
          );
          done();
        });
      });
  });
  it('should use different names for "image" for foreign wikis', function() {
    this.timeout(timeoutTime);
    return wiki({ apiUrl: 'https://es.wikipedia.org/w/api.php' })
      .page('Cristiano Ronaldo')
      .then(page => {
        return page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/commons/8/8c/Cristiano_Ronaldo_2018.jpg'
          );
        });
      });
  });
  it('should handle Issue #53', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('FC Copenhagen')
      .then(page => {
        page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/en/9/93/FC_K%C3%B8benhavn.svg'
          );
          done();
        });
      });
  });
  it('should handle Issue #54', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('FC Santa Coloma')
      .then(page => {
        page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/en/a/ab/Santa-Coloma1.png'
          );
          done();
        });
      });
  });
  it('should handle Issue #55', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://awoiaf.westeros.org/api.php',
      origin: null
    })
      .search('Winterfell')
      .should.eventually.have.property('results')
      .containEql('Crypt of Winterfell');
  });
  it('should handle Issue #57', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://oldschoolrunescape.wikia.com/api.php',
      origin: null
    })
      .search('Bob')
      .catch(e => e.message.should.equal('text search is disabled'));
  });
  it('should handle Issue #59', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('Batman')
      .then(page => {
        page.langlinks().then(links => {
          links.should.containEql({
            lang: 'ru',
            title: 'Бэтмен'
          });
          links.should.containEql({
            lang: 'az',
            title: 'Betmen'
          });
          done();
        });
      });
  });
  it('should handle Issue #62', function(done) {
    this.timeout(timeoutTime);
    const wi = wiki({
      apiUrl: 'http://fr.wikipedia.org/w/api.php'
    });
    wi.search('royan').then(data => {
      wi.page(data.results[0]).then(page => {
        page.mainImage().then(img => {
          img.should.equal(
            'https://upload.wikimedia.org/wikipedia/commons/1/18/Port_Royan.jpg'
          );
          done();
        });
      });
    });
  });
  it('should handle Issue #63', function() {
    this.timeout(timeoutTime);
    return wiki()
      .findById(250197)
      .then(page => {
        return page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/en/1/12/France_national_football_team_seal.svg'
          );
        });
      });
  });
  it('should handle Issue #64', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .findById(3165)
      .then(page => {
        page.mainImage().then(mainImage => {
          mainImage.should.equal(
            'https://upload.wikimedia.org/wikipedia/en/b/ba/ACF_Fiorentina_2.svg'
          );
          done();
        });
      });
  });
  it('should handle Issue #72', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('Java_Classloader')
      .then(page => {
        page.mainImage().then(mainImage => {
          should.equal(mainImage, undefined);
          done();
        });
      });
  });
  it('should handle Issue #74 -> make all infoboxes available', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .page('Cross_Game')
      .then(page => page.fullInfo())
      .then(info => {
        info.tvSeries.director.should.equal('Osamu Sekita');
        done();
      });
  });
  it('should handle Issue #80 -> implement find method (default behavior)', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .find('kylie jenner')
      .then(page => page.fullInfo())
      .then(info => {
        info.general.birthName.should.equal('Kylie Kristen Jenner');
        done();
      });
  });
  it('should handle Issue #80 -> implement find method with predicate', function(done) {
    this.timeout(timeoutTime);
    wiki()
      .find('kylie jenner', results =>
        results.find(result => result.includes('Kim'))
      )
      .then(page => page.fullInfo())
      .then(info => {
        info.general.birthName.should.equal('Kimberly Noel Kardashian');
        done();
      });
  });
  it('should fetch all pages of wiki', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'http://batman.wikia.com/api.php'
    })
      .allPages()
      .then(pages => pages.length.should.be.above(7000));
  });
  it('should fetch all categories of wiki', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'http://batman.wikia.com/api.php'
    })
      .allCategories()
      .then(cats => cats.should.containEql('Characters'));
  });
  it('should fetch all pages in category', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'http://batman.wikia.com/api.php'
    })
      .pagesInCategory('Category:Characters')
      .then(pages => pages.should.containEql('Robin (Damian Wayne)'));
  });
  it('should handle issue #83', function() {
    this.timeout(timeoutTime);
    return wiki()
      .page('athena')
      .then(p => {
        return p.mainImage().then(name => {
          return name.should.equal(
            'https://upload.wikimedia.org/wikipedia/commons/2/22/Mattei_Athena_Louvre_Ma530_n2.jpg'
          );
        });
      });
  });
  it('should handle opensearch', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://lol.gamepedia.com/api.php'
    })
      .opensearch('Ashe')
      .then(titles => titles.should.containEql('Ashe/Old Lore'));
  });
  it('should use opensearch as backup when text search is disabled', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://lol.gamepedia.com/api.php'
    })
      .search('Ashe')
      .then(titles =>
        titles.should.have.property('results').containEql('Ashe/Old Lore')
      );
  });
  it('should fetch deep infoboxes [Issue #95]', function() {
    this.timeout(timeoutTime);
    return wiki()
      .page('Copper')
      .then(page =>
        page.info().should.eventually.have.property('symbol', 'Cu')
      );
  });
  it('should parse tables [Issue #94]', function() {
    this.timeout(timeoutTime);
    return wiki({
      apiUrl: 'https://cod-esports.gamepedia.com/api.php'
    })
      .page('Team Envy')
      .then(page => page.tables())
      .then(tables => {
        tables[0].heading.should.equal('Player Roster');
        tables[0].subheading.should.equal('Active');
        tables[0].rows[0]
          .join(',')
          .should.equal('Huke,sa,Cuyler Garland,SMG Slayer,joined=2017-11-04');
      });
  });
});
<|endoftext|>


<commit_before>import React, {Component} from 'react';

import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import HuePicker from 'src/HuePicker';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/HuePicker.json';

import 'sass/containers/app/modules/media/HuePickerExamples.scss';

export default class HuePickerExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            rgb: [255, 0, 0]
        };

        this.changeHandler = ::this.changeHandler;

    }

    changeHandler(rgb) {
        this.setState({
            rgb
        });
    }

    render() {

        const {rgb} = this.state;

        return (

Lazy Image

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

                                <HuePicker value={rgb}
                                           onChange={this.changeHandler}/>

                                <div style={{color: `rgb(${rgb.join(', ')})`}}>[{rgb.join(', ')}]

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};<commit_msg>update HuePicker examples<commit_after>import React, {Component} from 'react';

import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import HuePicker from 'src/HuePicker';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/HuePicker.json';

import 'sass/containers/app/modules/media/HuePickerExamples.scss';

export default class HuePickerExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            rgb: [255, 0, 0]
        };

        this.changeHandler = ::this.changeHandler;

    }

    changeHandler(rgb) {
        this.setState({
            rgb
        });
    }

    render() {

        const {rgb} = this.state;

        return (

Lazy Image

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

                                <HuePicker value={rgb}
                                           onChange={this.changeHandler}/>

                                <div style={{color: `rgb(${rgb.join(', ')})`}}>
                                    [{rgb.join(', ')}]

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};<|endoftext|>