<commit_before>var _ = require('underscore');
var colors = require('colors');
var fs = require('fs');
var inquirer = require('inquirer');
var M = require('mstring');

colors.setTheme({
  silly: 'rainbow',
  input: 'grey',
  verbose: 'cyan',
  prompt: 'grey',
  info: 'green',
  data: 'grey',
  help: 'cyan',
  warn: 'yellow',
  debug: 'blue',
  error: 'red'
});

inquirer.prompt({
  type: 'list',
  name: 'category',
  message: 'Hackathon Starter Generator:',
  choices: ['Authentication', 'Exit']
}, function(answer) {
  if (answer.category === 'Authentication') {
    inquirer.prompt({
      type: 'checkbox',
      message: 'Select Authentication Providers:',
      name: 'auth',
      choices: [
        { name: 'Facebook', checked: true },
        { name: 'GitHub', checked: true },
        { name: 'Google', checked: true },
        { name: 'Twitter', checked: true },
        { name: 'Local', checked: true },
        { name: 'LinkedIn' },
        { name: 'Instagram' }
      ],
      validate: function(answer) {
        if (answer.length < 1) {
          return 'You must choose at least one authentication method.';
        }
        return true;
      }
    }, function(answer) {
      var facebookStrategyRequire = "var FacebookStrategy = require('passport-facebook').Strategy;";
      var facebookStrategy = M(function() {
        /***
         // Sign in with Facebook.

         passport.use(new FacebookStrategy(secrets.facebook, function(req, accessToken, refreshToken, profile, done) {
            if (req.user) {
              User.findOne({ $or: [{ facebook: profile.id }, { email: profile.email }] }, function(err, existingUser) {
                if (existingUser) {
                  req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
                  done(err);
                } else {
                  User.findById(req.user.id, function(err, user) {
                    user.facebook = profile.id;
                    user.tokens.push({ kind: 'facebook', accessToken: accessToken });
                    user.profile.name = user.profile.name || profile.displayName;
                    user.profile.gender = user.profile.gender || profile._json.gender;
                    user.profile.picture = user.profile.picture || 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
                    user.save(function(err) {
                      req.flash('info', { msg: 'Facebook account has been linked.' });
                      done(err, user);
                    });
                  });
                }
              });
            } else {
              User.findOne({ facebook: profile.id }, function(err, existingUser) {
                if (existingUser) return done(null, existingUser);
                User.findOne({ email: profile._json.email }, function(err, existingEmailUser) {
                  if (existingEmailUser) {
                    req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' });
                    done(err);
                  } else {
                    var user = new User();
                    user.email = profile._json.email;
                    user.facebook = profile.id;
                    user.tokens.push({ kind: 'facebook', accessToken: accessToken });
                    user.profile.name = profile.displayName;
                    user.profile.gender = profile._json.gender;
                    user.profile.picture = 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
                    user.profile.location = (profile._json.location) ? profile._json.location.name : '';
                    user.save(function(err) {
                      done(err, user);
                    });
                  }
                });
              });
            }
          }));

         ***/
      });
      var facebookButton = M(function() {
        /***
               a.btn.btn-block.btn-facebook.btn-social(href='/auth/facebook')
                 i.fa.fa-facebook
                 | Sign in with Facebook
         ***/
      });
      var facebookLinkUnlink = M(function() {
        /***

           if user.facebook
             p: a.text-danger(href='/account/unlink/facebook') Unlink your Facebook account
           else
             p: a(href='/auth/facebook') Link your Facebook account
         ***/
      });
      var facebookModel = '  facebook: String,';

      var passportConfigFile = 'config/passport.js';
      var userModelFile = 'models/User.js';
      var profileTemplateFile = 'views/account/profile.jade';
      var loginTemplateFile = 'views/account/login.jade';

      var passportConfig = fs.readFileSync(passportConfigFile).toString().split('\n');
      var loginTemplate = fs.readFileSync(loginTemplateFile).toString().split('\n');
      var profileTemplate = fs.readFileSync(profileTemplateFile).toString().split('\n');
      var userModel = fs.readFileSync(userModelFile).toString().split('\n');

      var index;

      if (_.contains(answer.auth, 'FCodeacebook')) {
        if (passportConfig.indexOf(facebookStrategyRequire) < 0) {

          // config/passport.js (+)
          index = passportConfig.indexOf("var passport = require('passport');");
          passportConfig.splice(index + 1, 0, facebookStrategyRequire);
          index = passportConfig.indexOf('passport.deserializeUser(function(id, done) {');
          passportConfig.splice(index + 6, 0, facebookStrategy);
          fs.writeFileSync(passportConfigFile, passportConfig.join('\n'));

          // views/account/login.jade (+)
          loginTemplate.push(facebookButton);
          fs.writeFileSync(loginTemplateFile, loginTemplate.join('\n'));

          // views/account/profile.jade (+)
          index = profileTemplate.indexOf('    h3 Linked Accounts');
          profileTemplate.splice(index + 1, 0, facebookLinkUnlink);
          fs.writeFileSync(profileTemplateFile, profileTemplate.join('\n'));

          // models/User.js (+)
          index = userModel.indexOf('  tokens: Array,');
          userModel.splice(index -1 , 0, facebookModel);
          fs.writeFileSync(userModelFile, userModel.join('\n'));

          console.log('Facebook authentication has been added.'.info);
        } else {
          console.log('Facebook authentication is already active.'.warn);
        }
      } else {

        // config/passport.js (-)
        index = passportConfig.indexOf(facebookStrategyRequire);
        passportConfig.splice(index, 1);
        index = passportConfig.indexOf('// Sign in with Facebook.');
        passportConfig.splice(index, 47);
        fs.writeFileSync(passportConfigFile, passportConfig.join('\n'));

        // views/account/login.jade (-)
        index = loginTemplate.indexOf("      a.btn.btn-block.btn-facebook.btn-social(href='/auth/facebook')");
        loginTemplate.splice(index, 4);
        fs.writeFileSync(loginTemplateFile, loginTemplate.join('\n'));

        // views/account/profile.jade (-)
        index = profileTemplate.indexOf("  if user.facebook");
        profileTemplate.splice(index - 1, 5);
        fs.writeFileSync(profileTemplateFile, profileTemplate.join('\n'));

        // models/User.js (-)
        index = userModel.indexOf('  facebook: String,');
        userModel.splice(index, 1);
        fs.writeFileSync(userModelFile, userModel.join('\n'));

        console.log('Facebook authentication has been removed.'.error);
      }
    });
  }
});<commit_msg>Added Google add/remove generator<commit_after>var _ = require('underscore');
var colors = require('colors');
var fs = require('fs');
var inquirer = require('inquirer');
var M = require('mstring');

colors.setTheme({
  silly: 'rainbow',
  input: 'grey',
  verbose: 'cyan',
  prompt: 'grey',
  info: 'green',
  data: 'grey',
  help: 'cyan',
  warn: 'yellow',
  debug: 'blue',
  error: 'red'
});

inquirer.prompt({
  type: 'list',
  name: 'category',
  message: 'Hackathon Starter Generator:',
  choices: ['Authentication', 'Exit']
}, function(answer) {
  if (answer.category === 'Authentication') {
    inquirer.prompt({
      type: 'checkbox',
      message: 'Select Authentication Providers:',
      name: 'auth',
      choices: [
        { name: 'Facebook', checked: true },
        { name: 'GitHub', checked: true },
        { name: 'Google', checked: true },
        { name: 'Twitter', checked: true },
        { name: 'Local', checked: true },
        { name: 'LinkedIn', checked: true }
      ],
      validate: function(answer) {
        if (answer.length < 1) return 'You must choose at least one authentication method.';
        return true;
      }
    }, function(answer) {
      var index;

      var passportConfigFile = 'config/passport.js';
      var userModelFile = 'models/User.js';
      var profileTemplateFile = 'views/account/profile.jade';
      var loginTemplateFile = 'views/account/login.jade';

      var passportConfig = fs.readFileSync(passportConfigFile).toString().split('\n');
      var loginTemplate = fs.readFileSync(loginTemplateFile).toString().split('\n');
      var profileTemplate = fs.readFileSync(profileTemplateFile).toString().split('\n');
      var userModel = fs.readFileSync(userModelFile).toString().split('\n');

      if (_.contains(answer.auth, 'Facebook')) {
        var facebookStrategyRequire = "var FacebookStrategy = require('passport-facebook').Strategy;";
        var facebookStrategy = M(function() {
          /***
          // Sign in with Facebook.

          passport.use(new FacebookStrategy(secrets.facebook, function(req, accessToken, refreshToken, profile, done) {
            if (req.user) {
              User.findOne({ $or: [{ facebook: profile.id }, { email: profile.email }] }, function(err, existingUser) {
                if (existingUser) {
                  req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
                  done(err);
                } else {
                  User.findById(req.user.id, function(err, user) {
                    user.facebook = profile.id;
                    user.tokens.push({ kind: 'facebook', accessToken: accessToken });
                    user.profile.name = user.profile.name || profile.displayName;
                    user.profile.gender = user.profile.gender || profile._json.gender;
                    user.profile.picture = user.profile.picture || 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
                    user.save(function(err) {
                      req.flash('info', { msg: 'Facebook account has been linked.' });
                      done(err, user);
                    });
                  });
                }
              });
            } else {
              User.findOne({ facebook: profile.id }, function(err, existingUser) {
                if (existingUser) return done(null, existingUser);
                User.findOne({ email: profile._json.email }, function(err, existingEmailUser) {
                  if (existingEmailUser) {
                    req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' });
                    done(err);
                  } else {
                    var user = new User();
                    user.email = profile._json.email;
                    user.facebook = profile.id;
                    user.tokens.push({ kind: 'facebook', accessToken: accessToken });
                    user.profile.name = profile.displayName;
                    user.profile.gender = profile._json.gender;
                    user.profile.picture = 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
                    user.profile.location = (profile._json.location) ? profile._json.location.name : '';
                    user.save(function(err) {
                      done(err, user);
                    });
                  }
                });
              });
            }
          }));

          ***/
        });
        var facebookButton = M(function() {
          /***
           a.btn.btn-block.btn-facebook.btn-social(href='/auth/facebook')
             i.fa.fa-facebook
             | Sign in with Facebook
           ***/
        });
        var facebookLinkUnlink = M(function() {
          /***

           if user.facebook
             p: a.text-danger(href='/account/unlink/facebook') Unlink your Facebook account
           else
             p: a(href='/auth/facebook') Link your Facebook account
           ***/
        });
        var facebookModel = '  facebook: String,';

        if (passportConfig.indexOf(facebookStrategyRequire) < 0) {

          // config/passport.js (+)
          index = passportConfig.indexOf("var passport = require('passport');");
          passportConfig.splice(index + 1, 0, facebookStrategyRequire);
          index = passportConfig.indexOf('passport.deserializeUser(function(id, done) {');
          passportConfig.splice(index + 6, 0, facebookStrategy);
          fs.writeFileSync(passportConfigFile, passportConfig.join('\n'));

          // views/account/login.jade (+)
          loginTemplate.push(facebookButton);
          fs.writeFileSync(loginTemplateFile, loginTemplate.join('\n'));

          // views/account/profile.jade (+)
          index = profileTemplate.indexOf('    h3 Linked Accounts');
          profileTemplate.splice(index + 1, 0, facebookLinkUnlink);
          fs.writeFileSync(profileTemplateFile, profileTemplate.join('\n'));

          // models/User.js (+)
          index = userModel.indexOf('  tokens: Array,');
          userModel.splice(index - 1, 0, facebookModel);
          fs.writeFileSync(userModelFile, userModel.join('\n'));

          console.log('Facebook authentication has been added.'.info);
        } else {
          console.log('Facebook authentication is already active.'.warn);
        }
      } else {

        // config/passport.js (-)
        index = passportConfig.indexOf(facebookStrategyRequire);
        passportConfig.splice(index, 1);
        index = passportConfig.indexOf('// Sign in with Facebook.');
        passportConfig.splice(index, 47);
        fs.writeFileSync(passportConfigFile, passportConfig.join('\n'));

        // views/account/login.jade (-)
        index = loginTemplate.indexOf("      a.btn.btn-block.btn-facebook.btn-social(href='/auth/facebook')");
        loginTemplate.splice(index, 4);
        fs.writeFileSync(loginTemplateFile, loginTemplate.join('\n'));

        // views/account/profile.jade (-)
        index = profileTemplate.indexOf("  if user.facebook");
        profileTemplate.splice(index - 1, 5);
        fs.writeFileSync(profileTemplateFile, profileTemplate.join('\n'));

        // models/User.js (-)
        index = userModel.indexOf('  facebook: String,');
        userModel.splice(index, 1);
        fs.writeFileSync(userModelFile, userModel.join('\n'));

        console.log('Facebook authentication has been removed.'.error);
      }

      if (_.contains(answer.auth, 'Google')) {
        var googleStrategyRequire = "var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;";
        var googleStrategy = M(function() {
          /***
          // Sign in with Google.

          passport.use(new GoogleStrategy(secrets.google, function(req, accessToken, refreshToken, profile, done) {
            if (req.user) {
              User.findOne({ $or: [{ google: profile.id }, { email: profile.email }] }, function(err, existingUser) {
                if (existingUser) {
                  req.flash('errors', { msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
                  done(err);
                } else {
                  User.findById(req.user.id, function(err, user) {
                    user.google = profile.id;
                    user.tokens.push({ kind: 'google', accessToken: accessToken });
                    user.profile.name = user.profile.name || profile.displayName;
                    user.profile.gender = user.profile.gender || profile._json.gender;
                    user.profile.picture = user.profile.picture || profile._json.picture;
                    user.save(function(err) {
                      req.flash('info', { msg: 'Google account has been linked.' });
                      done(err, user);
                    });
                  });
                }
              });
            } else {
              User.findOne({ google: profile.id }, function(err, existingUser) {
                if (existingUser) return done(null, existingUser);
                User.findOne({ email: profile._json.email }, function(err, existingEmailUser) {
                  if (existingEmailUser) {
                    req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Google manually from Account Settings.' });
                    done(err);
                  } else {
                    var user = new User();
                    user.email = profile._json.email;
                    user.google = profile.id;
                    user.tokens.push({ kind: 'google', accessToken: accessToken });
                    user.profile.name = profile.displayName;
                    user.profile.gender = profile._json.gender;
                    user.profile.picture = profile._json.picture;
                    user.save(function(err) {
                      done(err, user);
                    });
                  }
                });
              });
            }
          }));

          ***/
        });

        var googleButton = M(function() {
          /***
           a.btn.btn-block.btn-google-plus.btn-social(href='/auth/google')
             i.fa.fa-google-plus
             | Sign in with Google
           ***/
        });
        var googleLinkUnlink = M(function() {
          /***

           if user.google
             p: a.text-danger(href='/account/unlink/google') Unlink your Google account
           else
             p: a(href='/auth/google') Link your Google account
           ***/
        });
        var googleModel = '  google: String,';

        if (passportConfig.indexOf(googleStrategyRequire) < 0) {

          // config/passport.js (+)
          index = passportConfig.indexOf("var passport = require('passport');");
          passportConfig.splice(index + 1, 0, googleStrategyRequire);
          index = passportConfig.indexOf('passport.deserializeUser(function(id, done) {');
          passportConfig.splice(index + 6, 0, googleStrategy);
          fs.writeFileSync(passportConfigFile, passportConfig.join('\n'));

          // views/account/login.jade (+)
          loginTemplate.push(googleButton);
          fs.writeFileSync(loginTemplateFile, loginTemplate.join('\n'));

          // views/account/profile.jade (+)
          index = profileTemplate.indexOf('    h3 Linked Accounts');
          profileTemplate.splice(index + 1, 0, googleLinkUnlink);
          fs.writeFileSync(profileTemplateFile, profileTemplate.join('\n'));

          // models/User.js (+)
          index = userModel.indexOf('  tokens: Array,');
          userModel.splice(index - 1, 0, googleModel);
          fs.writeFileSync(userModelFile, userModel.join('\n'));

          console.log('Google authentication has been added.'.info);
        } else {
          console.log('Google authentication is already active.'.warn);
        }
      } else {

        // config/passport.js (-)
        index = passportConfig.indexOf(googleStrategyRequire);
        passportConfig.splice(index, 1);
        index = passportConfig.indexOf('// Sign in with Google.');
        passportConfig.splice(index, 46);
        fs.writeFileSync(passportConfigFile, passportConfig.join('\n'));

        // views/account/login.jade (-)
        index = loginTemplate.indexOf("      a.btn.btn-block.btn-google-plus.btn-social(href='/auth/google')");
        loginTemplate.splice(index, 4);
        fs.writeFileSync(loginTemplateFile, loginTemplate.join('\n'));

        // views/account/profile.jade (-)
        index = profileTemplate.indexOf("  if user.google");
        profileTemplate.splice(index - 1, 5);
        fs.writeFileSync(profileTemplateFile, profileTemplate.join('\n'));

        // models/User.js (-)
        index = userModel.indexOf('  google: String,');
        userModel.splice(index, 1);
        fs.writeFileSync(userModelFile, userModel.join('\n'));

        console.log('Google authentication has been removed.'.error);
      }
    });
  }
});<|endoftext|>


<commit_before>import {path} from "ramda"
import {omit} from "ramda"
import {prop} from "ramda"
import {map} from "ramda"
import {merge} from "ramda"
import {allP} from "ramda-extra"
import {resolveP} from "ramda-extra"
import {allObjectP} from "ramda-extra"

import startLoadingSignal from "../startLoadingSignal"
import finishLoadingSignal from "../finishLoadingSignal"
import updateLocationSignal from "../updateLocationSignal"
import clearFormSignal from "../clearFormSignal"
import mergeResourceSignal from "../mergeResourceSignal"
import storeCurrentSignal from "../storeCurrentSignal"
import pushProject from "../pushProject"
import pushPhotograph from "../pushPhotograph"

export default function createProjectSignal (slug: string): Function {
  return function thunk (dispatch: ReduxDispatchType, getState: GetStateType, {client}: {client: HSDKClientType}): Promise<SignalType> {
    const state = getState()
    const self = path(["ephemeral", "current", "self"], state)
    const session = path(["resources", "sessions", self], state)
    const bearer = path(["attributes", "bearer"], session)
    const form = path(["ephemeral", "forms", slug], state)
    const attributes = omit(["photographs"], form)
    const photographs = prop("photographs", form)
    const projectRequest = pushProject(client)(bearer)
    const photographRequest = pushPhotograph(client)(bearer)

    return resolveP(dispatch(startLoadingSignal(slug)))
      .then((): Promise<ProjectResourceType> => projectRequest(attributes))
      .then((project: ProjectResourceType): Promise<{mergedResourceSignal: SignalType, storeCurrentSignal: SignalType, project: ProjectResourceType}> => {
        return allObjectP({
          mergedResourceSignal: dispatch(mergeResourceSignal(project)),
          storeCurrentSignal: dispatch(storeCurrentSignal({
            id: project.id,
            key: "project",
          })),
          photographs: allP(map(photographRequest, map(merge({project}), photographs))),
          project,
        })
      })
      .then(({project}: {project: ProjectResourceType}): Promise<{finishLoadingSignal: SignalType, clearFormSignal: SignalType, updateLocationSignal: updateLocationSignal}> => {
        return allObjectP({
          finishLoadingSignal: dispatch(finishLoadingSignal(slug)),
          storeCurrentSignal: dispatch(clearFormSignal(slug)),
          updateLocationSignal: dispatch(updateLocationSignal(`/projects/${project.id}`)),
        })
      })
      .then((): SignalType => dispatch({type: "createProjectSignal"}))
  }
}
<commit_msg>Fixing name<commit_after>import {path} from "ramda"
import {omit} from "ramda"
import {prop} from "ramda"
import {map} from "ramda"
import {merge} from "ramda"
import {allP} from "ramda-extra"
import {resolveP} from "ramda-extra"
import {allObjectP} from "ramda-extra"

import startLoadingSignal from "../startLoadingSignal"
import finishLoadingSignal from "../finishLoadingSignal"
import updateLocationSignal from "../updateLocationSignal"
import clearFormSignal from "../clearFormSignal"
import mergeResourceSignal from "../mergeResourceSignal"
import storeCurrentSignal from "../storeCurrentSignal"
import pushProject from "../pushProject"
import pushPhotograph from "../pushPhotograph"

export default function createProjectSignal (slug: string): Function {
  return function thunk (dispatch: ReduxDispatchType, getState: GetStateType, {client}: {client: HSDKClientType}): Promise<SignalType> {
    const state = getState()
    const self = path(["ephemeral", "current", "self"], state)
    const session = path(["resources", "sessions", self], state)
    const bearer = path(["attributes", "bearer"], session)
    const form = path(["ephemeral", "forms", slug], state)
    const attributes = omit(["photographs"], form)
    const photographs = prop("photographs", form)
    const projectRequest = pushProject(client)(bearer)
    const photographRequest = pushPhotograph(client)(bearer)

    return resolveP(dispatch(startLoadingSignal(slug)))
      .then((): Promise<ProjectResourceType> => projectRequest(attributes))
      .then((project: ProjectResourceType): Promise<{mergedResourceSignal: SignalType, storeCurrentSignal: SignalType, project: ProjectResourceType}> => {
        return allObjectP({
          mergedResourceSignal: dispatch(mergeResourceSignal(project)),
          storeCurrentSignal: dispatch(storeCurrentSignal({
            id: project.id,
            key: "project",
          })),
          photographs: allP(map(photographRequest, map(merge({project}), photographs))),
          project,
        })
      })
      .then(({project}: {project: ProjectResourceType}): Promise<{finishLoadingSignal: SignalType, clearFormSignal: SignalType, updateLocationSignal: updateLocationSignal}> => {
        return allObjectP({
          finishLoadingSignal: dispatch(finishLoadingSignal(slug)),
          clearFormSignal: dispatch(clearFormSignal(slug)),
          updateLocationSignal: dispatch(updateLocationSignal(`/projects/${project.id}`)),
        })
      })
      .then((): SignalType => dispatch({type: "createProjectSignal"}))
  }
}
<|endoftext|>


<commit_before>'use strict';

import c3 from 'c3';
import _ from 'underscore';
import View from 'core/view';

let ChartTpl = require('app/templates/partials/chart.html');

export default View.extend({
    initialize() {
        this.template = ChartTpl;
    },

    postPlaceAt() {
        _.defer(this.createChart.bind(this));
    },

    createChart() {
        let chart = c3.generate({
            bindto: '#chart',
            data: {
                columns: [
                    ['data1', 30, 200, 100, 400, 150, 250],
                    ['data2', 50, 20, 10, 40, 15, 25]
                ]
            }
        });
    }
});
<commit_msg>started activity chart<commit_after>'use strict';

import c3 from 'c3';
import _ from 'underscore';
import View from 'core/view';

let ChartTpl = require('app/templates/partials/chart.html');

export default View.extend({
    initialize() {
        this.template = ChartTpl;
        this.provider = this.get('ProviderManager');;
    },

    postPlaceAt() {
        _.defer(this.createChart.bind(this));
    },

    createChart() {
        let chart = c3.generate({
            bindto: '#chart',
            data: {
                columns: [
                    ['data1', 30, 200, 100, 400, 150, 250],
                    ['data2', 50, 20, 10, 40, 15, 25]
                ]
            }
        });
    }
});
<|endoftext|>


<commit_before>describe('MakePlural compiler', function(){
    it('should have data members', function(){
        expect(MakePlural).to.have.keys('cardinals', 'ordinals', 'rules');
    });

    describe('.load()', function(){
        it('should require valid parameters', function(){
            expect(MakePlural.load).to.not.throwException();
            expect(MakePlural.load).withArgs('').to.throwException();
        });
        it('should load custom CLDR data', function(){
            var cldr = { supplemental: { 'plurals-type-cardinal': { xx: {
                'pluralRule-count-one': 'n = 1 @integer 1 @decimal 1.0, 1.00, 1.000, 1.0000',
                'pluralRule-count-other': ' @integer 0, 2~16, 100, 1000, … @decimal 0.0~0.9, 1.1~1.6, 10.0, 100.0, 1000.0, …'
            }}}};
            MakePlural.load(cldr);
            expect(MakePlural.rules).to.have.key('cardinal');
            expect(MakePlural.rules.cardinal).to.only.have.key('xx');
        });
        it('should load default CLDR data', function(){
            expect(MakePlural.load).withArgs(cardinals, ordinals).to.not.throwException();
            expect(MakePlural.rules).to.only.have.keys('cardinal', 'ordinal');
            expect(MakePlural.rules.cardinal).to.not.have.key('xx');
            expect(MakePlural.rules.cardinal).to.have.key('en');
            expect(MakePlural.rules.ordinal).to.have.key('en');
        });
        it('should return MakePlural', function(){
            expect(MakePlural.load()).to.be(MakePlural);
        });
    });

    describe('MakePlural()', function(){
        it('should require `new`', function(){
            expect(MakePlural).to.throwException(function(e){
                expect(e).to.be.a(TypeError);
                expect(e.message).to.contain('class');
            });
        });
        it('should require a locale', function(){
            var new_mp = function(lc) { return new MakePlural(lc); };
            expect(new_mp).to.throwException();
            expect(new_mp).withArgs('en').to.not.throwException();
        });
        it('should return a pluralization function', function(){
            var mp = new MakePlural('en');
            expect(mp).to.be.a(Function);
            expect(mp(1)).to.be('one');
        });
        it('should handle local options', function(){
            var mp = new MakePlural('en', { ordinals: true });
            expect(mp(2, true)).to.be('two');
        });
        it('should handle global options', function(){
            MakePlural.lc = 'en'
            MakePlural.ordinals = true;
            var mp = new MakePlural();
            expect(mp(2, true)).to.be('two');
            delete MakePlural.lc;
            MakePlural.ordinals = false;
        });
    });

    describe('#test()', function(){
        it('should validate default functions', function(){
            var mp = new MakePlural('en', { ordinals: true });
            expect(mp.test()).to.be(mp);
        });
        it('should not validate bad functions', function(){
            var cldr = { supplemental: { 'plurals-type-cardinal': { xx: {
                    'pluralRule-count-one': 'n = 1 @integer 2',
                    'pluralRule-count-other': ''
                }}}},
                prevRules = MakePlural.rules;
            MakePlural.load(cldr);
            var mp = new MakePlural('xx');
            expect(mp.test).to.throwException(function(e){
                expect(e.message).to.contain('self-test failed');
            });
            MakePlural.rules = prevRules;
        });
    });

    describe('#toString()', function(){
        it('should return a string', function(){
            var mp = new MakePlural('en', { ordinals: true });
            expect(mp.toString()).to.contain('function');
        });
        it('which can be eval\'d as a function', function(){
            var mp = new MakePlural('en', { ordinals: true });
            var fn = eval('(' + mp.toString() + ')');
            expect(fn).to.be.a(Function);
            expect(fn(1)).to.be('one');
            expect(fn(2, true)).to.be('two');
        });
    });
});
<commit_msg>Fix tests to account for API change in c61d68e<commit_after>describe('MakePlural compiler', function(){
    it('should have data members', function(){
        expect(MakePlural).to.have.keys('cardinals', 'ordinals', 'rules');
    });

    describe('.load()', function(){
        it('should require valid parameters', function(){
            expect(MakePlural.load).to.not.throwException();
            expect(MakePlural.load).withArgs('').to.throwException();
        });
        it('should load custom CLDR data', function(){
            var cldr = { supplemental: { 'plurals-type-cardinal': { xx: {
                'pluralRule-count-one': 'n = 1 @integer 1 @decimal 1.0, 1.00, 1.000, 1.0000',
                'pluralRule-count-other': ' @integer 0, 2~16, 100, 1000, … @decimal 0.0~0.9, 1.1~1.6, 10.0, 100.0, 1000.0, …'
            }}}};
            MakePlural.load(cldr);
            expect(MakePlural.rules).to.have.key('cardinal');
            expect(MakePlural.rules.cardinal).to.only.have.key('xx');
        });
        it('should load default CLDR data', function(){
            expect(MakePlural.load).withArgs(cardinals, ordinals).to.not.throwException();
            expect(MakePlural.rules).to.only.have.keys('cardinal', 'ordinal');
            expect(MakePlural.rules.cardinal).to.not.have.key('xx');
            expect(MakePlural.rules.cardinal).to.have.key('en');
            expect(MakePlural.rules.ordinal).to.have.key('en');
        });
        it('should return MakePlural', function(){
            expect(MakePlural.load()).to.be(MakePlural);
        });
    });

    describe('MakePlural()', function(){
        it('should require `new`', function(){
            expect(MakePlural).to.throwException(function(e){
                expect(e).to.be.a(TypeError);
                expect(e.message).to.contain('class');
            });
        });
        it('should require a locale', function(){
            var new_mp = function(lc) { return new MakePlural(lc); };
            expect(new_mp).to.throwException();
            expect(new_mp).withArgs('en').to.not.throwException();
        });
        it('should return a pluralization function', function(){
            var mp = new MakePlural('en');
            expect(mp).to.be.a(Function);
            expect(mp(1)).to.be('one');
        });
        it('should handle local options', function(){
            var mp = new MakePlural('en', { ordinals: true });
            expect(mp(2, true)).to.be('two');
        });
        it('should handle global options', function(){
            MakePlural.ordinals = true;
            var mp = new MakePlural('en');
            expect(mp(2, true)).to.be('two');
            MakePlural.ordinals = false;
        });
    });

    describe('#test()', function(){
        it('should validate default functions', function(){
            var mp = new MakePlural('en', { ordinals: true });
            expect(mp.test()).to.be(mp);
        });
        it('should not validate bad functions', function(){
            var cldr = { supplemental: { 'plurals-type-cardinal': { xx: {
                    'pluralRule-count-one': 'n = 1 @integer 2',
                    'pluralRule-count-other': ''
                }}}},
                prevRules = MakePlural.rules;
            MakePlural.load(cldr);
            var mp = new MakePlural('xx');
            expect(mp.test).to.throwException(function(e){
                expect(e.message).to.contain('self-test failed');
            });
            MakePlural.rules = prevRules;
        });
    });

    describe('#toString()', function(){
        it('should return a string', function(){
            var mp = new MakePlural('en', { ordinals: true });
            expect(mp.toString()).to.contain('function');
        });
        it('which can be eval\'d as a function', function(){
            var mp = new MakePlural('en', { ordinals: true });
            var fn = eval('(' + mp.toString() + ')');
            expect(fn).to.be.a(Function);
            expect(fn(1)).to.be('one');
            expect(fn(2, true)).to.be('two');
        });
    });
});
<|endoftext|>


<commit_before>'use strict';
/*eslint no-else-return:0 */

angular.module('lx.navigation', [])
/**
 * @ngdoc object
 * @name lx.navigation.$lxNavigation
 *
 * @description
 * Service for navigation. Gets or sets the navigation.
 *
 * For more information look at the [guide](/lx_navigation).
 *
 */
    .provider('$lxNavigation', function () {
        var config = {};

        function cloneNavObject (value) {
            return {
                title: value.title,
                route: value.route,
                app: value.app,
                state: value.state,
                roles: value.roles
            };
        }

        function userHasAccess (user, navItem) {
            if (!navItem.roles && !navItem.resources || !user) {
                return true;
            }

            if (navItem.roles && !navItem.resources) {
                if (user.roles) {
                    for (var x = 0; x < navItem.roles.length; x++) {
                        for (var y = 0; y < user.roles.length; y++) {
                            if (navItem.roles[x] === user.roles[y]) {
                                return true;
                            }
                        }
                    }
                }

                return false;
            } else {
                if (user.acl) {
                    for (var z = 0; z < navItem.resources.length; z++) {
                        for (var w = 0; w < user.acl.length; w++) {
                            if (navItem.resources[z] === user.acl[w]) {
                                return true;
                            }
                        }
                    }
                }

                return false;
            }
        }

        function getUserNavigation (navigation, currentApp, user) {
            var result = [];

            angular.forEach(navigation, function (navItem) {
                if (navItem.children) {
                    var childList = getUserNavigation(navItem.children, currentApp, user);
                    var val = cloneNavObject(navItem);
                    val.children = childList;

                    if (userHasAccess(user, val)) {
                        result.push(val);
                    }
                } else if (userHasAccess(user, navItem)) {
                    result.push(cloneNavObject(navItem));
                }
            });

            return result;
        }

        /**
         * @ngdoc method
         * @name lx.navigation.$lxNavigation#set
         * @methodOf lx.navigation.$lxNavigation
         *
         * @description
         * Setup the navigation configuration
         *
         * @param {object} options The options for config
         */
        this.set = function (options) {
            options = options || {};

            // default settings
            config.navigation = options.navigation;
        };

        this.$get = function ($log) {
            var pub = {};

            /**
             * @ngdoc method
             * @name lx.navigation.$lxNavigation#getNavigation
             * @methodOf lx.navigation.$lxNavigation
             *
             * @description
             * ...
             *
             * @param {object} data The name of the navigation object, the user acl, the current app
             * @returns {Array} The navigation
             */
            pub.getNavigation = function (data) {
                var currentApp = data.currentApp || 'main';

                if (config.navigation && config.navigation[data.navName]) {
                    return getUserNavigation(config.navigation[data.navName], currentApp, data.user);
                } else {
                    if (!config.navigation) {
                        $log.info('No Navigation defined. Please define a navigation with the help of the $lxTransportProvider in the config section of your app.');
                    } else {
                        $log.error('Your defined nav-link-list "' + data.navName + '" is not defined!');
                    }

                    return [];
                }
            };

            return pub;
        };
    })
/**
 * @ngdoc directive
 * @name lx.navigation.directive:lxComNav
 * @restrict E
 *
 * @description
 * Creates the navigation in a flat list.
 *
 * For more information look at the [guide](/lxComNav).
 *
 * @param {string=} orientation The orientation of the list, horizontal or vertical.
 * @param {string} navLinklist The list with all navigation links.
 * @param {object=} navTemplatePath The path to a template which should overwrite the standard layout.
 *
 */
    .directive('lxComNav', function ($location, ACTIVE_APP, $http, $templateCache, $compile, $lxNavigation) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                orientation: '@',
                navName: '@',
                navTemplatePath: '=',
                navUser: '='
            },
            link: function (scope, element) {

                var tplContent = '
' +
                    '
' +
                    '
'+
                    '{{item.title}}' +
                    '
' +
                    '
' +
                    '{{item.title}}' +
                    '{{item.title}}' +
                    '
'+
                    '
' +
                    '
';

                function replaceWithStandard (template) {
                    angular.forEach(scope.menu,function(key){
                        if(key.route && key.state){
                            console.error("Please use only one routing element in your navigation. Route or State, not both together!! ",key);
                            element.replaceWith($compile('NAV ERROR')(scope));
                            return false;
                        }
                    });
                    element.replaceWith($compile(template)(scope));
                }

                var orientation = scope.orientation || 'horizontal';
                element.toggleClass('nav-stacked', orientation === 'vertical');

                scope.menu = $lxNavigation.getNavigation({
                    currentApp: ACTIVE_APP,
                    navName: scope.navName,
                    user: scope.navUser
                });

                if (scope.navTemplatePath && scope.navTemplatePath.length > 3) {
                    $http.get(scope.navTemplatePath, {cache: $templateCache})
                        .success(function (tplGetContent) {
                            if (tplGetContent.substr(0, 5) !== '<!doc') {
                                replaceWithStandard(tplGetContent);
                            } else {
                                replaceWithStandard(tplContent);
                            }
                        })
                        .error(function () {
                            replaceWithStandard(tplContent);
                        });
                } else {
                    replaceWithStandard(tplContent);
                }

                scope.isActiveApp = function (app) {
                    return app === ACTIVE_APP;
                };

                scope.isActive = function (route) {
                    return route === $location.path();
                };
            }
        };
    })
/**
 * @ngdoc directive
 * @name lx.navigation.directive:lxComNavTree
 * @restrict E
 *
 * @description
 * Creates the navigation in a tree list.
 *
 * For more information look at the [guide](/lxComNavTree).
 *
 * @param {string} navLinklist The list with all navigation links.
 * @param {object=} navTemplatePath The path to a template which should overwrite the standard layout.
 *
 */
    .directive('lxComNavTree', function ($route, $location, $templateCache, ACTIVE_APP, $http, $compile, $lxNavigation) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                navName: '@',
                navTemplatePath: '=',
                navUser: '='
            },
            link: function (scope, element) {

                var tplContent = '
' +
                    '
' +
                    '
' +
                    '
';

                $templateCache.put('lx_navigation/standard/nav_tree_inside',
                        '
' +
                        '

' +
                        '

' +
                        ' 0}" ng-href="{{data.route}}">{{data.title}}' +
                        ' 0}" ng-href="{{data.route}}" target="_self">{{data.title}}' +
                        '
' +
                        '
' +
                        '

' +
                        '

' +
                        '{{data.title}}' +
                        '
' +
                        '
' +
                        '

' +
                        '

' +
                        ' 0}" ng-click="toggleShow(data);" style="cursor:pointer;">{{data.title}}' +
                        '
' +
                        '
' +
                        '

' +
                        '
');

                function replaceWithStandard (template) {
                    angular.forEach(scope.navList,function(key){
                        if(key.route && key.state){
                            console.error("Please use only one routing element in your navigation. Route or State, not both together!! ",key);
                            element.replaceWith($compile('NAV ERROR')(scope));
                            return false;
                        }
                    });
                    element.replaceWith($compile(template)(scope));
                }

                scope.app = ACTIVE_APP;

                scope.openAll = function (list) {
                    var found = false;
                    angular.forEach(list, function (value) {
                        if (value.children) {
                            var openLink = scope.openAll(value.children);
                            if (openLink) {
                                value.hide = 'nav-open';
                            }
                        }
                        if (value.route === $location.path()) {
                            found = true;
                        }
                    });
                    return found;
                };

                scope.toggleShow = function (data) {
                    if (data.hide === 'nav-close' || data.hide === undefined) {
                        data.hide = 'nav-open';
                    } else {
                        data.hide = 'nav-close';
                    }
                };

                scope.isActive = function (route) {
                    return route === $location.path();
                };

                scope.isActiveApp = function (app) {
                    return app === ACTIVE_APP;
                };

                scope.navList = $lxNavigation.getNavigation({
                    currentApp: ACTIVE_APP,
                    navName: scope.navName,
                    user: scope.navUser
                });

                if (scope.navList.length !== 0) {
                    angular.forEach(scope.navList, function (value) {
                        if (value.app === scope.app) {
                            value.hide = 'nav-open';
                        }
                    });
                    scope.openAll(scope.navList);
                }

                if (scope.navTemplatePath && scope.navTemplatePath.length > 3) {
                    $http.get(scope.navTemplatePath, {cache: $templateCache})
                        .success(function (tplGetContent) {
                            if (tplGetContent.substr(0, 5) !== '<!doc') {
                                replaceWithStandard(tplGetContent);
                            } else {
                                replaceWithStandard(tplContent);
                            }
                        })
                        .error(function () {
                            replaceWithStandard(tplContent);
                        });
                } else {
                    replaceWithStandard(tplContent);
                }
            }
        };
    });
<commit_msg>chore: fix eslint errors<commit_after>'use strict';
/*eslint no-else-return:0 */

angular.module('lx.navigation', [])
/**
 * @ngdoc object
 * @name lx.navigation.$lxNavigation
 *
 * @description
 * Service for navigation. Gets or sets the navigation.
 *
 * For more information look at the [guide](/lx_navigation).
 *
 */
    .provider('$lxNavigation', function () {
        var config = {};

        function cloneNavObject (value) {
            return {
                title: value.title,
                route: value.route,
                app: value.app,
                state: value.state,
                roles: value.roles
            };
        }

        function userHasAccess (user, navItem) {
            if (!navItem.roles && !navItem.resources || !user) {
                return true;
            }

            if (navItem.roles && !navItem.resources) {
                if (user.roles) {
                    for (var x = 0; x < navItem.roles.length; x++) {
                        for (var y = 0; y < user.roles.length; y++) {
                            if (navItem.roles[x] === user.roles[y]) {
                                return true;
                            }
                        }
                    }
                }

                return false;
            } else {
                if (user.acl) {
                    for (var z = 0; z < navItem.resources.length; z++) {
                        for (var w = 0; w < user.acl.length; w++) {
                            if (navItem.resources[z] === user.acl[w]) {
                                return true;
                            }
                        }
                    }
                }

                return false;
            }
        }

        function getUserNavigation (navigation, currentApp, user) {
            var result = [];

            angular.forEach(navigation, function (navItem) {
                if (navItem.children) {
                    var childList = getUserNavigation(navItem.children, currentApp, user);
                    var val = cloneNavObject(navItem);
                    val.children = childList;

                    if (userHasAccess(user, val)) {
                        result.push(val);
                    }
                } else if (userHasAccess(user, navItem)) {
                    result.push(cloneNavObject(navItem));
                }
            });

            return result;
        }

        /**
         * @ngdoc method
         * @name lx.navigation.$lxNavigation#set
         * @methodOf lx.navigation.$lxNavigation
         *
         * @description
         * Setup the navigation configuration
         *
         * @param {object} options The options for config
         */
        this.set = function (options) {
            options = options || {};

            // default settings
            config.navigation = options.navigation;
        };

        this.$get = function ($log) {
            var pub = {};

            /**
             * @ngdoc method
             * @name lx.navigation.$lxNavigation#getNavigation
             * @methodOf lx.navigation.$lxNavigation
             *
             * @description
             * ...
             *
             * @param {object} data The name of the navigation object, the user acl, the current app
             * @returns {Array} The navigation
             */
            pub.getNavigation = function (data) {
                var currentApp = data.currentApp || 'main';

                if (config.navigation && config.navigation[data.navName]) {
                    return getUserNavigation(config.navigation[data.navName], currentApp, data.user);
                } else {
                    if (!config.navigation) {
                        $log.info('No Navigation defined. Please define a navigation with the help of the $lxTransportProvider in the config section of your app.');
                    } else {
                        $log.error('Your defined nav-link-list "' + data.navName + '" is not defined!');
                    }

                    return [];
                }
            };

            return pub;
        };
    })
/**
 * @ngdoc directive
 * @name lx.navigation.directive:lxComNav
 * @restrict E
 *
 * @description
 * Creates the navigation in a flat list.
 *
 * For more information look at the [guide](/lxComNav).
 *
 * @param {string=} orientation The orientation of the list, horizontal or vertical.
 * @param {string} navLinklist The list with all navigation links.
 * @param {object=} navTemplatePath The path to a template which should overwrite the standard layout.
 *
 */
    .directive('lxComNav', function ($location, ACTIVE_APP, $http, $templateCache, $compile, $lxNavigation, $log) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                orientation: '@',
                navName: '@',
                navTemplatePath: '=',
                navUser: '='
            },
            link: function (scope, element) {

                var tplContent = '
' +
                    '
' +
                    '
' +
                    '{{item.title}}' +
                    '
' +
                    '
' +
                    '{{item.title}}' +
                    '{{item.title}}' +
                    '
' +
                    '
' +
                    '
';

                function replaceWithStandard (template) {
                    angular.forEach(scope.menu, function (key) {
                        if (key.route && key.state) {
                            $log.error('"Please use only one routing element in your navigation. Route or State, not both together!! ', key);
                            element.replaceWith($compile('NAV ERROR')(scope));
                            return false;
                        }
                    });
                    element.replaceWith($compile(template)(scope));
                }

                var orientation = scope.orientation || 'horizontal';
                element.toggleClass('nav-stacked', orientation === 'vertical');

                scope.menu = $lxNavigation.getNavigation({
                    currentApp: ACTIVE_APP,
                    navName: scope.navName,
                    user: scope.navUser
                });

                if (scope.navTemplatePath && scope.navTemplatePath.length > 3) {
                    $http.get(scope.navTemplatePath, {cache: $templateCache})
                        .success(function (tplGetContent) {
                            if (tplGetContent.substr(0, 5) !== '<!doc') {
                                replaceWithStandard(tplGetContent);
                            } else {
                                replaceWithStandard(tplContent);
                            }
                        })
                        .error(function () {
                            replaceWithStandard(tplContent);
                        });
                } else {
                    replaceWithStandard(tplContent);
                }

                scope.isActiveApp = function (app) {
                    return app === ACTIVE_APP;
                };

                scope.isActive = function (route) {
                    return route === $location.path();
                };
            }
        };
    })
/**
 * @ngdoc directive
 * @name lx.navigation.directive:lxComNavTree
 * @restrict E
 *
 * @description
 * Creates the navigation in a tree list.
 *
 * For more information look at the [guide](/lxComNavTree).
 *
 * @param {string} navLinklist The list with all navigation links.
 * @param {object=} navTemplatePath The path to a template which should overwrite the standard layout.
 *
 */
    .directive('lxComNavTree', function ($route, $location, $templateCache, ACTIVE_APP, $http, $compile, $lxNavigation, $log) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                navName: '@',
                navTemplatePath: '=',
                navUser: '='
            },
            link: function (scope, element) {

                var tplContent = '
' +
                    '
' +
                    '
' +
                    '
';

                $templateCache.put('lx_navigation/standard/nav_tree_inside',
                    '
' +
                    '

' +
                    '

' +
                    ' 0}" ng-href="{{data.route}}">{{data.title}}' +
                    ' 0}" ng-href="{{data.route}}" target="_self">{{data.title}}' +
                    '
' +
                    '
' +
                    '

' +
                    '

' +
                    '{{data.title}}' +
                    '
' +
                    '
' +
                    '

' +
                    '

' +
                    ' 0}" ng-click="toggleShow(data);" style="cursor:pointer;">{{data.title}}' +
                    '
' +
                    '
' +
                    '

' +
                    '
');

                function replaceWithStandard (template) {
                    angular.forEach(scope.navList, function (key) {
                        if (key.route && key.state) {
                            $log.error('Please use only one routing element in your navigation. Route or State, not both together!! ', key);
                            element.replaceWith($compile('NAV ERROR')(scope));
                            return false;
                        }
                    });
                    element.replaceWith($compile(template)(scope));
                }

                scope.app = ACTIVE_APP;

                scope.openAll = function (list) {
                    var found = false;
                    angular.forEach(list, function (value) {
                        if (value.children) {
                            var openLink = scope.openAll(value.children);
                            if (openLink) {
                                value.hide = 'nav-open';
                            }
                        }
                        if (value.route === $location.path()) {
                            found = true;
                        }
                    });
                    return found;
                };

                scope.toggleShow = function (data) {
                    if (data.hide === 'nav-close' || data.hide === undefined) {
                        data.hide = 'nav-open';
                    } else {
                        data.hide = 'nav-close';
                    }
                };

                scope.isActive = function (route) {
                    return route === $location.path();
                };

                scope.isActiveApp = function (app) {
                    return app === ACTIVE_APP;
                };

                scope.navList = $lxNavigation.getNavigation({
                    currentApp: ACTIVE_APP,
                    navName: scope.navName,
                    user: scope.navUser
                });

                if (scope.navList.length !== 0) {
                    angular.forEach(scope.navList, function (value) {
                        if (value.app === scope.app) {
                            value.hide = 'nav-open';
                        }
                    });
                    scope.openAll(scope.navList);
                }

                if (scope.navTemplatePath && scope.navTemplatePath.length > 3) {
                    $http.get(scope.navTemplatePath, {cache: $templateCache})
                        .success(function (tplGetContent) {
                            if (tplGetContent.substr(0, 5) !== '<!doc') {
                                replaceWithStandard(tplGetContent);
                            } else {
                                replaceWithStandard(tplContent);
                            }
                        })
                        .error(function () {
                            replaceWithStandard(tplContent);
                        });
                } else {
                    replaceWithStandard(tplContent);
                }
            }
        };
    });
<|endoftext|>


<commit_before>const e = require('eris')

// Please edit config.json with your token.
const conf = JSON.parse(require('fs').readFileSync('config.json', 'utf8'))

// You may change this desc, the owner, and prefix.
const bot = new e.CommandClient(conf.token, {}, {
  description: conf.desc,
  owner: 'Someone',
  prefix: conf.prefix
})

bot.on('ready', () => {
  console.log('dbot - discord responded with ready')
})

bot.registerCommand('about', 'my name is dbot and I live in `' + require('os').hostname() + '` https://github.com/tilda/dbot', {
  description: 'who am I? run this to find out',
  fullDescription: ':thinking:'
})

bot.registerCommand('generic', 'generic sucks', {
  description: 'what is generic',
  fullDescription: 'lmao im gonan die'
})

bot.on('messageCreate', (msg, args, err) => {
  if (msg.content === conf.prefix + 'shutdown') {
    if (msg.author.id === conf.owner) {
      bot.createMessage(msg.channel.id, 'ok bye')
      process.exit(1)
    } else {
      bot.createMessage(msg.channel.id, 'no')
    }
  }
  if (msg.content === conf.prefix + 'exec') {
    if (msg.author.id === conf.owner) {
      const lol = require('shelljs').exec(args.toString())
      if (lol.code !== 0) {
        bot.createMessage(msg.channel.id, 'Error!\n\`\`\`' + err.toString() + '\n\`\`\`')
      } else {
	 bot.createMessage(msg.channel.id, 'Success \`\`\`\n' + lol + '\n\`\`\`')
      }}}

bot.connect()
<commit_msg>[bot, core, eval]  me_irl<commit_after>const e = require('eris')

// Please edit config.json with your token.
const conf = JSON.parse(require('fs').readFileSync('config.json', 'utf8'))

// You may change this desc, the owner, and prefix.
const bot = new e.CommandClient(conf.token, {}, {
  description: conf.desc,
  owner: 'Someone',
  prefix: conf.prefix
})

bot.on('ready', () => {
  console.log('dbot - discord responded with ready')
})

bot.registerCommand('about', 'my name is dbot and I live in `' + require('os').hostname() + '` https://github.com/tilda/dbot', {
  description: 'who am I? run this to find out',
  fullDescription: ':thinking:'
})

bot.registerCommand('generic', 'generic sucks', {
  description: 'what is generic',
  fullDescription: 'lmao im gonan die'
})

bot.on('messageCreate', (msg, args, err) => {
  if (msg.content === conf.prefix + 'shutdown') {
    if (msg.author.id === conf.owner) {
      bot.createMessage(msg.channel.id, 'ok bye')
      process.exit(1)
    } else {
      bot.createMessage(msg.channel.id, 'no')
    }
  }
  if (msg.content === conf.prefix + 'exec') {
    if (msg.author.id === conf.owner) {
      const lol = require('shelljs').exec(args.toString())
      if (lol.code !== 0) {
        bot.createMessage(msg.channel.id, 'Error!\n\`\`\`' + err.toString() + '\n\`\`\`')
      } else {
	 bot.createMessage(msg.channel.id, 'Success \`\`\`\n' + lol + '\n\`\`\`')
      }}})

bot.connect()
<|endoftext|>


<commit_before>'use strict';

const test = require('ava');
const fileType = require('file-type');
const config = require('../../test-config.json');
const docusign = require('../../docusign');
const dsUtils = require('../../dsUtils');

let client = null;
let envelopeId = config.envelopeId;
let templateId = config.templateId;

test.before(function envelopesBefore (t) {
  return docusign.init(config.integratorKey, config.apiEnv, config.debug)
  .then(response => {
    t.ok(response.message === 'successfully initialized');
    return docusign.createClient(config.email, config.password);
  })
  .then(_client => {
    client = _client;
  });
});

test.after(function envelopesAfter (t) {
  return client.logOut();
});

test(function getConsoleUrl (t) {
  return client.envelopes.getConsoleUrl()
  .then(response => {
    let regex = new RegExp('https://demo.docusign.net/Member/StartInSession.aspx?');
    t.ok(response.url);
    t.ok(regex.test(response.url));
  });
});

test(function getEnvelopeInfo (t) {
  return client.envelopes.getEnvelopeInfo(envelopeId)
  .then(response => {
    t.ok(response.status);
    t.ok(response.documentsUri);
    t.ok(response.envelopeUri);
    t.ok(response.recipientsUri);
  });
});

test('getSignedDocuments', t => {
  let encoding = null;
  let attachCertificate = true;
  return client.envelopes.getSignedDocuments(envelopeId, encoding, attachCertificate)
  .then(response => {
    t.same('pdf', fileType(response).ext);
  });
});

test('[getSignedDocuments] 404 on get non-existent signed documents', t => {
  let nonExistentEnvelopeId = dsUtils.generateNewGuid();
  let encoding = null;
  let attachCertificate = true;
  return client.envelopes.getSignedDocuments(nonExistentEnvelopeId, encoding, attachCertificate)
  .then(response => {
    t.notOk(response, 'Got response, expected none');
  })
  .catch(error => {
    t.ok(error.statusCode === 404, 'Unexpected status code: ' + error.statusCode);
  });
});

test(function getEnvelopeList (t) {
  let date = new Date();
  if (date.getMonth() !== 0) {
    date.setMonth(date.getMonth() - 1);
  } else {
    date.setMonth(12);
    date.setYear(date.getYear() - 1);
  }
  return client.envelopes.getEnvelopeList(date)
  .then(response => {
    t.ok(response);
    t.ok(response.envelopes.length > 0);
    t.ok(response.totalSetSize);
    t.ok(response.resultSetSize);
  });
});

test(function getRecipients (t) {
  return client.envelopes.getRecipients(envelopeId)
  .then(response => {
    t.ok(response.signers);
    t.ok(response.signers[0].isBulkRecipient);
    t.ok(response.signers[0].name);
    t.ok(response.signers[0].email);
    t.ok(response.signers[0].recipientId);
    t.ok(response.signers[0].recipientIdGuid);
    t.ok(response.signers[0].requireIdLookup);
    t.ok(response.signers[0].userId);
  });
});

test(function getView (t) {
  let action = 'send';
  let fullName = 'DocuSign NPM';
  let email = config.email;
  let files = [{
    name: 'SampleDocument.pdf',
    extension: 'pdf',
    source: {
      type: 'path',
      content: 'test/SampleDocument.pdf'
    }
  }];
  let returnUrl = 'http://www.docusign.com/devcenter';
  let event = null;

  return client.envelopes.getView(action, fullName, email, files, returnUrl, event)
  .then(response => {
    var regex = new RegExp('https://demo.docusign.net/Member/StartInSession.aspx?');
    t.ok(response.url);
    t.ok(response.envelopeId);
    t.ok(regex.test(response.url));
  });
});

test(function getTemplateView (t) {
  return client.envelopes.getTemplateView(templateId, 'http://www.docusign.com/devcenter')
  .then(response => {
    var regex = new RegExp('https://demo.docusign.net/Member/StartInSession.aspx?');
    t.ok(response.url);
    t.ok(regex.test(response.url));
  });
});
<commit_msg>add sendEnvelope test<commit_after>'use strict';

const test = require('ava');
const fileType = require('file-type');
const config = require('../../test-config.json');
const docusign = require('../../docusign');
const dsUtils = require('../../dsUtils');

let client = null;
let envelopeId = config.envelopeId;
let templateId = config.templateId;
let fullName = 'DocuSign NPM';
let email = config.email;
let files = [{
  name: 'SampleDocument.pdf',
  extension: 'pdf',
  source: {
    type: 'path',
    content: 'test/SampleDocument.pdf'
  }
}];

test.before(function envelopesBefore (t) {
  return docusign.init(config.integratorKey, config.apiEnv, config.debug)
  .then(response => {
    t.ok(response.message === 'successfully initialized');
    return docusign.createClient(config.email, config.password);
  })
  .then(_client => {
    client = _client;
  });
});

test.after(function envelopesAfter (t) {
  return client.logOut();
});

test(function getConsoleUrl (t) {
  return client.envelopes.getConsoleUrl()
  .then(response => {
    let regex = new RegExp('https://demo.docusign.net/Member/StartInSession.aspx?');
    t.ok(response.url);
    t.ok(regex.test(response.url));
  });
});

test(function getEnvelopeInfo (t) {
  return client.envelopes.getEnvelopeInfo(envelopeId)
  .then(response => {
    t.ok(response.status);
    t.ok(response.documentsUri);
    t.ok(response.envelopeUri);
    t.ok(response.recipientsUri);
  });
});

test('getSignedDocuments', t => {
  let encoding = null;
  let attachCertificate = true;
  return client.envelopes.getSignedDocuments(envelopeId, encoding, attachCertificate)
  .then(response => {
    t.same('pdf', fileType(response).ext);
  });
});

test('[getSignedDocuments] 404 on get non-existent signed documents', t => {
  let nonExistentEnvelopeId = dsUtils.generateNewGuid();
  let encoding = null;
  let attachCertificate = true;
  return client.envelopes.getSignedDocuments(nonExistentEnvelopeId, encoding, attachCertificate)
  .then(response => {
    t.notOk(response, 'Got response, expected none');
  })
  .catch(error => {
    t.ok(error.statusCode === 404, 'Unexpected status code: ' + error.statusCode);
  });
});

test(function getEnvelopeList (t) {
  let date = new Date();
  if (date.getMonth() !== 0) {
    date.setMonth(date.getMonth() - 1);
  } else {
    date.setMonth(12);
    date.setYear(date.getYear() - 1);
  }
  return client.envelopes.getEnvelopeList(date)
  .then(response => {
    t.ok(response);
    t.ok(response.envelopes.length > 0);
    t.ok(response.totalSetSize);
    t.ok(response.resultSetSize);
  });
});

test(function getRecipients (t) {
  return client.envelopes.getRecipients(envelopeId)
  .then(response => {
    t.ok(response.signers);
    t.ok(response.signers[0].isBulkRecipient);
    t.ok(response.signers[0].name);
    t.ok(response.signers[0].email);
    t.ok(response.signers[0].recipientId);
    t.ok(response.signers[0].recipientIdGuid);
    t.ok(response.signers[0].requireIdLookup);
    t.ok(response.signers[0].userId);
  });
});

test(function getView (t) {
  let action = 'send';
  let returnUrl = 'http://www.docusign.com/devcenter';
  let event = null;

  return client.envelopes.getView(action, fullName, email, files, returnUrl, event)
  .then(response => {
    var regex = new RegExp('https://demo.docusign.net/Member/StartInSession.aspx?');
    t.ok(response.url);
    t.ok(response.envelopeId);
    t.ok(regex.test(response.url));
  });
});

test(function getTemplateView (t) {
  return client.envelopes.getTemplateView(templateId, 'http://www.docusign.com/devcenter')
  .then(response => {
    var regex = new RegExp('https://demo.docusign.net/Member/StartInSession.aspx?');
    t.ok(response.url);
    t.ok(regex.test(response.url));
  });
});

test(function sendEnvelope (t) {
  let emailSubject = 'DocuSign API - Signature Request on Document Call';
  let recipients = {
    signers: [{
      'email': config.email,
      'name': fullName,
      'recipientId': 1,
      'tabs': {
        'signHereTabs': [{
          'xPosition': '100',
          'yPosition': '100',
          'documentId': '1',
          'pageNumber': '1'
        }]
      }
    }]
  };
  let additionalParams = {};
  return client.envelopes.sendEnvelope(recipients, emailSubject, files, additionalParams)
  .then(response => {
    t.ok(response.envelopeId);
    t.ok(response.uri);
    t.ok(response.status === 'sent');
  });
});
<|endoftext|>


<commit_before>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Provides the namesspace for client-side communication
 * between pages originating from different domains (it works also
 * with pages from the same domain, but doing that is kinda
 * pointless).
 *
 * The only publicly visible class is goog.net.xpc.CrossPageChannel.
 *
 * Note: The preferred name for the main class would have been
 * CrossDomainChannel.  But as there already is a class named like
 * that (which serves a different purpose) in the maps codebase,
 * CrossPageChannel was chosen to avoid confusion.
 *
 * CrossPageChannel abstracts the underlying transport mechanism to
 * provide a common interface in all browsers.
 *
 */

/*
TODO(user)
- resolve fastback issues in Safari (IframeRelayTransport)
 */

/**
 * Namespace for CrossPageChannel
 */
goog.provide('goog.net.xpc');

goog.require('goog.debug.Logger');

/**
 * Enum used to identify transport types.
 * @enum {number}
 */
goog.net.xpc.TransportTypes = {
  NATIVE_MESSAGING: 1,
  FRAME_ELEMENT_METHOD: 2,
  IFRAME_RELAY: 3,
  IFRAME_POLLING: 4,
  FLASH: 5,
  NIX: 6
};

/**
 * Enum containing transport names. These need to correspond to the
 * transport class names for createTransport_() to work.
 * @type {Object}
 */
goog.net.xpc.TransportNames = {
  '1': 'NativeMessagingTransport',
  '2': 'FrameElementMethodTransport',
  '3': 'IframeRelayTransport',
  '4': 'IframePollingTransport',
  '5': 'FlashTransport',
  '6': 'NixTransport'
};

// TODO(user): Add auth token support to other methods.

/**
 * Field names used on configuration object.
 * @type {Object}
 */
goog.net.xpc.CfgFields = {
  /**
   * Channel name identifier.
   * Both peers have to be initialized with
   * the same channel name.  If not present, a channel name is
   * generated (which then has to transferred to the peer somehow).
   */
  CHANNEL_NAME: 'cn',
  /**
   * Authorization token. If set, NIX will use this authorization token
   * to validate the setup.
   */
  AUTH_TOKEN: 'at',
  /**
   * Remote party's authorization token. If set, NIX will validate this
   * authorization token against that sent by the other party.
   */
  REMOTE_AUTH_TOKEN: 'rat',
  /**
   * The URI of the peer page.
   */
  PEER_URI: 'pu',
  /**
   * Ifame-ID identifier.
   * The id of the iframe element the peer-document lives in.
   */
  IFRAME_ID: 'ifrid',
  /**
   * Transport type identifier.
   * The transport type to use. Possible values are entries from
   * goog.net.xpc.TransportTypes. If not present, the transport is
   * determined automatically based on the useragent's capabilities.
   */
  TRANSPORT: 'tp',
  /**
   * Local relay URI identifier (IframeRelayTransport-specific).
   * The URI (can't contain a fragment identifier) used by the peer to
   * relay data through.
   */
  LOCAL_RELAY_URI: 'lru',
  /**
   * Peer relay URI identifier (IframeRelayTransport-specific).
   * The URI (can't contain a fragment identifier) used to relay data
   * to the peer.
   */
  PEER_RELAY_URI: 'pru',
  /**
   * Local poll URI identifier (IframePollingTransport-specific).
   * The URI  (can't contain a fragment identifier)which is polled
   * to receive data from the peer.
   */
  LOCAL_POLL_URI: 'lpu',
  /**
   * Local poll URI identifier (IframePollingTransport-specific).
   * The URI (can't contain a fragment identifier) used to send data
   * to the peer.
   */
  PEER_POLL_URI: 'ppu',
  /**
   * The hostname of the peer window, including protocol, domain, and port
   * (if specified). Used for security sensitive applications that make
   * use of NativeMessagingTransport (i.e. most applications).
   */
  PEER_HOSTNAME: 'ph'
};

/**
 * @enum {number}
 */
goog.net.xpc.ChannelStates = {
  NOT_CONNECTED: 1,
  CONNECTED: 2,
  CLOSED: 3
};

/**
 * The name of the transport service (used for internal signalling).
 * @type {string}
 * @private
 */
goog.net.xpc.TRANSPORT_SERVICE_ = 'tp';

/**
 * Transport signaling message: setup.
 * @protected
 */
goog.net.xpc.SETUP = 'SETUP';

/**
 * Transport signaling message: setup acknowledgement.
 * @private
 */
goog.net.xpc.SETUP_ACK_ = 'SETUP_ACK';

/**
 * Object holding active channels.
 * @type {Object}
 * @private
 */
goog.net.xpc.channels_ = {};

/**
 * Returns a random string.
 * @param {number} length How many characters the string shall contain.
 * @param {string=} opt_characters The characters used.
 * @return {string} The random string.
 */
goog.net.xpc.getRandomString = function(length, opt_characters) {
  var chars = opt_characters || goog.net.xpc.randomStringCharacters_;
  var charsLength = chars.length;
  var s = '';
  while (length-- > 0) {
    s += chars.charAt(Math.floor(Math.random() * charsLength));
  }
  return s;
};

/**
 * The default characters used for random string generation.
 * @type {string}
 * @private
 */
goog.net.xpc.randomStringCharacters_ =
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

/**
 * The logger.
 * @type {goog.debug.Logger}
 */
goog.net.xpc.logger = goog.debug.Logger.getLogger('goog.net.xpc');
<commit_msg><commit_after>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Provides the namesspace for client-side communication
 * between pages originating from different domains (it works also
 * with pages from the same domain, but doing that is kinda
 * pointless).
 *
 * The only publicly visible class is goog.net.xpc.CrossPageChannel.
 *
 * Note: The preferred name for the main class would have been
 * CrossDomainChannel.  But as there already is a class named like
 * that (which serves a different purpose) in the maps codebase,
 * CrossPageChannel was chosen to avoid confusion.
 *
 * CrossPageChannel abstracts the underlying transport mechanism to
 * provide a common interface in all browsers.
 *
 */

/*
TODO(user)
- resolve fastback issues in Safari (IframeRelayTransport)
 */

/**
 * Namespace for CrossPageChannel
 */
goog.provide('goog.net.xpc');
goog.provide('goog.net.xpc.CfgFields');
goog.provide('goog.net.xpc.ChannelStates');
goog.provide('goog.net.xpc.TransportNames');
goog.provide('goog.net.xpc.TransportTypes');
goog.provide('goog.net.xpc.UriCfgFields');

goog.require('goog.debug.Logger');

/**
 * Enum used to identify transport types.
 * @enum {number}
 */
goog.net.xpc.TransportTypes = {
  NATIVE_MESSAGING: 1,
  FRAME_ELEMENT_METHOD: 2,
  IFRAME_RELAY: 3,
  IFRAME_POLLING: 4,
  FLASH: 5,
  NIX: 6
};

/**
 * Enum containing transport names. These need to correspond to the
 * transport class names for createTransport_() to work.
 * @type {Object}
 */
goog.net.xpc.TransportNames = {
  '1': 'NativeMessagingTransport',
  '2': 'FrameElementMethodTransport',
  '3': 'IframeRelayTransport',
  '4': 'IframePollingTransport',
  '5': 'FlashTransport',
  '6': 'NixTransport'
};

// TODO(user): Add auth token support to other methods.

/**
 * Field names used on configuration object.
 * @type {Object}
 */
goog.net.xpc.CfgFields = {
  /**
   * Channel name identifier.
   * Both peers have to be initialized with
   * the same channel name.  If not present, a channel name is
   * generated (which then has to transferred to the peer somehow).
   */
  CHANNEL_NAME: 'cn',
  /**
   * Authorization token. If set, NIX will use this authorization token
   * to validate the setup.
   */
  AUTH_TOKEN: 'at',
  /**
   * Remote party's authorization token. If set, NIX will validate this
   * authorization token against that sent by the other party.
   */
  REMOTE_AUTH_TOKEN: 'rat',
  /**
   * The URI of the peer page.
   */
  PEER_URI: 'pu',
  /**
   * Ifame-ID identifier.
   * The id of the iframe element the peer-document lives in.
   */
  IFRAME_ID: 'ifrid',
  /**
   * Transport type identifier.
   * The transport type to use. Possible values are entries from
   * goog.net.xpc.TransportTypes. If not present, the transport is
   * determined automatically based on the useragent's capabilities.
   */
  TRANSPORT: 'tp',
  /**
   * Local relay URI identifier (IframeRelayTransport-specific).
   * The URI (can't contain a fragment identifier) used by the peer to
   * relay data through.
   */
  LOCAL_RELAY_URI: 'lru',
  /**
   * Peer relay URI identifier (IframeRelayTransport-specific).
   * The URI (can't contain a fragment identifier) used to relay data
   * to the peer.
   */
  PEER_RELAY_URI: 'pru',
  /**
   * Local poll URI identifier (IframePollingTransport-specific).
   * The URI  (can't contain a fragment identifier)which is polled
   * to receive data from the peer.
   */
  LOCAL_POLL_URI: 'lpu',
  /**
   * Local poll URI identifier (IframePollingTransport-specific).
   * The URI (can't contain a fragment identifier) used to send data
   * to the peer.
   */
  PEER_POLL_URI: 'ppu',
  /**
   * The hostname of the peer window, including protocol, domain, and port
   * (if specified). Used for security sensitive applications that make
   * use of NativeMessagingTransport (i.e. most applications).
   */
  PEER_HOSTNAME: 'ph'
};

/**
 * @enum {number}
 */
goog.net.xpc.ChannelStates = {
  NOT_CONNECTED: 1,
  CONNECTED: 2,
  CLOSED: 3
};

/**
 * The name of the transport service (used for internal signalling).
 * @type {string}
 * @private
 */
goog.net.xpc.TRANSPORT_SERVICE_ = 'tp';

/**
 * Transport signaling message: setup.
 * @protected
 */
goog.net.xpc.SETUP = 'SETUP';

/**
 * Transport signaling message: setup acknowledgement.
 * @private
 */
goog.net.xpc.SETUP_ACK_ = 'SETUP_ACK';

/**
 * Object holding active channels.
 * @type {Object}
 * @private
 */
goog.net.xpc.channels_ = {};

/**
 * Returns a random string.
 * @param {number} length How many characters the string shall contain.
 * @param {string=} opt_characters The characters used.
 * @return {string} The random string.
 */
goog.net.xpc.getRandomString = function(length, opt_characters) {
  var chars = opt_characters || goog.net.xpc.randomStringCharacters_;
  var charsLength = chars.length;
  var s = '';
  while (length-- > 0) {
    s += chars.charAt(Math.floor(Math.random() * charsLength));
  }
  return s;
};

/**
 * The default characters used for random string generation.
 * @type {string}
 * @private
 */
goog.net.xpc.randomStringCharacters_ =
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

/**
 * The logger.
 * @type {goog.debug.Logger}
 */
goog.net.xpc.logger = goog.debug.Logger.getLogger('goog.net.xpc');
<|endoftext|>


<commit_before>var quadToDay = {
	"A": "Monday",
	"B": "Thursday",
	"C": "Tuesday",
	"D": "Friday",
	"E": "Daily"
};

var quads = L.geoJson(quadsJson);

function onLocationFound(ll) {
	var layer = leafletPip.pointInLayer(ll, quads);
	if (layer.length) {
		var quad = layer[0].feature.properties.QUAD;
		var pickupDay = quadToDay[quad];
	};

	document.getElementById('day').innerHTML = layer.length ? '
Your trash gets picked up on ' + pickupDay + '
' : '
Address outside of service area.
';
};

$('#geocode').submit(function(e) {
	var address = $('#formValueId').val();
	var url = 'http://nominatim.openstreetmap.org/search?q='+ encodeURIComponent(address) +'&format=json&limit-1&addressdetails=1';
	$.getJSON(url, function(data) {
		var lat = data[0].lat;
		var lon = data[0].lon;

		document.getElementById('coords').innerHTML = '
Your address is located at [' + lat + ', ' + lon + '].
';

		onLocationFound(L.latLng(lat, lon));
	});
	e.preventDefault();
});<commit_msg>changed service area to urban service area<commit_after>var quadToDay = {
	"A": "Monday",
	"B": "Thursday",
	"C": "Tuesday",
	"D": "Friday",
	"E": "Daily"
};

var quads = L.geoJson(quadsJson);

function onLocationFound(ll) {
	var layer = leafletPip.pointInLayer(ll, quads);
	if (layer.length) {
		var quad = layer[0].feature.properties.QUAD;
		var pickupDay = quadToDay[quad];
	};

	document.getElementById('day').innerHTML = layer.length ? '
Your trash gets picked up on ' + pickupDay + '
' : '
Address outside of urban service area.
';
};

$('#geocode').submit(function(e) {
	var address = $('#formValueId').val();
	var url = 'http://nominatim.openstreetmap.org/search?q='+ encodeURIComponent(address) +'&format=json&limit-1&addressdetails=1';
	$.getJSON(url, function(data) {
		var lat = data[0].lat;
		var lon = data[0].lon;

		document.getElementById('coords').innerHTML = '
Your address is located at [' + lat + ', ' + lon + '].
';

		onLocationFound(L.latLng(lat, lon));
	});
	e.preventDefault();
});<|endoftext|>


<commit_before>"use babel";

describe('The prolog-linter for AtomLinter', () => {
  const lint = require('../lib/linter-prolog').provideLinter().lint;

  beforeEach(() => {
    waitsForPromise(() => {
      return atom.packages.activatePackage("linter-prolog");
    });
  });

  it('finds a simple syntax error', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/simple_syntax_error.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(1);
          expect(messages[0].type).toBeDefined();
          expect(messages[0].type).toEqual('error');
          expect(messages[0].text).toBeDefined();
          expect(messages[0].text).toEqual('Syntax error: Unexpected end of file');
          expect(messages[0].filePath).toBeDefined();
          expect(messages[0].filePath).toMatch(/.+simple_syntax_error\.pl$/);
          expect(messages[0].range).toBeDefined();
          expect(messages[0].range.length).toEqual(2);
          expect(messages[0].range).toEqual([[0, 7], [0, 7]]);
        });
      });
    });
  });

  it('finds nothing wrong with an empty file', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/empty.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(0);
        });
      });
    });
  });

  it('finds nothing wrong with a simple implementation of append', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/append.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(0);
        });
      });
    });
  });

  it('find errors in filepath with whitespace', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/file space.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(1);
        });
      });
    });
  });

  it('finds singleton variable warnings', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/singleton_warning.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(1);
          expect(messages[0].type).toBeDefined();
          expect(messages[0].type).toEqual('warning');
          expect(messages[0].text).toBeDefined();
          expect(messages[0].text).toEqual('Singleton variables: [X]');
          expect(messages[0].filePath).toBeDefined();
          expect(messages[0].filePath).toMatch(/.+singleton_warning\.pl$/);
          expect(messages[0].range).toBeDefined();
          expect(messages[0].range.length).toEqual(2);
          expect(messages[0].range).toEqual([[0, 0], [0, 0]]);
        });
      });
    });
  });
});
<commit_msg>adapt test cases to linter v2 api<commit_after>"use babel";

describe('The prolog-linter for AtomLinter', () => {
  const lint = require('../lib/linter-prolog').provideLinter().lint;

  beforeEach(() => {
    waitsForPromise(() => {
      return atom.packages.activatePackage("linter-prolog");
    });
  });

  it('finds a simple syntax error', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/simple_syntax_error.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(1);
          expect(messages[0].severity).toBeDefined();
          expect(messages[0].severity).toEqual('error');
          expect(messages[0].excerpt).toBeDefined();
          expect(messages[0].excerpt).toEqual('Syntax error: Unexpected end of file');
          expect(messages[0].location.file).toBeDefined();
          expect(messages[0].location.file).toMatch(/.+simple_syntax_error\.pl$/);
          expect(messages[0].location.position).toBeDefined();
          expect(messages[0].location.position.length).toEqual(2);
          expect(messages[0].location.position).toEqual([[0, 7], [0, 7]]);
        });
      });
    });
  });

  it('finds nothing wrong with an empty file', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/empty.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(0);
        });
      });
    });
  });

  it('finds nothing wrong with a simple implementation of append', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/append.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(0);
        });
      });
    });
  });

  it('find errors in filepath with whitespace', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/file space.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(1);
        });
      });
    });
  });

  it('finds singleton variable warnings', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/singleton_warning.pl').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(1);
          expect(messages[0].severity).toBeDefined();
          expect(messages[0].severity).toEqual('warning');
          expect(messages[0].excerpt).toBeDefined();
          expect(messages[0].excerpt).toEqual('Singleton variables: [X]');
          expect(messages[0].location.file).toBeDefined();
          expect(messages[0].location.file).toMatch(/.+singleton_warning\.pl$/);
          expect(messages[0].location.position).toBeDefined();
          expect(messages[0].location.position.length).toEqual(2);
          expect(messages[0].location.position).toEqual([[0, 0], [0, 0]]);
        });
      });
    });
  });
});
<|endoftext|>