<commit_before>var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var crypto = require('crypto');
var db = require('../db');

// Configure the local strategy for use by Passport.
//
// The local strategy requires a `verify` function which receives the credentials
// (`username` and `password`) submitted by the user.  The function must verify
// that the password is correct and then invoke `cb` with a user object, which
// will be set at `req.user` in route handlers after authentication.
passport.use(new LocalStrategy(function verify(username, password, cb) {
  db.get('SELECT rowid AS id, * FROM users WHERE username = ?', [ username ], function(err, row) {
    if (err) { return cb(err); }
    if (!row) { return cb(null, false, { message: 'Incorrect username or password.' }); }

    crypto.pbkdf2(password, row.salt, 310000, 32, 'sha256', function(err, hashedPassword) {
      if (err) { return cb(err); }
      if (!crypto.timingSafeEqual(row.hashed_password, hashedPassword)) {
        return cb(null, false, { message: 'Incorrect username or password.' });
      }
      return cb(null, row);
    });
  });
}));

// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session.  The
// typical implementation of this is as simple as supplying the user ID when
// serializing, and querying the user record by ID from the database when
// deserializing.
passport.serializeUser(function(user, cb) {
  process.nextTick(function() {
    cb(null, { id: user.id, username: user.username });
  });
});

passport.deserializeUser(function(user, cb) {
  process.nextTick(function() {
    return cb(null, user);
  });
});

var router = express.Router();

/* GET /login
 *
 * This route prompts the user to log in.
 *
 * The 'login' view renders an HTML form, into which the user enters their
 * username and password.  When the user submits the form, a request will be
 * sent to the `POST /login/password` route.
 */
router.get('/login', function(req, res, next) {
  res.render('login');
});

/* POST /login/password
 *
 * This route authenticates the user by verifying a username and password.
 *
 * A username and password are submitted to this route via an HTML form, which
 * was rendered by the `GET /login` route.  The username and password is
 * authenticated using the `local` strategy.  The strategy will parse the
 * username and password from the request and call the `verify` function.
 *
 * Upon successful authentication, a login session will be established.  As the
 * user interacts with the app, by clicking links and submitting forms, the
 * subsequent requests will be authenticated by verifying the session.
 *
 * When authentication fails, the user will be re-prompted to login and shown
 * a message informing them of what went wrong.
 */
router.post('/login/password', passport.authenticate('local', {
  successReturnToOrRedirect: '/',
  failureRedirect: '/login',
  failureMessage: true
}));

/* POST /logout
 *
 * This route logs the user out.
 */
router.post('/logout', function(req, res, next) {
  req.logout();
  res.redirect('/');
});

/* GET /signup
 *
 * This route prompts the user to sign up.
 *
 * The 'signup' view renders an HTML form, into which the user enters their
 * desired username and password.  When the user submits the form, a request
 * will be sent to the `POST /signup` route.
 */
router.get('/signup', function(req, res, next) {
  res.render('signup');
});

/* POST /signup
 *
 * This route creates a new user account.
 *
 * A desired username and password are submitted to this route via an HTML form,
 * which was rendered by the `GET /signup` route.  The password is hashed and
 * then a new user record is inserted into the database.  If the record is
 * successfully created, the user is logged in.
 */
router.post('/signup', function(req, res, next) {
  var salt = crypto.randomBytes(16);
  crypto.pbkdf2(req.body.password, salt, 310000, 32, 'sha256', function(err, hashedPassword) {
    if (err) { return next(err); }
    db.run('INSERT INTO users (username, hashed_password, salt) VALUES (?, ?, ?)', [
      req.body.username,
      hashedPassword,
      salt
    ], function(err) {
      if (err) { return next(err); }
      var user = {
        id: this.lastID,
        username: req.body.username
      };
      req.login(user, function(err) {
        if (err) { return next(err); }
        res.redirect('/');
      });
    });
  });
});

module.exports = router;
<commit_msg>Add comments.<commit_after>var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var crypto = require('crypto');
var db = require('../db');

/* Configure password authentication strategy.
 *
 * The `LocalStrategy` authenticates users by verifying a username and password.
 * The strategy parses the username and password from the request and calls the
 * `verify` function.
 *
 * The `verify` function queries the database for the user record and verifies
 * the password by hashing the password supplied by the user and comparing it to
 * the hashed password stored in the database.  If the comparison succeeds, the
 * user is authenticated; otherwise, not.
 */
passport.use(new LocalStrategy(function verify(username, password, cb) {
  db.get('SELECT rowid AS id, * FROM users WHERE username = ?', [ username ], function(err, row) {
    if (err) { return cb(err); }
    if (!row) { return cb(null, false, { message: 'Incorrect username or password.' }); }

    crypto.pbkdf2(password, row.salt, 310000, 32, 'sha256', function(err, hashedPassword) {
      if (err) { return cb(err); }
      if (!crypto.timingSafeEqual(row.hashed_password, hashedPassword)) {
        return cb(null, false, { message: 'Incorrect username or password.' });
      }
      return cb(null, row);
    });
  });
}));

// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session.  The
// typical implementation of this is as simple as supplying the user ID when
// serializing, and querying the user record by ID from the database when
// deserializing.
passport.serializeUser(function(user, cb) {
  process.nextTick(function() {
    cb(null, { id: user.id, username: user.username });
  });
});

passport.deserializeUser(function(user, cb) {
  process.nextTick(function() {
    return cb(null, user);
  });
});

var router = express.Router();

/* GET /login
 *
 * This route prompts the user to log in.
 *
 * The 'login' view renders an HTML form, into which the user enters their
 * username and password.  When the user submits the form, a request will be
 * sent to the `POST /login/password` route.
 */
router.get('/login', function(req, res, next) {
  res.render('login');
});

/* POST /login/password
 *
 * This route authenticates the user by verifying a username and password.
 *
 * A username and password are submitted to this route via an HTML form, which
 * was rendered by the `GET /login` route.  The username and password is
 * authenticated using the `local` strategy.  The strategy will parse the
 * username and password from the request and call the `verify` function.
 *
 * Upon successful authentication, a login session will be established.  As the
 * user interacts with the app, by clicking links and submitting forms, the
 * subsequent requests will be authenticated by verifying the session.
 *
 * When authentication fails, the user will be re-prompted to login and shown
 * a message informing them of what went wrong.
 */
router.post('/login/password', passport.authenticate('local', {
  successReturnToOrRedirect: '/',
  failureRedirect: '/login',
  failureMessage: true
}));

/* POST /logout
 *
 * This route logs the user out.
 */
router.post('/logout', function(req, res, next) {
  req.logout();
  res.redirect('/');
});

/* GET /signup
 *
 * This route prompts the user to sign up.
 *
 * The 'signup' view renders an HTML form, into which the user enters their
 * desired username and password.  When the user submits the form, a request
 * will be sent to the `POST /signup` route.
 */
router.get('/signup', function(req, res, next) {
  res.render('signup');
});

/* POST /signup
 *
 * This route creates a new user account.
 *
 * A desired username and password are submitted to this route via an HTML form,
 * which was rendered by the `GET /signup` route.  The password is hashed and
 * then a new user record is inserted into the database.  If the record is
 * successfully created, the user is logged in.
 */
router.post('/signup', function(req, res, next) {
  var salt = crypto.randomBytes(16);
  crypto.pbkdf2(req.body.password, salt, 310000, 32, 'sha256', function(err, hashedPassword) {
    if (err) { return next(err); }
    db.run('INSERT INTO users (username, hashed_password, salt) VALUES (?, ?, ?)', [
      req.body.username,
      hashedPassword,
      salt
    ], function(err) {
      if (err) { return next(err); }
      var user = {
        id: this.lastID,
        username: req.body.username
      };
      req.login(user, function(err) {
        if (err) { return next(err); }
        res.redirect('/');
      });
    });
  });
});

module.exports = router;
<|endoftext|>


<commit_before>import Command from './Command.js';

/**
 * Table Command
 */
export default class TableCommand extends Command {
    /**
     * @inheritDoc
     */
    execute() {
        let rows = this.editor.window.prompt('Rows');

        if (isNaN(rows) || rows <= 0) {
            return;
        }

        let cols = this.editor.window.prompt('Cols');

        if (isNaN(cols) || cols <= 0) {
            return;
        }

        const figure = this.editor.document.createElement('figure');
        const table = this.editor.document.createElement('table');
        const figcaption = this.editor.document.createElement('figcaption');

        figure.classList.add('table');
        figure.appendChild(table);
        figure.appendChild(figcaption);

        ['thead', 'tbody', 'tfoot'].forEach(section => {
            const item = this.editor.document.createElement(section);
            const cell = section === 'thead' ? 'th' : 'td';
            const r = section === 'tbody' ? rows : 1;
            let tr;

            table.appendChild(item);

            for (let i = 0; i < r; i++) {
                tr = this.editor.document.createElement('tr');
                item.appendChild(tr);

                for (let j = 0; j < cols; ++j) {
                    tr.appendChild(this.editor.document.createElement(cell));
                }
            }
        });

        this.editor.insert(figure);
    }
}
<commit_msg>Use const<commit_after>import Command from './Command.js';

/**
 * Table Command
 */
export default class TableCommand extends Command {
    /**
     * @inheritDoc
     */
    execute() {
        const rows = this.editor.window.prompt('Rows');

        if (isNaN(rows) || rows <= 0) {
            return;
        }

        const cols = this.editor.window.prompt('Cols');

        if (isNaN(cols) || cols <= 0) {
            return;
        }

        const figure = this.editor.document.createElement('figure');
        const table = this.editor.document.createElement('table');
        const figcaption = this.editor.document.createElement('figcaption');

        figure.classList.add('table');
        figure.appendChild(table);
        figure.appendChild(figcaption);

        ['thead', 'tbody', 'tfoot'].forEach(section => {
            const item = this.editor.document.createElement(section);
            const cell = section === 'thead' ? 'th' : 'td';
            const r = section === 'tbody' ? rows : 1;
            let tr;

            table.appendChild(item);

            for (let i = 0; i < r; i++) {
                tr = this.editor.document.createElement('tr');
                item.appendChild(tr);

                for (let j = 0; j < cols; ++j) {
                    tr.appendChild(this.editor.document.createElement(cell));
                }
            }
        });

        this.editor.insert(figure);
    }
}
<|endoftext|>


<commit_before>var GoogleStrategy = require('passport-google').Strategy;
var User = require('../models/user').User;

module.exports.setupAuth = function(app, passport) {
  passport.serializeUser(function(user, done) {
    done(null, user._id);
  });

  passport.deserializeUser(function(obj, done) {
    User.findOne({ _id: obj }, function(err, result) {
      done(err, result);
    });
  });

  function processAuth(identifier, profile, done) {
    User.findOne({ openid: identifier }, function(err, result) {
      if (result == null) {
        var user = new User({
          openid: identifier,
          name: profile.displayName,
          email: profile.emails[0].value,
          createdAt: Date.now()
        });
        user.save(function(err, user) {
          if (err) {
            throw err;
          } else {
            done(err, user);
          }
        });
      } else {
        done(err, result);
      }
    });
  }

  passport.use(new GoogleStrategy({
    returnURL: app.realm + 'auth/google/return',
    realm: app.realm
  }, function(identifier, profile, done) {
    identifier = 'gl-' + identifier.substr(identifier.lastIndexOf('id=') + 3);
    processAuth(identifier, profile, done);
  }));

  app.get('/login', function(req, res) {
    res.redirect('/auth/google');
  })

  app.get('/auth/google', passport.authenticate('google'), function(req, res) {
    res.send('Unknown failure.');
  });

  app.get('/auth/google/return', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
    res.redirect('/');
  });
};<commit_msg>Add logout<commit_after>var GoogleStrategy = require('passport-google').Strategy;
var User = require('../models/user').User;

module.exports.setupAuth = function(app, passport) {
  passport.serializeUser(function(user, done) {
    done(null, user._id);
  });

  passport.deserializeUser(function(obj, done) {
    User.findOne({ _id: obj }, function(err, result) {
      done(err, result);
    });
  });

  function processAuth(identifier, profile, done) {
    User.findOne({ openid: identifier }, function(err, result) {
      if (result == null) {
        var user = new User({
          openid: identifier,
          name: profile.displayName,
          email: profile.emails[0].value,
          createdAt: Date.now()
        });
        user.save(function(err, user) {
          if (err) {
            throw err;
          } else {
            done(err, user);
          }
        });
      } else {
        done(err, result);
      }
    });
  }

  passport.use(new GoogleStrategy({
    returnURL: app.realm + 'auth/google/return',
    realm: app.realm
  }, function(identifier, profile, done) {
    identifier = 'gl-' + identifier.substr(identifier.lastIndexOf('id=') + 3);
    processAuth(identifier, profile, done);
  }));

  app.get('/auth/google', passport.authenticate('google'), function(req, res) {
    res.send('Unknown failure.');
  });

  app.get('/auth/google/return', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
    res.redirect('/');
  });

  app.get('/login', function(req, res) {
    res.redirect('/auth/google');
  })

  app.get('/logout', function(req, res) {
    req.logOut();
    res.redirect('/');
  })
};<|endoftext|>


<commit_before>import Immutable from 'seamless-immutable'

export default {
    name: 'todos',
    initialState: Immutable({ todos: [] }),

    eventHandlers: {
        TodoAdded: (state, event) => (state.setIn(['todos'], [{
            aggregateId: event.aggregateId,
            completed: event.payload.completed,
            text: event.payload.text
        }].concat(state.todos))),
        TodoDeleted: (state, event) => state.setIn(['todos'], state.todos.filter(item => item.aggregateId !== event.aggregateId)),
        TodoEdited: (state, event) => state.setIn(['todos'], state.todos.map(todo =>
            todo.aggregateId === event.aggregateId
                ? { ...todo, text: action.text }
                : todo
        )),
        TodoCompleted: (state, event) => state.setIn(['todos'], state.todos.map(todo =>
            todo.aggregateId === event.aggregateId
                ? { ...todo, completed: !todo.completed }
                : todo
        ))
    }
};
<commit_msg>small fix<commit_after>import Immutable from 'seamless-immutable'

export default {
    name: 'todos',
    initialState: Immutable({ todos: [] }),

    eventHandlers: {
        TodoAdded: (state, event) => (state.setIn(['todos'], [{
            aggregateId: event.aggregateId,
            completed: event.payload.completed,
            text: event.payload.text
        }].concat(state.todos))),
        TodoDeleted: (state, event) => state.setIn(['todos'], state.todos.filter(item => item.aggregateId !== event.aggregateId)),
        TodoEdited: (state, event) => state.setIn(['todos'], state.todos.map(todo =>
            todo.aggregateId === event.aggregateId
                ? { ...todo, text: event.text }
                : todo
        )),
        TodoCompleted: (state, event) => state.setIn(['todos'], state.todos.map(todo =>
            todo.aggregateId === event.aggregateId
                ? { ...todo, completed: !todo.completed }
                : todo
        ))
    }
};
<|endoftext|>


<commit_before>'use strict'

define(['angular', 'underscore'], function (angular, _) {
  var controller = function ($rootScope, $scope, $log, group, $parse) {
    $parse('current.group').assign($scope, group)

    $scope.$watch('current.group._id.$oid', function (id) {
      $scope.focus = id ? 1 : 0
    })
  }

  controller.resolve = {
    group: function ($rootScope, Restangular) {
      var id = $rootScope.$eval('session.username')
      if (id) {
        return Restangular.one('groups', id).get()
      }
    }
  }

  return controller
})
<commit_msg>History support.<commit_after>'use strict'

define(['angular', 'underscore'], function (angular, _) {
  var controller = function ($rootScope, $scope, $log, group, $parse, $location) {
    $parse('current.group').assign($scope, group)

    $scope.$watch('current.group._id.$oid', function (id) {
      $scope.focus = id ? 1 : 0
    })

    $scope.$watch('focus', function (focus) {
      $location.search('s', focus)
    })

    $scope.$on('$routeUpdate', function () {
      $scope.focus = $location.search().s
    })
  }

  controller.resolve = {
    group: function ($rootScope, Restangular) {
      var id = $rootScope.$eval('session.username')
      if (id) {
        return Restangular.one('groups', id).get()
      }
    }
  }

  return controller
})
<|endoftext|>


<commit_before>class Annotation {
    constructor() {
        this.value = null;
    }

    value() { return this.value; }

    set(name, value) { this[name] = value; }
}

module.exports = Annotation;<commit_msg>Major Changes to Internal Structure<commit_after>class Annotation {
    constructor() {
        this.value = null;
    }

    value() { return this.value; }

    set(name, value) {
        if (name !== "value" && typeof this[name] !== "function") {
            throw new Error("Invalid Argument")
        } else {
            this[name] = value;
        }
    }
}

module.exports = Annotation;<|endoftext|>


<commit_before>var testRunner = require('./testRunner');
var testReporter = require('./reporters/nodeTestReporter');
var testConfig = require('./testConfig')();
var testSuiteGenerator = require('./testSuiteGenerator');
var CSVFormatter = require('./formatter/CSVFormatter');

var models = testConfig.models;
var formats = testConfig.formats;
var tests = testConfig.get;
var suite = testConfig.suite;

var TESTS = {
    'scrollGallery': tests.scrollGallery,
    'complex': tests.complex
};
suite.tests = testSuiteGenerator({
    iterations: 3,
    formats: ['Value'],
    tests: TESTS,
    models: {
        modelWithSource: models.modelWithSource
    }
});
testRunner(suite, 'node ' + process.version, CSVFormatter.pipe(CSVFormatter.toTable, testReporter));
<commit_msg>the beginning testing of the two<commit_after>var testRunner = require('./testRunner');
var testReporter = require('./reporters/nodeTestReporter');
var testConfig = require('./testConfig')();
var testSuiteGenerator = require('./testSuiteGenerator');
var CSVFormatter = require('./formatter/CSVFormatter');

var models = testConfig.models;
var formats = testConfig.formats;
var tests = testConfig.get;
var suite = testConfig.suite;

var TESTS = {
    'scrollGallery': tests.scrollGallery,
    'complex': tests.complex
};
suite.tests = testSuiteGenerator({
    iterations: 10,
    formats: ['JSON']
});
testRunner(suite, 'node ' + process.version, CSVFormatter.pipe(CSVFormatter.toTable, testReporter));
<|endoftext|>


<commit_before><commit_msg>Added spaces after icons<commit_after><|endoftext|>


<commit_before><commit_msg>index bug fix<commit_after><|endoftext|>


<commit_before>// react plugin - https://github.com/yannickcr/eslint-plugin-react

'use strict';

module.exports = {
    'plugins': [
        'react',
    ],
    'ecmaFeatures': {
        'jsx': true,
    },
    'rules': {
        // prevent missing displayName in a React component definition
        'react/display-name': 0,
        // forbid certain propTypes (forbid-prop-types)
        'react/forbid-prop-types': 0,
        // enforce boolean attributes notation in JSX
        'react/jsx-boolean-value': [2, 'never'],
        // validate closing bracket location in JSX
        'react/jsx-closing-bracket-location': [2, 'after-props'],
        // enforce or disallow spaces inside of curly braces in JSX attributes
        'react/jsx-curly-spacing': [2, 'always'],
        // enforce or disallow spaces around equal signs in JSX attributes
        'react/jsx-equals-spacing': [2, 'never'],
        // ensure correct position of the first property.
        'react/jsx-first-prop-new-line': 0,
        // enforce event handler naming conventions in JSX
        'react/jsx-handler-names': [2, {
            'eventHandlerPrefix': '_handle',
            'eventHandlerPropPrefix': 'on',
        }],
        // validate props indentation in JSX
        'react/jsx-indent-props': [2, 4],
        // validate JSX indentation
        'react/jsx-indent': [2, 4],
        // detect missing key prop
        'react/jsx-key': 1,
        // limit maximum of props on a single line in JSX
        'react/jsx-max-props-per-line': 0,
        // no .bind() or Arrow Functions in JSX Props
        'react/jsx-no-bind': [2, { 'allowArrowFunctions': true }],
        // prevent duplicate props in JSX
        'react/jsx-no-duplicate-props': 0,
        // prevent usage of unwrapped JSX strings
        'react/jsx-no-literals': 0,
        // disallow undeclared variables in JSX
        'react/jsx-no-undef': 2,
        // enforce PasalCase for user-defined JSX components
        'react/jsx-pascal-case': 2,
        // enforce props alphabetical sorting
        'react/jsx-sort-props': 0,
        // prevent React to be incorrectly marked as unused
        'react/jsx-uses-react': 2,
        // prevent variables used in JSX to be incorrectly marked as unused
        'react/jsx-uses-vars': 2,
        // prevent usage of dangerous JSX properties
        'react/no-danger': 0,
        // prevent usage of deprecated methods
        'react/no-deprecated': 1,
        // prevent usage of setState in componentDidMount
        'react/no-did-mount-set-state': [2, 'allow-in-func'],
        // prevent usage of setState in componentDidUpdate
        'react/no-did-update-set-state': [2, 'allow-in-func'],
        // prevent direct mutation of this.state
        'react/no-direct-mutation-state': 1,
        // prevent usage of isMounted
        'react/no-is-mounted': 2,
        // prevent multiple component definition per file
        'react/no-multi-comp': 2,
        // prevent usage of setState
        'react/no-set-state': 1,
        // prevent usage of unknown DOM property
        'react/no-unknown-property': 2,
        // require ES6 class declarations over React.createClass
        'react/prefer-es6-class': [2, 'always'],
        // enforce stateless components to be written as a pure function
        'react/prefer-stateless-function': 0,
        // prevent missing props validation in a React component definition
        'react/prop-types': 2,
        // prevent missing React when using JSX
        'react/react-in-jsx-scope': 2,
        // restrict file extensions that may be required
        'react/require-extension': 0,
        // enforce ES5 or ES6 class for returning value in render function
        'react/require-render-return': 2,
        // prevent extra closing tags for components without children
        'react/self-closing-comp': 2,
        // enforce component methods order
        'react/sort-comp': [2, {
            'order': [
                'lifecycle',
                '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/',
                'render',
                '/^render.+$/',
                'everything-else',
                '/^_?handle/',
            ],
        }],
        // enforce propTypes declarations alphabetical sorting
        'react/sort-prop-types': 0,
        // prevent missing parentheses around multilines JSX
        'react/wrap-multilines': [2, {
            'declaration': true,
            'assignment': true,
            'return': true,
        }],
    },
};
<commit_msg>Fix deprecated rules.<commit_after>// react plugin - https://github.com/yannickcr/eslint-plugin-react

'use strict';

module.exports = {
    'plugins': [
        'react',
    ],
    'ecmaFeatures': {
        'jsx': true,
    },
    'rules': {
        // prevent missing displayName in a React component definition
        'react/display-name': 0,
        // forbid certain propTypes (forbid-prop-types)
        'react/forbid-prop-types': 0,
        // enforce boolean attributes notation in JSX
        'react/jsx-boolean-value': [2, 'never'],
        // validate closing bracket location in JSX
        'react/jsx-closing-bracket-location': [2, 'after-props'],
        // enforce or disallow spaces inside of curly braces in JSX attributes
        'react/jsx-curly-spacing': [2, 'always'],
        // enforce or disallow spaces around equal signs in JSX attributes
        'react/jsx-equals-spacing': [2, 'never'],
        // ensure correct position of the first property.
        'react/jsx-first-prop-new-line': 0,
        // enforce event handler naming conventions in JSX
        'react/jsx-handler-names': [2, {
            'eventHandlerPrefix': '_handle',
            'eventHandlerPropPrefix': 'on',
        }],
        // validate props indentation in JSX
        'react/jsx-indent-props': [2, 4],
        // validate JSX indentation
        'react/jsx-indent': [2, 4],
        // detect missing key prop
        'react/jsx-key': 1,
        // limit maximum of props on a single line in JSX
        'react/jsx-max-props-per-line': 0,
        // no .bind() or Arrow Functions in JSX Props
        'react/jsx-no-bind': [2, { 'allowArrowFunctions': true }],
        // prevent duplicate props in JSX
        'react/jsx-no-duplicate-props': 0,
        // prevent usage of unwrapped JSX strings
        'react/jsx-no-literals': 0,
        // disallow undeclared variables in JSX
        'react/jsx-no-undef': 2,
        // enforce PasalCase for user-defined JSX components
        'react/jsx-pascal-case': 2,
        // enforce props alphabetical sorting
        'react/jsx-sort-props': 0,
        // prevent React to be incorrectly marked as unused
        'react/jsx-uses-react': 2,
        // prevent variables used in JSX to be incorrectly marked as unused
        'react/jsx-uses-vars': 2,
        // prevent missing parentheses around multilines JSX
        'react/jsx-wrap-multilines': [2, {
            'declaration': true,
            'assignment': true,
            'return': true,
        }],
        // prevent usage of dangerous JSX properties
        'react/no-danger': 0,
        // prevent usage of deprecated methods
        'react/no-deprecated': 1,
        // prevent usage of setState in componentDidMount
        'react/no-did-mount-set-state': [2],
        // prevent usage of setState in componentDidUpdate
        'react/no-did-update-set-state': [2],
        // prevent direct mutation of this.state
        'react/no-direct-mutation-state': 1,
        // prevent usage of isMounted
        'react/no-is-mounted': 2,
        // prevent multiple component definition per file
        'react/no-multi-comp': 2,
        // prevent usage of setState
        'react/no-set-state': 1,
        // prevent usage of unknown DOM property
        'react/no-unknown-property': 2,
        // require ES6 class declarations over React.createClass
        'react/prefer-es6-class': [2, 'always'],
        // enforce stateless components to be written as a pure function
        'react/prefer-stateless-function': 0,
        // prevent missing props validation in a React component definition
        'react/prop-types': 2,
        // prevent missing React when using JSX
        'react/react-in-jsx-scope': 2,
        // restrict file extensions that may be required
        'react/require-extension': 0,
        // enforce ES5 or ES6 class for returning value in render function
        'react/require-render-return': 2,
        // prevent extra closing tags for components without children
        'react/self-closing-comp': 2,
        // enforce component methods order
        'react/sort-comp': [2, {
            'order': [
                'lifecycle',
                '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/',
                'render',
                '/^render.+$/',
                'everything-else',
                '/^_?handle/',
            ],
        }],
        // enforce propTypes declarations alphabetical sorting
        'react/sort-prop-types': 0,
    },
};
<|endoftext|>


<commit_before>/**
 * Modified ESLint Possible Errors.
 * https://github.com/yannickcr/eslint-plugin-react
 */
module.exports = {
    "plugins": ["react"],
    "parserOptions": {
        "ecmaFeatures": { "jsx": true }
    },
    "rules": {
        "react/display-name": "off",
        "react/forbid-component-props": "off",
        "react/forbid-elements": "off",
        "react/forbid-prop-types": ["error", { "forbid": ["any", "array", "object"] }],
        "react/forbid-foreign-prop-types": "error",
        "react/no-array-index-key": "error",
        "react/no-children-prop": "error",
        "react/no-danger": "off",
        "react/no-danger-with-children": "error",
        "react/no-deprecated": "error",
        "react/no-did-mount-set-state": "error",
        "react/no-did-update-set-state": "error",
        "react/no-direct-mutation-state": "error",
        "react/no-find-dom-node": "error",
        "react/no-is-mounted": "error",
        "react/no-multi-comp": ["error", { "ignoreStateless": true }],
        "react/no-render-return-value": "error",
        "react/no-set-state": "off",
        "react/no-string-refs": "error",
        "react/no-unescaped-entities": "error",
        "react/no-unknown-property": "error",
        "react/no-unused-prop-types": ["warn", { "customValidators": [], "skipShapeProps": true }],
        "react/no-will-update-set-state": "error",
        "react/prefer-es6-class": ["error", "always"],
        "react/prefer-stateless-function": ["error", { "ignorePureComponents": true }],
        "react/prop-types": ["error", { "ignore": ["children"], "customValidators": [] }],
        "react/react-in-jsx-scope": "error",
        "react/require-default-props": "error",
        "react/require-optimization": "off",
        "react/require-render-return": "error",
        "react/self-closing-comp": "error",
        "react/sort-comp": ["error", {
            "order": [
                "static-methods",
                "lifecycle",
                "/^on.+$/",
                "/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/",
                "everything-else",
                "/^render.+$/",
                "render"
            ]
        }],
        "react/sort-prop-types": "off",
        "react/style-prop-object": "error",
        "react/void-dom-elements-no-children": "error",

        "react/jsx-boolean-value": ["error", "never"],
        "react/jsx-closing-bracket-location": ["error", "line-aligned"],
        "react/jsx-curly-spacing": ["error", "never", { "allowMultiline": true }],
        "react/jsx-equals-spacing": ["error", "never"],
        "react/jsx-filename-extension": ["error", { "extensions": [".js", ".jsx"] }],
        "react/jsx-first-prop-new-line": ["error", "multiline"],
        "react/jsx-handler-names": "off",
        "react/jsx-indent": ["error", 4],
        "react/jsx-indent-props": ["error", 4],
        "react/jsx-key": "off",
        "react/jsx-max-props-per-line": "off",
        "react/jsx-no-bind": ["error", {
            "ignoreRefs": true,
            "allowArrowFunctions": true,
            "allowBind": false
        }],
        "react/jsx-no-comment-textnodes": "error",
        "react/jsx-no-duplicate-props": "error",
        "react/jsx-no-literals": "off",
        "react/jsx-no-target-blank": "error",
        "react/jsx-no-undef": "error",
        "react/jsx-pascal-case": "error",
        "react/jsx-sort-props": "off",
        "react/jsx-tag-spacing": ["error", {
            "closingSlash": "never",
            "beforeSelfClosing": "always",
            "afterOpening": "never"
        }],
        "react/jsx-uses-react": "error",
        "react/jsx-uses-vars": "error",
        "react/jsx-wrap-multilines": ["error", {
            "arrow": true,
            "assignment": true,
            "declaration": true,
            "return": true
        }]
    }
};
<commit_msg>upgrade to eslint-plugin-react 7.5.1<commit_after>/**
 * Modified ESLint Possible Errors.
 * https://github.com/yannickcr/eslint-plugin-react
 */
module.exports = {
    "plugins": [
        "react"
    ],
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "rules": {
        "react/boolean-prop-naming": "error",
        "react/button-has-type": "error",
        "react/default-props-match-prop-types": "error",
        "react/destructuring-assignment": "off",
        "react/display-name": "off",
        "react/forbid-component-props": "off",
        "react/forbid-dom-props": "off",
        "react/forbid-elements": "off",
        "react/forbid-prop-types": ["error", { "forbid": ["any", "array", "object"] }],
        "react/forbid-foreign-prop-types": "error",
        "react/no-access-state-in-setstate": "error",
        "react/no-array-index-key": "error",
        "react/no-children-prop": "error",
        "react/no-danger": "off",
        "react/no-danger-with-children": "error",
        "react/no-deprecated": "error",
        "react/no-did-mount-set-state": "error",
        "react/no-did-update-set-state": "error",
        "react/no-direct-mutation-state": "error",
        "react/no-find-dom-node": "error",
        "react/no-is-mounted": "error",
        "react/no-multi-comp": ["error", { "ignoreStateless": true }],
        "react/no-redundant-should-component-update": "error",
        "react/no-render-return-value": "error",
        "react/no-set-state": "off",
        "react/no-typos": "error",
        "react/no-string-refs": "error",
        "react/no-this-in-sfc": "error",
        "react/no-unescaped-entities": "error",
        "react/no-unknown-property": "error",
        "react/no-unused-prop-types": ["warn", { "customValidators": [], "skipShapeProps": true }],
        "react/no-unused-state": "error",
        "react/no-will-update-set-state": "error",
        "react/prefer-es6-class": ["error", "always"],
        "react/prefer-stateless-function": ["error", { "ignorePureComponents": true }],
        "react/prop-types": ["error", { "ignore": ["children"], "customValidators": [] }],
        "react/react-in-jsx-scope": "error",
        "react/require-default-props": "error",
        "react/require-optimization": "off",
        "react/require-render-return": "error",
        "react/self-closing-comp": "error",
        "react/sort-comp": ["error", {
            "order": [
                "static-methods",
                "lifecycle",
                "/^on.+$/",
                "/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/",
                "everything-else",
                "/^render.+$/",
                "render"
            ]
        }],
        "react/sort-prop-types": "off",
        "react/style-prop-object": "error",
        "react/void-dom-elements-no-children": "error",

        "react/jsx-boolean-value": ["error", "never"],
        "react/jsx-closing-bracket-location": ["error", "line-aligned"],
        "react/jsx-closing-tag-location": "error",
        "react/jsx-curly-spacing": ["error", "never", { "allowMultiline": true }],
        "react/jsx-equals-spacing": ["error", "never"],
        "react/jsx-filename-extension": ["error", { "extensions": [".js", ".jsx"] }],
        "react/jsx-first-prop-new-line": ["error", "multiline"],
        "react/jsx-handler-names": "off",
        "react/jsx-indent": ["error", 4],
        "react/jsx-indent-props": ["error", 4],
        "react/jsx-key": "off",
        "react/jsx-max-props-per-line": "off",
        "react/jsx-no-bind": ["error", {
            "ignoreRefs": true,
            "allowArrowFunctions": true,
            "allowBind": false
        }],
        "react/jsx-no-comment-textnodes": "error",
        "react/jsx-no-duplicate-props": "error",
        "react/jsx-no-literals": "off",
        "react/jsx-no-target-blank": "error",
        "react/jsx-no-undef": "error",
        "react/jsx-one-expression-per-line": "error",
        "react/jsx-curly-brace-presence": ["error", { "props": "ignore", "children": "always" }],
        "react/jsx-pascal-case": "error",
        "react/jsx-sort-default-props": "off",
        "react/jsx-sort-props": "off",
        "react/jsx-tag-spacing": ["error", {
            "afterOpening": "never",
            "beforeClosing": "never",
            "beforeSelfClosing": "always",
            "closingSlash": "never",
        }],
        "react/jsx-uses-react": "error",
        "react/jsx-uses-vars": "error",
        "react/jsx-wrap-multilines": ["error", {
            "arrow": true,
            "assignment": true,
            "declaration": true,
            "return": true
        }]
    }
};
<|endoftext|>


<commit_before>module.exports = {
  rules: {
    indent: [2, 2],
    'brace-style': [
      2, '1tbs', {allowSingleLine: true}
    ],
    quotes: [
      2, 'single', 'avoid-escape'
    ],
    camelcase: [2, {
      properties: 'never'
    }],
    'comma-spacing': [2, {
      before: false,
      after: true
    }],
    'comma-style': [2, 'last'],
    'eol-last': 2,
    'func-names': 0,
    'key-spacing': [2, {
      beforeColon: false,
      afterColon: true
    }],
    'new-cap': 1,
    'no-multiple-empty-lines': [2, {
      max: 2
    }],
    'no-nested-ternary': 2,
    'no-new-object': 2,
    'no-spaced-func': 2,
    'no-trailing-spaces': 2,
    'no-extra-parens': 2,
    'no-underscore-dangle': 0,
    'one-var': [2, 'never'],
    'padded-blocks': [2, 'never'],
    semi: [2, 'always'],
    'semi-spacing': [2, {
      before: false,
      after: true
    }],
    'space-after-keywords': 2,
    'space-before-blocks': 2,
    'space-before-function-paren': [2, 'always'],
    'space-infix-ops': 1,
    'space-return-throw-case': 2,
    'spaced-comment': 2
  }
};
<commit_msg>ignore extra parenthesis except on functions<commit_after>module.exports = {
  rules: {
    indent: [2, 2],
    'brace-style': [
      2, '1tbs', {allowSingleLine: true}
    ],
    quotes: [
      2, 'single', 'avoid-escape'
    ],
    camelcase: [2, {
      properties: 'never'
    }],
    'comma-spacing': [2, {
      before: false,
      after: true
    }],
    'comma-style': [2, 'last'],
    'eol-last': 2,
    'func-names': 0,
    'key-spacing': [2, {
      beforeColon: false,
      afterColon: true
    }],
    'new-cap': 1,
    'no-multiple-empty-lines': [2, {
      max: 2
    }],
    'no-nested-ternary': 2,
    'no-new-object': 2,
    'no-spaced-func': 2,
    'no-trailing-spaces': 2,
    'no-extra-parens': [2, 'functions'],
    'no-underscore-dangle': 0,
    'one-var': [2, 'never'],
    'padded-blocks': [2, 'never'],
    semi: [2, 'always'],
    'semi-spacing': [2, {
      before: false,
      after: true
    }],
    'space-after-keywords': 2,
    'space-before-blocks': 2,
    'space-before-function-paren': [2, 'always'],
    'space-infix-ops': 1,
    'space-return-throw-case': 2,
    'spaced-comment': 2
  }
};
<|endoftext|>


<commit_before>"use strict";

// jshint maxparams: 3

exports.traverseArrayImpl = function () {
  function array1(a) {return [a];}

  function array2(a) {
    return function (b) {return [a, b];};
  }

  function concat2(xs) {
    return function (ys) {return xs.concat(ys);};
  }

  return function (apply) {
    return function (map) {
      return function (pure) {
        return function (f) {
          return function (array) {
            function go(bot, top) {
              switch (top - bot) {
              case 0: return pure([]);
              case 1: return map(array1)(f(array[bot]));
              case 2: return apply(map(array2)(f(array[bot])))(f(array[bot + 1]));
              default:
                var pivot = bot + Math.floor((top - bot) / 4) * 2;
                return apply(map(concat2)(go(bot, pivot)))(go(pivot, top));
              }
            }
            return go(0, array.length);
          };
        };
      };
    };
  };
}();
<commit_msg>Fix pivot selection<commit_after>"use strict";

// jshint maxparams: 3

exports.traverseArrayImpl = function () {
  function array1(a) {return [a];}

  function array2(a) {
    return function (b) {return [a, b];};
  }

  function concat2(xs) {
    return function (ys) {return xs.concat(ys);};
  }

  return function (apply) {
    return function (map) {
      return function (pure) {
        return function (f) {
          return function (array) {
            function go(bot, top) {
              switch (top - bot) {
              case 0: return pure([]);
              case 1: return map(array1)(f(array[bot]));
              case 2: return apply(map(array2)(f(array[bot])))(f(array[bot + 1]));
              default:
                var pivot = Math.floor((top + bot) / 2);
                return apply(map(concat2)(go(bot, pivot)))(go(pivot, top));
              }
            }
            return go(0, array.length);
          };
        };
      };
    };
  };
}();
<|endoftext|>


<commit_before>import React from 'react';
import Panel from 'react-bootstrap/lib/Panel';
import Col from 'react-bootstrap/lib/Col';
import Row from 'react-bootstrap/lib/Row';
import Alert from 'react-bootstrap/lib/Alert';
import WorkItem from './WorkItem';
import GraphDisplay from './GraphDisplay';
import { Link, IndexLink } from 'react-router';
import './details.css';

export const DetailsGraph = React.createClass({
  contextTypes: {
    graph: React.PropTypes.object.isRequired,
  },

  getInitialState() {
    return {
      selectedNode: 'linux32-builds-tier2',
    };
  },

  handleNodeSelected(name) {
    this.setState({ selectedNode: name });
  },

  renderNodeInfo() {
    const node = this.context.graph.byName[this.state.selectedNode];

    if (!node) {
      return (
        <Alert bsStyle="info">

Select a node in the graph to see details about it

        </Alert>
      );
    }

    return (

{node.name}

{node.title}

        {node.description ?
{node.description}
 : null}

State

{node.state}

          {node.assigned ?
Assigned:
 : null}
          {node.assigned ?
{node.assigned}
 : null}
          {node.external ?
External:
 : null}
          {node.external ?
yes
 : null}
          {node.milestone ?
Milestone:
 : null}
          {node.milestone ?
yes
 : null}
          {node.bug ?
Bug:
 : null}
          {node.bug ? (

              <a href={`https://bugzilla.mozilla.org/show_bug.cgi?id=${node.bug}`} target="_blank">
                #{node.bug}

          ) : null}

Dependencies

              {node.dependencies.map(dep =>
{dep}
)}

    );
  },

  render() {
    return (
      <Row>
        <Col className="hidden-xs hidden-sm" md={7}>
          <GraphDisplay
            root={this.props.params.rootWorkItem}
            onSelect={this.handleNodeSelected} />
        </Col>
        <Col className="hidden-md hidden-lg" xs={6}>

            {this.context.graph.nodes.map(node => (

 this.handleNodeSelected(node.name)}>
                {node.name}

            ))}

        </Col>
        <Col xs={6} md={5}>
          {this.renderNodeInfo()}
        </Col>
      </Row>
    );
  },
});

export const DetailsKanban = React.createClass({
  contextTypes: {
    graph: React.PropTypes.object.isRequired,
  },

  getInitialState() {
    return {
      visible: {
        blocked: false,
        inProgress: true,
        ready: true,
        done: false,
      },
    };
  },

  toggleVisible(state) {
    const update = {};
    update[state] = !this.state.visible[state];
    this.setState({
      visible: { ...this.state.visible, ...update },
    });
  },

  render() {
    const graph = this.context.graph;
    const distances = graph.rootDistances(this.props.params.rootWorkItem);

    const byState = { blocked: [], inProgress: [], ready: [], done: [] };
    graph.nodes.forEach(node => byState[node.state].push(node));

    const listItems = (state, title) => {
      const visible = this.state.visible[state];
      const nodes = byState[state];

      // sort the longest distances first
      nodes.sort((a, b) => distances[b.name] - distances[a.name]);

      const header = (

 this.toggleVisible(state)}>
          {title}

      );

      const className = `wi-${state}`;

      if (!nodes.length) {
        return (
          <Panel collapsible expanded={visible} header={header}>
            no items
          </Panel>
        );
      }

      return <Panel collapsible className={className} expanded={visible} header={header}>
        <Row>
          {
            nodes.map(node => (
              <Col key={node.name} xs={12}>
                <WorkItem node={node} />
              </Col>
            ))
          }
        </Row>
      </Panel>;
    };
    return

      {listItems('blocked', 'Blocked')}
      {listItems('inProgress', 'In Progress')}
      {listItems('ready', 'Ready')}
      {listItems('done', 'Done')}

;
  },
});

const Tab = React.createClass({
  // see http://brandonlehr.com/bootstrap-tabs-react-router-and-the-active-class/
  contextTypes: {
    router: React.PropTypes.object.isRequired,
  },

  propTypes: {
    to: React.PropTypes.string,
    onlyActiveOnIndex: React.PropTypes.bool,
    children: React.PropTypes.node,
  },

  render() {
    const isActive = this.context.router.isActive(this.props.to, this.props.onlyActiveOnIndex);
    const LinkComponent = this.props.onlyActiveOnIndex ? IndexLink : Link;
    const className = isActive ? 'active' : '';

    return (

        <LinkComponent to={this.props.to}>{this.props.children}</LinkComponent>

    );
  },
});

export const DetailsComponent = React.createClass({
  contextTypes: {
    graph: React.PropTypes.object.isRequired,
  },

  childContextTypes: {
    graph: React.PropTypes.object,
  },

  getChildContext() {
    // limit the graph to work items rooted at rootWorkItem and pass that along as
    // the graph context
    const graph = this.props.params.rootWorkItem === 'all' ?
      this.context.graph :
      this.context.graph.subgraph(this.props.params.rootWorkItem);
    return { graph };
  },

  render() {
    const root = `/details/${this.props.params.rootWorkItem}`;
    return (

            <Tab to={root} onlyActiveOnIndex>Graph</Tab>
            <Tab to={`${root}/kanban`}>Kanban</Tab>

          {this.props.children}

    );
  },
});

<commit_msg>default to no node selected (oops)<commit_after>import React from 'react';
import Panel from 'react-bootstrap/lib/Panel';
import Col from 'react-bootstrap/lib/Col';
import Row from 'react-bootstrap/lib/Row';
import Alert from 'react-bootstrap/lib/Alert';
import WorkItem from './WorkItem';
import GraphDisplay from './GraphDisplay';
import { Link, IndexLink } from 'react-router';
import './details.css';

export const DetailsGraph = React.createClass({
  contextTypes: {
    graph: React.PropTypes.object.isRequired,
  },

  getInitialState() {
    return {
      selectedNode: null,
    };
  },

  handleNodeSelected(name) {
    this.setState({ selectedNode: name });
  },

  renderNodeInfo() {
    const node = this.context.graph.byName[this.state.selectedNode];

    if (!node) {
      return (
        <Alert bsStyle="info">

Select a node in the graph to see details about it

        </Alert>
      );
    }

    return (

{node.name}

{node.title}

        {node.description ?
{node.description}
 : null}

State

{node.state}

          {node.assigned ?
Assigned:
 : null}
          {node.assigned ?
{node.assigned}
 : null}
          {node.external ?
External:
 : null}
          {node.external ?
yes
 : null}
          {node.milestone ?
Milestone:
 : null}
          {node.milestone ?
yes
 : null}
          {node.bug ?
Bug:
 : null}
          {node.bug ? (

              <a href={`https://bugzilla.mozilla.org/show_bug.cgi?id=${node.bug}`} target="_blank">
                #{node.bug}

          ) : null}

Dependencies

              {node.dependencies.map(dep =>
{dep}
)}

    );
  },

  render() {
    return (
      <Row>
        <Col className="hidden-xs hidden-sm" md={7}>
          <GraphDisplay
            root={this.props.params.rootWorkItem}
            onSelect={this.handleNodeSelected} />
        </Col>
        <Col className="hidden-md hidden-lg" xs={6}>

            {this.context.graph.nodes.map(node => (

 this.handleNodeSelected(node.name)}>
                {node.name}

            ))}

        </Col>
        <Col xs={6} md={5}>
          {this.renderNodeInfo()}
        </Col>
      </Row>
    );
  },
});

export const DetailsKanban = React.createClass({
  contextTypes: {
    graph: React.PropTypes.object.isRequired,
  },

  getInitialState() {
    return {
      visible: {
        blocked: false,
        inProgress: true,
        ready: true,
        done: false,
      },
    };
  },

  toggleVisible(state) {
    const update = {};
    update[state] = !this.state.visible[state];
    this.setState({
      visible: { ...this.state.visible, ...update },
    });
  },

  render() {
    const graph = this.context.graph;
    const distances = graph.rootDistances(this.props.params.rootWorkItem);

    const byState = { blocked: [], inProgress: [], ready: [], done: [] };
    graph.nodes.forEach(node => byState[node.state].push(node));

    const listItems = (state, title) => {
      const visible = this.state.visible[state];
      const nodes = byState[state];

      // sort the longest distances first
      nodes.sort((a, b) => distances[b.name] - distances[a.name]);

      const header = (

 this.toggleVisible(state)}>
          {title}

      );

      const className = `wi-${state}`;

      if (!nodes.length) {
        return (
          <Panel collapsible expanded={visible} header={header}>
            no items
          </Panel>
        );
      }

      return <Panel collapsible className={className} expanded={visible} header={header}>
        <Row>
          {
            nodes.map(node => (
              <Col key={node.name} xs={12}>
                <WorkItem node={node} />
              </Col>
            ))
          }
        </Row>
      </Panel>;
    };
    return

      {listItems('blocked', 'Blocked')}
      {listItems('inProgress', 'In Progress')}
      {listItems('ready', 'Ready')}
      {listItems('done', 'Done')}

;
  },
});

const Tab = React.createClass({
  // see http://brandonlehr.com/bootstrap-tabs-react-router-and-the-active-class/
  contextTypes: {
    router: React.PropTypes.object.isRequired,
  },

  propTypes: {
    to: React.PropTypes.string,
    onlyActiveOnIndex: React.PropTypes.bool,
    children: React.PropTypes.node,
  },

  render() {
    const isActive = this.context.router.isActive(this.props.to, this.props.onlyActiveOnIndex);
    const LinkComponent = this.props.onlyActiveOnIndex ? IndexLink : Link;
    const className = isActive ? 'active' : '';

    return (

        <LinkComponent to={this.props.to}>{this.props.children}</LinkComponent>

    );
  },
});

export const DetailsComponent = React.createClass({
  contextTypes: {
    graph: React.PropTypes.object.isRequired,
  },

  childContextTypes: {
    graph: React.PropTypes.object,
  },

  getChildContext() {
    // limit the graph to work items rooted at rootWorkItem and pass that along as
    // the graph context
    const graph = this.props.params.rootWorkItem === 'all' ?
      this.context.graph :
      this.context.graph.subgraph(this.props.params.rootWorkItem);
    return { graph };
  },

  render() {
    const root = `/details/${this.props.params.rootWorkItem}`;
    return (

            <Tab to={root} onlyActiveOnIndex>Graph</Tab>
            <Tab to={`${root}/kanban`}>Kanban</Tab>

          {this.props.children}

    );
  },
});

<|endoftext|>


<commit_before>/* regexBldg gets building name from ID
           Ex:  nrh-3-3071  => nrh
                fish-3-3050 => fish
   regexNum gets room # from ID
           Ex:  nrh-3-3071  => 3071
           fish-3-3050 => 3050
*/

var regexBldg = /([(a-zA-Z)])\w+/g,
    regexNum = /([^(a-zA-Z)\-])\w+/g;

// Used for convenience, but not neccesary
var $modalTitle = $('#map-modal .modal-title'),
    $modalBody = $("#map-modal .modal-body");

function updateModalTitle(title) {
    /*
    Gets the display modal ready with correct
    values, awaiting `display: block`.
    */
    $modalTitle.text(title);
}

function updateModalBody(html) {
    $modalBody.html("
" + html + "
");
}

function updateResidents(roomNum) {
    /*
    Uses onfloors w/ room # formatted for dictionary key
    to get and parse the given data. If room has 2 residents,
    2 are returned, with comma; if room has 1 resident, only
    one is returned; returns if room has no residents.
    */
    switch (roomNum) {
        case "3058":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Lounge");
            updateModalBody("No residents.");
            break;
        case "3098":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("User Center");
            updateModalBody("No residents.");
            break;
        case "3034":
        case "3048":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Server Room");
            var rtps = groups['rtp'];
            var rtpHTML = "";
            for (var i = 0; i < rtps.length; i++) {
              rtpHTML += rtps[i];
              if (i < rtps.length - 1) {
                rtpHTML += "
"
              }
            }
            updateModalBody(rtpHTML);
            break;
        case "3021":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Project Room");
            updateModalBody(eboard['Improvements']);
            break;
        case "3017":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Research Room");
            var threedeeayys = groups['3da'];
            var threedeeayyHTML = "";
            for (var i = 0; i < threedeeayys.length; i++) {
              threedeeayyHTML += threedeeayys[i];
              if (i < threedeeayys.length - 1) {
                threedeeayyHTML += "
"
              }
            }
            updateModalBody(threedeeayyHTML);
            break;
        case "3012":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Luser Center");
            updateModalBody("No residents.");
            break;
        case "3032":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Eboard Closet");
            updateModalBody(eboard['Financial']);
            break;
        case "3028":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Janitorial Closet");
            updateModalBody("Mike");
            break;
        case "3008":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Social Closet");
            updateModalBody(eboard['Social']);
            break;
        case "3120":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("SS Networking");
            updateModalBody("ssn@csh.rit.edu");
            break;
        case "3124":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Software Room");
            updateModalBody("No residents.");
            break;
        case "3950":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Elevator");
            updateModalBody("No residents.");
            break;
        case "3080":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Trash Room");
            updateModalBody("No residents.");
            break;
        case "3078":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Library");
            updateModalBody(eboard['History']);
            break;
        case "3082":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Kitchen");
            updateModalBody("Brandon Chiu");
            break;
        case "F%203961":
        case "3961":
        case "3960":
        case "3962":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Staircase");
            updateModalBody("No residents.");
            break;
        case "F%203023":
        case "F%203018":
        case "3047":
        case "3025":
        case "3075":
        case "3087":
        case "3115":
        case "3121":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Restroom");
        default:
            residents = onfloors[roomNum];
            if (typeof(residents) == 'undefined') {
              updateModalBody('No residents.');
            } else if (residents[1]) {
              updateModalBody(residents[0] + '
' + residents[1]);
            } else {
              updateModalBody(residents[0]);
            }
            break;
    }
}

function nrhOrFish(id) {
    /*
    Uses regex, checks if id starts with nrh or fish, or something else
    Example IDs:  nrh-3-3071  => isNrh
                  fish-3-3050 => isFish
                  sol-3-3011  => Neither
    */
    var bldg = id.match(regexBldg).toString(),
        num = id.match(regexNum).toString();
    if (bldg === "nrh") {
        $modalTitle.css('textTransform', 'uppercase');
        updateModalBody("Loading...");
        updateModalTitle(bldg + " " + num);
        updateResidents(num);
    } else if (bldg === "fish") {
        $modalTitle.css('textTransform', 'capitalize');
        updateModalBody("Loading...");
        updateModalTitle(bldg + " " + num);
        updateResidents('F ' + num);
    } else {
        console.log("ERROR: Room of id" + id + " is neither in NRH nor Fish");
    }
}

$('.room').click(function() {
    /*
    Uses jQuery click function,
    gets ID of clicked element
    and calls nrhOrFish w/ ID.
    */
    nrhOrFish(this.id);
});

$('#search-button').click(function(e) {
    e.preventDefault();
    query = $('#search').val().replace(/\s+/g, '-').toLowerCase();
    var bldg = query.match(regexBldg),
        num = query.match(regexNum);
        id = ('#' + bldg + "-3-" + num).toString();  // Concatenates the bldg name and room num to a searcheable ID
    if ((bldg == "nrh" || bldg == "fish") && ($(id).length)) {  // Checks if the building is NRH/Fish, and if the room exists on the map
        nrhOrFish(query);
        $('#map-modal').modal('show');
    }
    else {
        $('#search').attr('data-content', 'Room not found.\nExample searches: NRH 3071, Fish 3049').popover('show').popover('disable');
    }
});
<commit_msg>Update scripts.js<commit_after>/* regexBldg gets building name from ID
           Ex:  nrh-3-3071  => nrh
                fish-3-3050 => fish
   regexNum gets room # from ID
           Ex:  nrh-3-3071  => 3071
           fish-3-3050 => 3050
*/

var regexBldg = /([(a-zA-Z)])\w+/g,
    regexNum = /([^(a-zA-Z)\-])\w+/g;

// Used for convenience, but not neccesary
var $modalTitle = $('#map-modal .modal-title'),
    $modalBody = $("#map-modal .modal-body");

function updateModalTitle(title) {
    /*
    Gets the display modal ready with correct
    values, awaiting `display: block`.
    */
    $modalTitle.text(title);
}

function updateModalBody(html) {
    $modalBody.html("
" + html + "
");
}

function updateResidents(roomNum) {
    /*
    Uses onfloors w/ room # formatted for dictionary key
    to get and parse the given data. If room has 2 residents,
    2 are returned, with comma; if room has 1 resident, only
    one is returned; returns if room has no residents.
    */
    switch (roomNum) {
        case "3058":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Lounge");
            updateModalBody("No residents.");
            break;
        case "3098":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("User Center");
            updateModalBody("No residents.");
            break;
        case "3034":
        case "3048":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Server Room");
            var rtps = groups['rtp'];
            var rtpHTML = "";
            for (var i = 0; i < rtps.length; i++) {
              rtpHTML += rtps[i];
              if (i < rtps.length - 1) {
                rtpHTML += "
"
              }
            }
            updateModalBody(rtpHTML);
            break;
        case "3021":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Project Room");
            updateModalBody(eboard['Improvements']);
            break;
        case "3017":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Research Room");
            var threedeeayys = groups['3da'];
            var threedeeayyHTML = "";
            for (var i = 0; i < threedeeayys.length; i++) {
              threedeeayyHTML += threedeeayys[i];
              if (i < threedeeayys.length - 1) {
                threedeeayyHTML += "
"
              }
            }
            updateModalBody(threedeeayyHTML);
            break;
        case "3012":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Luser Center");
            updateModalBody("No residents.");
            break;
        case "3032":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Eboard Closet");
            updateModalBody(eboard['Financial']);
            break;
        case "3028":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Janitorial Closet");
            updateModalBody("Mike");
            break;
        case "3008":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Social Closet");
            updateModalBody(eboard['Social']);
            break;
        case "3120":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("SS Networking");
            updateModalBody("ssn@csh.rit.edu");
            break;
        case "3124":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Software Room");
            updateModalBody("No residents.");
            break;
        case "3950":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Elevator");
            updateModalBody("No residents.");
            break;
        case "3080":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Trash Room");
            updateModalBody("No residents.");
            break;
        case "3078":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Library");
            updateModalBody(eboard['History']);
            break;
        case "3082":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Kitchen");
            updateModalBody("Brandon Chiu");
            break;
        case "F%203961":
        case "3961":
        case "3960":
        case "3962":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Staircase");
            updateModalBody("No residents.");
            break;
        case "F%203023":
        case "F%203018":
        case "3047":
        case "3025":
        case "3075":
        case "3087":
        case "3115":
        case "3121":
            $modalTitle.css('textTransform', 'capitalize');
            updateModalTitle("Restroom");
        default:
            residents = onfloors[roomNum];
            if (typeof(residents) == 'undefined') {
              updateModalBody('No residents.');
            } else if (residents[1]) {
              updateModalBody(residents[0] + '
' + residents[1]);
            } else {
              updateModalBody(residents[0]);
            }
            break;
    }
}

function nrhOrFish(id) {
    /*
    Uses regex, checks if id starts with nrh or fish, or something else
    Example IDs:  nrh-3-3071  => isNrh
                  fish-3-3050 => isFish
                  sol-3-3011  => Neither
    */
    var bldg = id.match(regexBldg).toString(),
        num = id.match(regexNum).toString();
    if (bldg === "nrh") {
        $modalTitle.css('textTransform', 'uppercase');
        updateModalBody("Loading...");
        updateModalTitle(bldg + " " + num);
        updateResidents(num);
    } else if (bldg === "fish") {
        $modalTitle.css('textTransform', 'capitalize');
        updateModalBody("Loading...");
        updateModalTitle(bldg + " " + num);
        updateResidents('F ' + num);
    } else {
        console.log("ERROR: Room of id " + id + " is neither in NRH nor Fish");
    }
}

$('.room').click(function() {
    /*
    Uses jQuery click function,
    gets ID of clicked element
    and calls nrhOrFish w/ ID.
    */
    nrhOrFish(this.id);
});

$('#search-button').click(function(e) {
    e.preventDefault();
    query = $('#search').val().replace(/\s+/g, '-').toLowerCase();
    var bldg = query.match(regexBldg),
        num = query.match(regexNum);
        id = ('#' + bldg + "-3-" + num).toString();  // Concatenates the bldg name and room num to a searcheable ID
    if ((bldg == "nrh" || bldg == "fish") && ($(id).length)) {  // Checks if the building is NRH/Fish, and if the room exists on the map
        nrhOrFish(query);
        $('#map-modal').modal('show');
    }
    else {
        $('#search').attr('data-content', 'Room not found.\nExample searches: NRH 3071, Fish 3049').popover('show').popover('disable');
    }
});
<|endoftext|>


<commit_before>var vm = require("vm");
var _ = require("lodash");

// Usage:
// > var write = console.commands();
// >> var write = console.commands({verbose: true});

function executeJavascript(input, options) {
    if (input[0] !== ">" || input.length > 255) {
        return;
    }

    var startPos = input[1] === ">" ? 2 : 1;

    try {
         // Timeout set to a bit more than 1 screen frame duration
        return vm.runInNewContext(input.slice(startPos), {version: _.clone(process.versions)}, {
            timeout: 17,
            filename: (options.botname || "ai") + ".vm"
        }).replace(/\n/g, "");
    } catch (e) {
        var error = e.message;
        var lines = error.split("\n");

        if (startPos === 1 && /\n\s*\^\s*\n/.test(error)) {
            error = lines[lines.length - 1] + " (" + lines[0] + ")";
        } else if (lines.length > 4) {
            error = lines.splice(0, 4).join("\n") + lines.splice(5).join("");
        }

        return error;
    }
}

function runScriptInChat(client, to, message) {
    var result = executeJavascript(message, {botname: client.nick});

    if (result !== undefined) {
        client.say(to, result);
    }
}

function init(newSettings) {
    settings = newSettings;
}

function channelMessage(from, to, message) {
    runScriptInChat(this.client, to, message);
}

function pm(from, message) {
    runScriptInChat(this.client, from, message);
}

module.exports = {
    "message#": channelMessage,
    pm: pm
};<commit_msg>Fine tune jsRunner<commit_after>var vm = require("vm");
var _ = require("lodash");

// Usage:
// > var write = console.commands();
// >> var write = console.commands({verbose: true});

var env = {
    version: _.clone(process.versions)
};

function executeJavascript(input, options) {
    if (input[0] !== ">" || input.length > 255) {
        return;
    }

    var startPos = input[1] === ">" ? 2 : 1;
    var buffer = [];

    local_env = _.cloneDeep(env);
    local_env.console = {
        log: function() {
            var data = "";
            for (var i = 0; i < arguments.length; i++) {
                data += arguments[i];
            }

            buffer.push(data);
        }
    };

    Object.freeze(local_env.version);

    try {
         // Timeout set to a bit more than 1 screen frame duration
        var result = vm.runInNewContext(input.slice(startPos), local_env, {
            timeout: 17,
            filename: (options.botname || "ai") + ".vm"
        });

        return ("" +
            buffer.splice(0, 4).join("\n") +
            buffer.splice(5).join("") +
            "\n" + (result + "").replace(/\n/g, "")
        );
    } catch (e) {
        var error = e.message;
        var lines = error.split("\n");

        if (startPos === 1 && /\n\s*\^\s*\n/.test(error)) {
            error = lines[lines.length - 1] + " (" + lines[0] + ")";
        } else if (lines.length > 4) {
            error = lines.splice(0, 4).join("\n") + lines.splice(5).join("");
        }

        return error;
    }
}

function runScriptInChat(client, to, message) {
    var result = executeJavascript(message, {botname: client.nick});

    if (result !== undefined) {
        client.say(to, result);
    }
}

function init(newSettings) {
    settings = newSettings;
}

function channelMessage(from, to, message) {
    runScriptInChat(this.client, to, message);
}

function pm(from, message) {
    runScriptInChat(this.client, from, message);
}

module.exports = {
    "message#": channelMessage,
    pm: pm
};<|endoftext|>


<commit_before>var url = require('url');
var crypto = require('crypto');
var _ = require('underscore');
var superagent = require('superagent');

function InfogramApi (apiKey, apiSecret) {
  this.base = url.parse('https://infogr.am/service/v1');
  if (!apiKey || !apiSecret) {
    throw new Error('Please provide two arguments: apiKey and apiSecret');
  }
  this.apiKey = apiKey;
  this.apiSecret = apiSecret;
}

InfogramApi.prototype = {
  get: function (path, params) {
    var method = superagent.get;
    return this.call(method, path, params);
  },

  post: function (path, params) {
    var method = superagent.post;
    params['content'] = JSON.stringify(params['content']);
    return this.call(method, path, params);
  },

  put: function (path, params) {
    var method = superagent.put;
    params['content'] = JSON.stringify(params['content']);
    return this.call(method, path, params);
  },

  delete: function (path, params) {
    var method = superagent.delete;
    return this.call(method, path, params);
  },

  call: function (method, path, params) {
    var basePath = this.base.pathname;
    if (_.last(basePath) !== '/' && _.last(path) !== '/') {
      basePath += '/';
    }

    var req = method('https://' + this.base.hostname + basePath + path);

    var requestParams = _.extend(_.clone(params), {
      api_key: this.apiKey
    });

    requestParams.format = requestParams.format || 'json';

    var requestOptions = {
      hostname: this.base.hostname,
      port: this.base.port,
      path: basePath + path,
      method: req.method
    };

    var baseString = signatureBaseString.call(this, requestOptions, requestParams);

    var signingKey = percentEncode(this.apiSecret);

    return new Promise(function (resolve, reject) {
      var hmac = crypto.createHmac('sha1', signingKey);
      hmac.end(baseString, 'UTF-8', function makeRequest (error) {
        if (error) {
          reject(error);
          return;
        }

        requestParams['api_sig'] = hmac.read().toString('base64');

        if (req.method === 'GET' || req.method === 'DELETE') {
          req.query(requestParams);
        } else {
          req.type('form');
          req.send(requestParams);
        }

        if (requestParams.format !== 'json') {
          req.parse(binaryParser);
        }

        req.end(function (err, res) {
          if (err) {
            reject(err);
          } else {
            resolve(res.body);
          }
        });
      });
    });
  }
};

InfogramApi._addMethods = function (methods) {
  for (var i in methods) {
    if (methods.hasOwnProperty(i)) {
      this.prototype[i] = methods[i];
    }
  }
};

function signatureBaseString (requestOptions, params) {
  var components = [];
  components.push(requestOptions.method);

  var host = requestOptions.hostname;
  if (requestOptions.port) {
    host += ':' + requestOptions.port;
  }

  components.push(percentEncode(this.base.protocol + '//' + host + requestOptions.path));

  components.push(percentEncode(buildQueryString(params)));

  return components.join('&');
}

function percentEncode (input) {
  return encodeURIComponent(input).replace(/[!'()*]/g, function (c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

function binaryParser (res, callback) {
  res.setEncoding('binary');
  res.data = '';
  res.on('data', function (chunk) {
    res.data += chunk;
  });
  res.on('end', function () {
    callback(null, new Buffer(res.data, 'binary'));
  });
}

function buildQueryString (params) {
  var query = '';
  var first = true;
  var keys = _.keys(params);

  keys.sort();
  _.each(keys, function (key) {
    if (!first) {
      query += '&';
    }
    query += percentEncode(key) + '=' + percentEncode(params[key]);
    first = false;
  });

  return query;
}

module.exports = InfogramApi;
<commit_msg>New buffer is depricated use Buffer.from<commit_after>var url = require('url');
var crypto = require('crypto');
var _ = require('underscore');
var superagent = require('superagent');

function InfogramApi (apiKey, apiSecret) {
  this.base = url.parse('https://infogr.am/service/v1');
  if (!apiKey || !apiSecret) {
    throw new Error('Please provide two arguments: apiKey and apiSecret');
  }
  this.apiKey = apiKey;
  this.apiSecret = apiSecret;
}

InfogramApi.prototype = {
  get: function (path, params) {
    var method = superagent.get;
    return this.call(method, path, params);
  },

  post: function (path, params) {
    var method = superagent.post;
    params['content'] = JSON.stringify(params['content']);
    return this.call(method, path, params);
  },

  put: function (path, params) {
    var method = superagent.put;
    params['content'] = JSON.stringify(params['content']);
    return this.call(method, path, params);
  },

  delete: function (path, params) {
    var method = superagent.delete;
    return this.call(method, path, params);
  },

  call: function (method, path, params) {
    var basePath = this.base.pathname;
    if (_.last(basePath) !== '/' && _.last(path) !== '/') {
      basePath += '/';
    }

    var req = method('https://' + this.base.hostname + basePath + path);

    var requestParams = _.extend(_.clone(params), {
      api_key: this.apiKey
    });

    requestParams.format = requestParams.format || 'json';

    var requestOptions = {
      hostname: this.base.hostname,
      port: this.base.port,
      path: basePath + path,
      method: req.method
    };

    var baseString = signatureBaseString.call(this, requestOptions, requestParams);

    var signingKey = percentEncode(this.apiSecret);

    return new Promise(function (resolve, reject) {
      var hmac = crypto.createHmac('sha1', signingKey);
      hmac.end(baseString, 'UTF-8', function makeRequest (error) {
        if (error) {
          reject(error);
          return;
        }

        requestParams['api_sig'] = hmac.read().toString('base64');

        if (req.method === 'GET' || req.method === 'DELETE') {
          req.query(requestParams);
        } else {
          req.type('form');
          req.send(requestParams);
        }

        if (requestParams.format !== 'json') {
          req.parse(binaryParser);
        }

        req.end(function (err, res) {
          if (err) {
            reject(err);
          } else {
            resolve(res.body);
          }
        });
      });
    });
  }
};

InfogramApi._addMethods = function (methods) {
  for (var i in methods) {
    if (methods.hasOwnProperty(i)) {
      this.prototype[i] = methods[i];
    }
  }
};

function signatureBaseString (requestOptions, params) {
  var components = [];
  components.push(requestOptions.method);

  var host = requestOptions.hostname;
  if (requestOptions.port) {
    host += ':' + requestOptions.port;
  }

  components.push(percentEncode(this.base.protocol + '//' + host + requestOptions.path));

  components.push(percentEncode(buildQueryString(params)));

  return components.join('&');
}

function percentEncode (input) {
  return encodeURIComponent(input).replace(/[!'()*]/g, function (c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

function binaryParser (res, callback) {
  res.setEncoding('binary');
  res.data = '';
  res.on('data', function (chunk) {
    res.data += chunk;
  });
  res.on('end', function () {
    callback(null, Buffer.from(res.data, 'binary'));
  });
}

function buildQueryString (params) {
  var query = '';
  var first = true;
  var keys = _.keys(params);

  keys.sort();
  _.each(keys, function (key) {
    if (!first) {
      query += '&';
    }
    query += percentEncode(key) + '=' + percentEncode(params[key]);
    first = false;
  });

  return query;
}

module.exports = InfogramApi;
<|endoftext|>