<commit_before>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-totvs-dev:app', function () {

    var configFiles = [
            '.editorconfig',
            '.bowerrc',
            'bower.json',
            '.gitignore',
            '.jshintrc',
            '.jscsrc',
            'package.json'
        ],

        appFiles = [
            'src/app/index.html',
            'src/app/js/totvs-app.module.js',
            'src/app/js/totvs-app.config.js',
            'src/app/js/totvs-app.route.js'
        ],

        assetsFiles = [
            'src/app/assets/css/app.less',
            'src/app/assets/css/app.css',
            'src/app/assets/img/favicon.ico',
            'src/app/assets/img/loading.gif',
            'src/app/assets/img/totvs.png',
            'src/app/assets/img/icon-home.png',
            'src/app/assets/img/icon-help.png',
            'src/app/assets/img/icon-cfg.png',
            'src/app/assets/img/icon-off.png'
        ],

        desktopFiles = [
            'src/app/js/totvs-desktop/totvs-desktop.module.js',
            'src/app/js/totvs-desktop/totvs-desktop.controller.js',
            'src/app/js/totvs-desktop/totvs-desktop-header.directive.js',
            'src/app/js/totvs-desktop/totvs-desktop-tab.directive.js',
            'src/app/js/totvs-desktop/totvs-desktop-tab.service.js',
            'src/app/js/totvs-desktop/totvs-desktop-view.service.js'
        ],

        menuFiles = [
            'src/app/js/totvs-menu/totvs-menu-favorites.factory.js',
            'src/app/js/totvs-menu/totvs-menu-processes.factory.js',
            'src/app/js/totvs-menu/totvs-menu-programs.factory.js',
            'src/app/js/totvs-menu/totvs-menu-recents.factory.js',
            'src/app/js/totvs-menu/totvs-menu.constant.js',
            'src/app/js/totvs-menu/totvs-menu.controller.js',
            'src/app/js/totvs-menu/totvs-menu.module.js',
            'src/app/js/totvs-menu/totvs-menu.view.html'
        ],

        sampleCRUDFiles = [
            'src/app/js/customers/customer-edit.controller.js',
            'src/app/js/customers/customer-edit.view.html',
            'src/app/js/customers/customer-list.controller.js',
            'src/app/js/customers/customer-list.view.html',
            'src/app/js/customers/customer-search.controller.js',
            'src/app/js/customers/customer-search.view.html',
            'src/app/js/customers/customer.factory.js',
            'src/app/js/customers/customer.module.js',
            'src/app/js/customers/customer.route.js',
            'src/app/js/customers/i18n/translations.js'
        ],

        sampleDashboardFiles = [
            'src/app/js/dashboard/dashboard-settings.controller.js',
            'src/app/js/dashboard/dashboard-settings.view.html',
            'src/app/js/dashboard/dashboard.controller.js',
            'src/app/js/dashboard/dashboard.factory.js',
            'src/app/js/dashboard/dashboard.module.js',
            'src/app/js/dashboard/dashboard.route.js',
            'src/app/js/dashboard/dashboard.view.html',
            'src/app/js/dashboard/widgets/widget-area.controller.js',
            'src/app/js/dashboard/widgets/widget-area.view.html',
            'src/app/js/dashboard/widgets/widget-pie.controller.js',
            'src/app/js/dashboard/widgets/widget-pie.view.html',
            'src/app/js/dashboard/widgets/widget-table.controller.js',
            'src/app/js/dashboard/widgets/widget-table.view.html',
            'src/app/js/dashboard/widgets/widget.module.js',
            'src/app/js/dashboard/assets/css/dashboard.style.css',
            'src/app/js/dashboard/i18n/translations.js'
        ];

    describe('default answers', function() {

        before(function () {
            return helpers.run(path.join(__dirname, '../generators/app'))
                .withPrompts({})
                .toPromise();
        });

        it('Creates files config', function () {
            assert.file(configFiles);
        });

        it('Creates files app', function () {
            assert.file(appFiles);
        });

        it('Creates files assets', function () {
            assert.file(assetsFiles);
        });

        it('Creates files i18n', function () {
            assert.file([
                'src/app/i18n/translations.js'
            ]);
        });

        it('Creates files desktop', function () {
            assert.file(desktopFiles);
        });

        it('Creates files menu', function () {
            assert.file(menuFiles);
        });

        it('Creates files Sample CRUD', function () {
            assert.file(sampleCRUDFiles);
        });

        it('Creates files Sample Dashboard', function () {
            assert.file(sampleDashboardFiles);
        });

    });

    /*describe('no UI Router', function() {

        before(function () {
            return helpers.run(path.join(__dirname, '../generators/app'))
                .withPrompts({})
                .toPromise();
        });

        assert.fileContent('src/app/index.html', 'angular');
    });*/

    describe('no Samples', function() {

        before(function () {
            return helpers.run(path.join(__dirname, '../generators/app'))
                .withPrompts({samples: []})
                .toPromise();
        });

        it('No creates files CRUD', function () {
            assert.noFile(sampleCRUDFiles);
        });

        it('No creates files Dashboard', function () {
            assert.noFile(sampleDashboardFiles);
        });

    });
});
<commit_msg>test sample crud<commit_after>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-totvs-dev:app', function () {

    var configFiles = [
            '.editorconfig',
            '.bowerrc',
            'bower.json',
            '.gitignore',
            '.jshintrc',
            '.jscsrc',
            'package.json'
        ],

        appFiles = [
            'src/app/index.html',
            'src/app/js/totvs-app.module.js',
            'src/app/js/totvs-app.config.js',
            'src/app/js/totvs-app.route.js'
        ],

        assetsFiles = [
            'src/app/assets/css/app.less',
            'src/app/assets/css/app.css',
            'src/app/assets/img/favicon.ico',
            'src/app/assets/img/loading.gif',
            'src/app/assets/img/totvs.png',
            'src/app/assets/img/icon-home.png',
            'src/app/assets/img/icon-help.png',
            'src/app/assets/img/icon-cfg.png',
            'src/app/assets/img/icon-off.png'
        ],

        desktopFiles = [
            'src/app/js/totvs-desktop/totvs-desktop.module.js',
            'src/app/js/totvs-desktop/totvs-desktop.controller.js',
            'src/app/js/totvs-desktop/totvs-desktop-header.directive.js',
            'src/app/js/totvs-desktop/totvs-desktop-tab.directive.js',
            'src/app/js/totvs-desktop/totvs-desktop-tab.service.js',
            'src/app/js/totvs-desktop/totvs-desktop-view.service.js'
        ],

        menuFiles = [
            'src/app/js/totvs-menu/totvs-menu-favorites.factory.js',
            'src/app/js/totvs-menu/totvs-menu-processes.factory.js',
            'src/app/js/totvs-menu/totvs-menu-programs.factory.js',
            'src/app/js/totvs-menu/totvs-menu-recents.factory.js',
            'src/app/js/totvs-menu/totvs-menu.constant.js',
            'src/app/js/totvs-menu/totvs-menu.controller.js',
            'src/app/js/totvs-menu/totvs-menu.module.js',
            'src/app/js/totvs-menu/totvs-menu.view.html'
        ],

        sampleCRUDFiles = [
            'src/app/js/customers/customers-detail.controller.js',
            'src/app/js/customers/customers-detail.view.html',
            'src/app/js/customers/customers-edit.controller.js',
            'src/app/js/customers/customers-edit.view.html',
            'src/app/js/customers/customers-list.controller.js',
            'src/app/js/customers/customers-list.view.html',
            'src/app/js/customers/customers-search.controller.js',
            'src/app/js/customers/customers-search.view.html',
            'src/app/js/customers/customers.factory.js',
            'src/app/js/customers/customers.module.js',
            'src/app/js/customers/customers.route.js',
            'src/app/js/customers/i18n/translations.js'
        ],

        sampleDashboardFiles = [
            'src/app/js/dashboard/dashboard-settings.controller.js',
            'src/app/js/dashboard/dashboard-settings.view.html',
            'src/app/js/dashboard/dashboard.controller.js',
            'src/app/js/dashboard/dashboard.factory.js',
            'src/app/js/dashboard/dashboard.module.js',
            'src/app/js/dashboard/dashboard.route.js',
            'src/app/js/dashboard/dashboard.view.html',
            'src/app/js/dashboard/widgets/widget-area.controller.js',
            'src/app/js/dashboard/widgets/widget-area.view.html',
            'src/app/js/dashboard/widgets/widget-pie.controller.js',
            'src/app/js/dashboard/widgets/widget-pie.view.html',
            'src/app/js/dashboard/widgets/widget-table.controller.js',
            'src/app/js/dashboard/widgets/widget-table.view.html',
            'src/app/js/dashboard/widgets/widget.module.js',
            'src/app/js/dashboard/assets/css/dashboard.style.css',
            'src/app/js/dashboard/i18n/translations.js'
        ];

    describe('default answers', function() {

        before(function () {
            return helpers.run(path.join(__dirname, '../generators/app'))
                .withPrompts({})
                .toPromise();
        });

        it('Creates files config', function () {
            assert.file(configFiles);
        });

        it('Creates files app', function () {
            assert.file(appFiles);
        });

        it('Creates files assets', function () {
            assert.file(assetsFiles);
        });

        it('Creates files i18n', function () {
            assert.file([
                'src/app/i18n/translations.js'
            ]);
        });

        it('Creates files desktop', function () {
            assert.file(desktopFiles);
        });

        it('Creates files menu', function () {
            assert.file(menuFiles);
        });

        it('Creates files Sample CRUD', function () {
            assert.file(sampleCRUDFiles);
        });

        it('Creates files Sample Dashboard', function () {
            assert.file(sampleDashboardFiles);
        });

    });

    /*describe('no UI Router', function() {

        before(function () {
            return helpers.run(path.join(__dirname, '../generators/app'))
                .withPrompts({})
                .toPromise();
        });

        assert.fileContent('src/app/index.html', 'angular');
    });*/

    describe('no Samples', function() {

        before(function () {
            return helpers.run(path.join(__dirname, '../generators/app'))
                .withPrompts({samples: []})
                .toPromise();
        });

        it('No creates files CRUD', function () {
            assert.noFile(sampleCRUDFiles);
        });

        it('No creates files Dashboard', function () {
            assert.noFile(sampleDashboardFiles);
        });

    });
});
<|endoftext|>


<commit_before>/*

//--------------------------------------------------------------------------------------------------//
//---------------------------------------- Table Of Contents ---------------------------------------//
//--------------------------------------------------------------------------------------------------//

---------------------------------------------------------------
#                             Config                          #
---------------------------------------------------------------

//

---------------------------------------------------------------
#                            Filters                          #
---------------------------------------------------------------

isLoggedIn
isLoggedOut
isAdmin

canView
canPost
canEditPost
canEditComment

hasCompletedProfile

---------------------------------------------------------------
#                          Controllers                        #
---------------------------------------------------------------

PostsListController
PostPageController

---------------------------------------------------------------
#                             Routes                          #
---------------------------------------------------------------

1) Paginated Lists
----------------------
Top
New
Best
Pending
Categories

2) Digest
--------------------
Digest

3) Posts
--------------------
Post Page
Post Page (scroll to comment)
Post Edit
Post Submit

4) Comments
--------------------
Comment Page
Comment Edit
Comment Submit

5) Users
--------------------
User Profie
User Edit
Forgot Password
Account
All Users
Unsubscribe (from notifications)
Sign Up
Sign In

6) Misc Routes
--------------------
Settings
Categories
Toolbox

*/

//--------------------------------------------------------------------------------------------------//
//--------------------------------------------- Config ---------------------------------------------//
//--------------------------------------------------------------------------------------------------//

Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'not_found',
});

//--------------------------------------------------------------------------------------------------//
//--------------------------------------------- Filters --------------------------------------------//
//--------------------------------------------------------------------------------------------------//

var filters = {

  nProgressHook: function () {
    if (this.ready()) {
      NProgress.done();
    } else {
      NProgress.start();
      this.stop();
    }
  },

  resetScroll: function () {
    var scrollTo = window.currentScroll || 0;
    $('body').scrollTop(scrollTo);
    $('body').css("min-height", 0);
  },

  isLoggedIn: function() {
    if (!(Meteor.loggingIn() || Meteor.user())) {
      throwError(i18n.t('Please Sign In First.'))
      this.render('signin');
      this.stop();
    }
  },

  isLoggedOut: function() {
    if(Meteor.user()){
      this.render('already_logged_in');
      this.stop();
    }
  },

  isAdmin: function() {
    this.subscribe('currentUser').wait();
    if(!this.ready()) return;
    if(!Meteor.loggingIn() && Session.get('settingsLoaded') && !isAdmin()){
      throwError(i18n.t("Sorry, you  have to be an admin to view this page."))
      this.render('no_rights');
      this.stop();
    }
  },

  canView: function() {
    if(Session.get('settingsLoaded') && !canView()){
      console.log('cannot view')
      this.render('no_rights');
      this.stop();
    }
  },

  canPost: function () {
    if(!Meteor.loggingIn() && Session.get('settingsLoaded') && !canPost()){
      throwError(i18n.t("Sorry, you don't have permissions to add new items."))
      this.render('no_rights');
      this.stop();
    }
  },

  canEditPost: function() {
    var post = Posts.findOne(this.params._id);
    if(!Meteor.loggingIn() && Session.get('settingsLoaded') && !currentUserCanEdit(post)){
      throwError(i18n.t("Sorry, you cannot edit this post."))
      this.render('no_rights');
      this.stop();
    }
  },

  canEditComment: function() {
    var comment = Comments.findOne(this.params._id);
    if(!Meteor.loggingIn() && Session.get('settingsLoaded') && !currentUserCanEdit(comment)){
      throwError(i18n.t("Sorry, you cannot edit this comment."))
      this.render('no_rights');
      this.stop();
    }
  },

  hasCompletedProfile: function() {
    var user = Meteor.user();
    if (user && ! Meteor.loggingIn() && ! userProfileComplete(user)){
      this.render('user_email');
      this.stop();
    }
  }

}

// Load Hooks

Router.load( function () {
  clearSeenErrors(); // set all errors who have already been seen to not show anymore
  Session.set('categorySlug', null);

  // if we're not on the search page itself, clear search query and field
  if(getCurrentRoute().indexOf('search') == -1){
    Session.set('searchQuery', '');
    $('.search-field').val('').blur();
  }

});

// Before Hooks

// Use nProgress on every route that has to load a subscription
Router.before(filters.nProgressHook, {only: [
  'posts_top',
  'posts_new',
  'posts_best',
  'posts_pending',
  'posts_digest',
  'posts_category',
  'search',
  'post_page',
  'post_edit',
  'comment_page',
  'comment_edit',
  'comment_reply',
  'user_edit',
  'user_profile',
  'all-users',
  'logs'
]});

Router.before(filters.canView);
Router.before(filters.hasCompletedProfile);
Router.before(filters.isLoggedIn, {only: ['comment_reply','post_submit']});
Router.before(filters.isLoggedOut, {only: ['signin', 'signup']});
Router.before(filters.canPost, {only: ['posts_pending', 'comment_reply', 'post_submit']});
Router.before(filters.canEditPost, {only: ['post_edit']});
Router.before(filters.canEditComment, {only: ['comment_edit']});
Router.before(filters.isAdmin, {only: ['posts_pending', 'all-users', 'settings', 'categories', 'toolbox', 'logs']});

// After Hooks

Router.after(filters.resetScroll, {except:['posts_top', 'posts_new', 'posts_best', 'posts_pending', 'posts_category', 'all-users']});
Router.after( function () {
  analyticsRequest() // log this request with mixpanel, etc
});

// Unload Hooks

//

//--------------------------------------------------------------------------------------------------//
//------------------------------------------- Controllers ------------------------------------------//
//--------------------------------------------------------------------------------------------------//

// Controller for all posts lists

PostsListController = RouteController.extend({
  template:'posts_list',
  waitOn: function () {
    // take the first segment of the path to get the view, unless it's '/' in which case the view default to 'top'
    // note: most of the time this.params.slug will be empty
    this._terms = {
      view: this.path == '/' ? 'top' : this.path.split('/')[1],
      limit: this.params.limit || getSetting('postsPerPage', 10),
      category: this.params.slug,
      query: Session.get("searchQuery")
    }
    return [
      Meteor.subscribe('postsList', this._terms),
      Meteor.subscribe('postsListUsers', this._terms)
    ]
  },
  data: function () {
    var parameters = getParameters(this._terms),
        posts = Posts.find(parameters.find, parameters.options);
        postsCount = posts.count();

    Session.set('postsLimit', this._terms.limit);

    return {
      postsList: posts,
      postsCount: postsCount
    }
  },
  after: function() {
    var view = this.path == '/' ? 'top' : this.path.split('/')[1];
    Session.set('view', view);
  }
});

// Controller for post digest

PostsDigestController = RouteController.extend({
  template: 'posts_digest',
  waitOn: function() {
    // if day is set, use that. If not default to today
    var currentDate = this.params.day ? new Date(this.params.year, this.params.month-1, this.params.day) : Session.get('today'),
        terms = {
          view: 'digest',
          after: moment(currentDate).startOf('day').valueOf(),
          before: moment(currentDate).endOf('day').valueOf()
        }
    return [
      Meteor.subscribe('postsList', terms),
      Meteor.subscribe('postsListUsers', terms)
    ]
  },
  data: function() {
    var currentDate = this.params.day ? new Date(this.params.year, this.params.month-1, this.params.day) : Session.get('today'),
        terms = {
          view: 'digest',
          after: moment(currentDate).startOf('day').valueOf(),
          before: moment(currentDate).endOf('day').valueOf()
        },
        parameters = getParameters(terms);
    Session.set('currentDate', currentDate);
    return {
      posts: Posts.find(parameters.find, parameters.options)
    }
  }
});

// Controller for post pages

PostPageController = RouteController.extend({
  template: 'post_page',
  waitOn: function () {
    return [
      Meteor.subscribe('singlePost', this.params._id),
      Meteor.subscribe('postComments', this.params._id),
      Meteor.subscribe('postUsers', this.params._id)
    ];
  },
  data: function () {
    return {postId: this.params._id};
  },
  after: function () {
    window.queueComments = false;
    window.openedComments = [];
    // TODO: scroll to comment position
  }
});

// Controller for comment pages

CommentPageController = RouteController.extend({
  waitOn: function() {
    return [
      Meteor.subscribe('singleComment', this.params._id),
      Meteor.subscribe('commentUser', this.params._id),
      Meteor.subscribe('commentPost', this.params._id)
    ]
  },
  data: function() {
    return {
      comment: Comments.findOne(this.params._id)
    }
  },
  after: function () {
    window.queueComments = false;
  }
});

// Controller for user pages

UserPageController = RouteController.extend({
  waitOn: function() {
    return Meteor.subscribe('singleUser', this.params._idOrSlug);
  },
  data: function() {
    var findById = Meteor.users.findOne(this.params._idOrSlug);
    var findBySlug = Meteor.users.findOne({slug: this.params._idOrSlug});
    if(typeof findById !== "undefined"){
      // redirect to slug-based URL
      Router.go(getProfileUrl(findById), {replaceState: true});
    }else{
      return {
        user: (typeof findById == "undefined") ? findBySlug : findById
      }
    }
  }
});

//--------------------------------------------------------------------------------------------------//
//--------------------------------------------- Routes ---------------------------------------------//
//--------------------------------------------------------------------------------------------------//

Router.map(function() {

  // -------------------------------------------- Post Lists -------------------------------------------- //

  // Top

  this.route('posts_top', {
    path: '/',
    controller: PostsListController
  });

  this.route('posts_top', {
    path: '/top/:limit?',
    controller: PostsListController
  });

  // New

  this.route('posts_new', {
    path: '/new/:limit?',
    controller: PostsListController
  });

  // Best

  this.route('posts_best', {
    path: '/best/:limit?',
    controller: PostsListController
  });

  // Pending

  this.route('posts_pending', {
    path: '/pending/:limit?',
    controller: PostsListController
  });

  // Categories

  this.route('posts_category', {
    path: '/category/:slug/:limit?',
    controller: PostsListController,
    after: function() {
      Session.set('categorySlug', this.params.slug);
    }
  });

  // TODO: enable /category/new, /category/best, etc. views

  // Search

  this.route('search', {
    path: '/search/:limit?',
    controller: PostsListController
  });

  // Digest

  this.route('posts_digest', {
    path: '/digest/:year/:month/:day',
    controller: PostsDigestController
  });

  this.route('posts_digest', {
    path: '/digest',
    controller: PostsDigestController
  });

  // -------------------------------------------- Post -------------------------------------------- //

  // Post Page

  this.route('post_page', {
    path: '/posts/:_id',
    controller: PostPageController
  });

  this.route('post_page', {
    path: '/posts/:_id/comment/:commentId',
    controller: PostPageController,
    after: function () {
      // TODO: scroll to comment position
    }
  });

  // Post Edit

  this.route('post_edit', {
    path: '/posts/:_id/edit',
    waitOn: function () {
      return Meteor.subscribe('singlePost', this.params._id);
    },
    data: function() {
      return {postId: this.params._id};
    }
  });

  // Post Submit

  this.route('post_submit', {path: '/submit'});

  // -------------------------------------------- Comment -------------------------------------------- //

  // Comment Page

  this.route('comment_page', {
    path: '/comments/:_id',
    controller: CommentPageController
  });

  // Comment Reply

  this.route('comment_reply', {
    path: '/comments/:_id/reply',
    controller: CommentPageController,
    after: function() {
      window.queueComments = false;
    }
  });

  // Comment Edit

  this.route('comment_edit', {
    path: '/comments/:_id/edit',
    controller: CommentPageController,
    after: function() {
      window.queueComments = false;
    }
  });

  // -------------------------------------------- Users -------------------------------------------- //

  // User Profile

  this.route('user_profile', {
    path: '/users/:_idOrSlug',
    controller: UserPageController
  });

  // User Edit

  this.route('user_edit', {
    path: '/users/:_idOrSlug/edit',
    controller: UserPageController
  });

  // Account

  this.route('account', {
    path: '/account',
    template: 'user_edit',
    data: function() {
      return {
        user: Meteor.user()
      }
    }
  });

  // Forgot Password

  this.route('forgot_password');

  // All Users

  this.route('all-users', {
    path: '/all-users/:limit?',
    template: 'users',
    waitOn: function() {
      var limit = parseInt(this.params.limit) || 20;
      return Meteor.subscribe('allUsers', this.params.filterBy, this.params.sortBy, limit);
    },
    data: function() {
      var limit = parseInt(this.params.limit) || 20,
          parameters = getUsersParameters(this.params.filterBy, this.params.sortBy, limit),
          filterBy = (typeof this.params.filterBy === 'string') ? this.params.filterBy : 'all',
          sortBy = (typeof this.params.sortBy === 'string') ? this.params.sortBy : 'createdAt';
      Session.set('usersLimit', limit);
      return {
        users: Meteor.users.find(parameters.find, parameters.options),
        filterBy: filterBy,
        sortBy: sortBy
      }
    }
  });

  // Unsubscribe (from notifications)

  this.route('unsubscribe', {
    path: '/unsubscribe/:hash',
    data: function() {
      return {
        hash: this.params.hash
      }
    }
  });

  // User Sign-Up

  this.route('signup');

  // User Sign-In

  this.route('signin');

  // -------------------------------------------- Other -------------------------------------------- //

  // Categories

  this.route('categories');

  // Settings

  this.route('settings');

  // Toolbox

  this.route('toolbox');

  // Search Logs

  this.route('logs', {
    path: '/logs/:limit?',
    waitOn: function () {
      var limit = this.params.limit || 100;
      Session.set('logsLimit', limit);
      return Meteor.subscribe('searches', limit);
    },
    data: function () {
      return Searches.find({}, {sort: {timestamp: -1}});
    }
  });
});
<commit_msg>router.js: all router-level access checks now wait for required subscriptions to be ready instead of hacking around<commit_after>/*

//--------------------------------------------------------------------------------------------------//
//---------------------------------------- Table Of Contents ---------------------------------------//
//--------------------------------------------------------------------------------------------------//

---------------------------------------------------------------
#                             Config                          #
---------------------------------------------------------------

//

---------------------------------------------------------------
#                            Filters                          #
---------------------------------------------------------------

isLoggedIn
isLoggedOut
isAdmin

canView
canPost
canEditPost
canEditComment

hasCompletedProfile

---------------------------------------------------------------
#                          Controllers                        #
---------------------------------------------------------------

PostsListController
PostPageController

---------------------------------------------------------------
#                             Routes                          #
---------------------------------------------------------------

1) Paginated Lists
----------------------
Top
New
Best
Pending
Categories

2) Digest
--------------------
Digest

3) Posts
--------------------
Post Page
Post Page (scroll to comment)
Post Edit
Post Submit

4) Comments
--------------------
Comment Page
Comment Edit
Comment Submit

5) Users
--------------------
User Profie
User Edit
Forgot Password
Account
All Users
Unsubscribe (from notifications)
Sign Up
Sign In

6) Misc Routes
--------------------
Settings
Categories
Toolbox

*/

//--------------------------------------------------------------------------------------------------//
//--------------------------------------------- Config ---------------------------------------------//
//--------------------------------------------------------------------------------------------------//

Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'not_found',
});

//--------------------------------------------------------------------------------------------------//
//--------------------------------------------- Filters --------------------------------------------//
//--------------------------------------------------------------------------------------------------//

var filters = {

  nProgressHook: function () {
    if (this.ready()) {
      NProgress.done();
    } else {
      NProgress.start();
      this.stop();
    }
  },

  resetScroll: function () {
    var scrollTo = window.currentScroll || 0;
    $('body').scrollTop(scrollTo);
    $('body').css("min-height", 0);
  },

  isLoggedIn: function() {
    if (!(Meteor.loggingIn() || Meteor.user())) {
      throwError(i18n.t('Please Sign In First.'))
      this.render('signin');
      this.stop();
    }
  },

  isLoggedOut: function() {
    if(Meteor.user()){
      this.render('already_logged_in');
      this.stop();
    }
  },

  isAdmin: function() {
    this.subscribe('currentUser').wait();
    if(!this.ready()) return;
    if(!isAdmin()){
      throwError(i18n.t("Sorry, you  have to be an admin to view this page."))
      this.render('no_rights');
      this.stop();
    }
  },

  canView: function() {
    this.subscribe('currentUser').wait();
    this.subscribe('settings').wait();
    if(!this.ready()) return;
    if(!canView()){
      console.log('cannot view')
      this.render('no_rights');
      this.stop();
    }
  },

  canPost: function () {
    this.subscribe('currentUser').wait();
    this.subscribe('settings').wait();
    if(!this.ready()) return;
    if(!canPost()){
      throwError(i18n.t("Sorry, you don't have permissions to add new items."))
      this.render('no_rights');
      this.stop();
    }
  },

  canEditPost: function() {
    this.subscribe('currentUser').wait();
    if(!this.ready()) return;
    // Already subscribed to this post by route({waitOn: ...})
    var post = Posts.findOne(this.params._id);
    if(!currentUserCanEdit(post)){
      throwError(i18n.t("Sorry, you cannot edit this post."))
      this.render('no_rights');
      this.stop();
    }
  },

  canEditComment: function() {
    this.subscribe('currentUser').wait();
    if(!this.ready()) return;
    // Already subscribed to this commit by CommentPageController
    var comment = Comments.findOne(this.params._id);
    if(!currentUserCanEdit(comment)){
      throwError(i18n.t("Sorry, you cannot edit this comment."))
      this.render('no_rights');
      this.stop();
    }
  },

  hasCompletedProfile: function() {
    this.subscribe('currentUser').wait();
    if(!this.ready()) return;
    var user = Meteor.user();
    if (user && ! userProfileComplete(user)){
      this.render('user_email');
      this.stop();
    }
  }

}

// Load Hooks

Router.load( function () {
  clearSeenErrors(); // set all errors who have already been seen to not show anymore
  Session.set('categorySlug', null);

  // if we're not on the search page itself, clear search query and field
  if(getCurrentRoute().indexOf('search') == -1){
    Session.set('searchQuery', '');
    $('.search-field').val('').blur();
  }

});

// Before Hooks

// Use nProgress on every route that has to load a subscription
Router.before(filters.nProgressHook, {only: [
  'posts_top',
  'posts_new',
  'posts_best',
  'posts_pending',
  'posts_digest',
  'posts_category',
  'search',
  'post_page',
  'post_edit',
  'comment_page',
  'comment_edit',
  'comment_reply',
  'user_edit',
  'user_profile',
  'all-users',
  'logs'
]});

Router.before(filters.canView);
Router.before(filters.hasCompletedProfile);
Router.before(filters.isLoggedIn, {only: ['comment_reply','post_submit']});
Router.before(filters.isLoggedOut, {only: ['signin', 'signup']});
Router.before(filters.canPost, {only: ['posts_pending', 'comment_reply', 'post_submit']});
Router.before(filters.canEditPost, {only: ['post_edit']});
Router.before(filters.canEditComment, {only: ['comment_edit']});
Router.before(filters.isAdmin, {only: ['posts_pending', 'all-users', 'settings', 'categories', 'toolbox', 'logs']});

// After Hooks

Router.after(filters.resetScroll, {except:['posts_top', 'posts_new', 'posts_best', 'posts_pending', 'posts_category', 'all-users']});
Router.after( function () {
  analyticsRequest() // log this request with mixpanel, etc
});

// Unload Hooks

//

//--------------------------------------------------------------------------------------------------//
//------------------------------------------- Controllers ------------------------------------------//
//--------------------------------------------------------------------------------------------------//

// Controller for all posts lists

PostsListController = RouteController.extend({
  template:'posts_list',
  waitOn: function () {
    // take the first segment of the path to get the view, unless it's '/' in which case the view default to 'top'
    // note: most of the time this.params.slug will be empty
    this._terms = {
      view: this.path == '/' ? 'top' : this.path.split('/')[1],
      limit: this.params.limit || getSetting('postsPerPage', 10),
      category: this.params.slug,
      query: Session.get("searchQuery")
    }
    return [
      Meteor.subscribe('postsList', this._terms),
      Meteor.subscribe('postsListUsers', this._terms)
    ]
  },
  data: function () {
    var parameters = getParameters(this._terms),
        posts = Posts.find(parameters.find, parameters.options);
        postsCount = posts.count();

    Session.set('postsLimit', this._terms.limit);

    return {
      postsList: posts,
      postsCount: postsCount
    }
  },
  after: function() {
    var view = this.path == '/' ? 'top' : this.path.split('/')[1];
    Session.set('view', view);
  }
});

// Controller for post digest

PostsDigestController = RouteController.extend({
  template: 'posts_digest',
  waitOn: function() {
    // if day is set, use that. If not default to today
    var currentDate = this.params.day ? new Date(this.params.year, this.params.month-1, this.params.day) : Session.get('today'),
        terms = {
          view: 'digest',
          after: moment(currentDate).startOf('day').valueOf(),
          before: moment(currentDate).endOf('day').valueOf()
        }
    return [
      Meteor.subscribe('postsList', terms),
      Meteor.subscribe('postsListUsers', terms)
    ]
  },
  data: function() {
    var currentDate = this.params.day ? new Date(this.params.year, this.params.month-1, this.params.day) : Session.get('today'),
        terms = {
          view: 'digest',
          after: moment(currentDate).startOf('day').valueOf(),
          before: moment(currentDate).endOf('day').valueOf()
        },
        parameters = getParameters(terms);
    Session.set('currentDate', currentDate);
    return {
      posts: Posts.find(parameters.find, parameters.options)
    }
  }
});

// Controller for post pages

PostPageController = RouteController.extend({
  template: 'post_page',
  waitOn: function () {
    return [
      Meteor.subscribe('singlePost', this.params._id),
      Meteor.subscribe('postComments', this.params._id),
      Meteor.subscribe('postUsers', this.params._id)
    ];
  },
  data: function () {
    return {postId: this.params._id};
  },
  after: function () {
    window.queueComments = false;
    window.openedComments = [];
    // TODO: scroll to comment position
  }
});

// Controller for comment pages

CommentPageController = RouteController.extend({
  waitOn: function() {
    return [
      Meteor.subscribe('singleComment', this.params._id),
      Meteor.subscribe('commentUser', this.params._id),
      Meteor.subscribe('commentPost', this.params._id)
    ]
  },
  data: function() {
    return {
      comment: Comments.findOne(this.params._id)
    }
  },
  after: function () {
    window.queueComments = false;
  }
});

// Controller for user pages

UserPageController = RouteController.extend({
  waitOn: function() {
    return Meteor.subscribe('singleUser', this.params._idOrSlug);
  },
  data: function() {
    var findById = Meteor.users.findOne(this.params._idOrSlug);
    var findBySlug = Meteor.users.findOne({slug: this.params._idOrSlug});
    if(typeof findById !== "undefined"){
      // redirect to slug-based URL
      Router.go(getProfileUrl(findById), {replaceState: true});
    }else{
      return {
        user: (typeof findById == "undefined") ? findBySlug : findById
      }
    }
  }
});

//--------------------------------------------------------------------------------------------------//
//--------------------------------------------- Routes ---------------------------------------------//
//--------------------------------------------------------------------------------------------------//

Router.map(function() {

  // -------------------------------------------- Post Lists -------------------------------------------- //

  // Top

  this.route('posts_top', {
    path: '/',
    controller: PostsListController
  });

  this.route('posts_top', {
    path: '/top/:limit?',
    controller: PostsListController
  });

  // New

  this.route('posts_new', {
    path: '/new/:limit?',
    controller: PostsListController
  });

  // Best

  this.route('posts_best', {
    path: '/best/:limit?',
    controller: PostsListController
  });

  // Pending

  this.route('posts_pending', {
    path: '/pending/:limit?',
    controller: PostsListController
  });

  // Categories

  this.route('posts_category', {
    path: '/category/:slug/:limit?',
    controller: PostsListController,
    after: function() {
      Session.set('categorySlug', this.params.slug);
    }
  });

  // TODO: enable /category/new, /category/best, etc. views

  // Search

  this.route('search', {
    path: '/search/:limit?',
    controller: PostsListController
  });

  // Digest

  this.route('posts_digest', {
    path: '/digest/:year/:month/:day',
    controller: PostsDigestController
  });

  this.route('posts_digest', {
    path: '/digest',
    controller: PostsDigestController
  });

  // -------------------------------------------- Post -------------------------------------------- //

  // Post Page

  this.route('post_page', {
    path: '/posts/:_id',
    controller: PostPageController
  });

  this.route('post_page', {
    path: '/posts/:_id/comment/:commentId',
    controller: PostPageController,
    after: function () {
      // TODO: scroll to comment position
    }
  });

  // Post Edit

  this.route('post_edit', {
    path: '/posts/:_id/edit',
    waitOn: function () {
      return Meteor.subscribe('singlePost', this.params._id);
    },
    data: function() {
      return {postId: this.params._id};
    }
  });

  // Post Submit

  this.route('post_submit', {path: '/submit'});

  // -------------------------------------------- Comment -------------------------------------------- //

  // Comment Page

  this.route('comment_page', {
    path: '/comments/:_id',
    controller: CommentPageController
  });

  // Comment Reply

  this.route('comment_reply', {
    path: '/comments/:_id/reply',
    controller: CommentPageController,
    after: function() {
      window.queueComments = false;
    }
  });

  // Comment Edit

  this.route('comment_edit', {
    path: '/comments/:_id/edit',
    controller: CommentPageController,
    after: function() {
      window.queueComments = false;
    }
  });

  // -------------------------------------------- Users -------------------------------------------- //

  // User Profile

  this.route('user_profile', {
    path: '/users/:_idOrSlug',
    controller: UserPageController
  });

  // User Edit

  this.route('user_edit', {
    path: '/users/:_idOrSlug/edit',
    controller: UserPageController
  });

  // Account

  this.route('account', {
    path: '/account',
    template: 'user_edit',
    data: function() {
      return {
        user: Meteor.user()
      }
    }
  });

  // Forgot Password

  this.route('forgot_password');

  // All Users

  this.route('all-users', {
    path: '/all-users/:limit?',
    template: 'users',
    waitOn: function() {
      var limit = parseInt(this.params.limit) || 20;
      return Meteor.subscribe('allUsers', this.params.filterBy, this.params.sortBy, limit);
    },
    data: function() {
      var limit = parseInt(this.params.limit) || 20,
          parameters = getUsersParameters(this.params.filterBy, this.params.sortBy, limit),
          filterBy = (typeof this.params.filterBy === 'string') ? this.params.filterBy : 'all',
          sortBy = (typeof this.params.sortBy === 'string') ? this.params.sortBy : 'createdAt';
      Session.set('usersLimit', limit);
      return {
        users: Meteor.users.find(parameters.find, parameters.options),
        filterBy: filterBy,
        sortBy: sortBy
      }
    }
  });

  // Unsubscribe (from notifications)

  this.route('unsubscribe', {
    path: '/unsubscribe/:hash',
    data: function() {
      return {
        hash: this.params.hash
      }
    }
  });

  // User Sign-Up

  this.route('signup');

  // User Sign-In

  this.route('signin');

  // -------------------------------------------- Other -------------------------------------------- //

  // Categories

  this.route('categories');

  // Settings

  this.route('settings');

  // Toolbox

  this.route('toolbox');

  // Search Logs

  this.route('logs', {
    path: '/logs/:limit?',
    waitOn: function () {
      var limit = this.params.limit || 100;
      Session.set('logsLimit', limit);
      return Meteor.subscribe('searches', limit);
    },
    data: function () {
      return Searches.find({}, {sort: {timestamp: -1}});
    }
  });
});
<|endoftext|>


<commit_before>/* jshint -W058 */
document.addEventListener('DOMContentLoaded', function(event) {

var tick = 0;

function drawBoard() {
	var board = document.getElementById('boardcontainer');

	//make 49 squares. board is 7x7, duh.
	for(var i = 1; i <= 49; i++) {
		var sq = document.createElement('div');
		sq.setAttribute('id','sq'+i);
		sq.setAttribute('class','square');
		board.appendChild(sq);
	}
}

gameData = {
	level : 1,
	score : {},
	stats : {
		clicks: 0,
		moves: 0
	}
};

gameUtils = {
	draw : {
		pickRandomColor : function(obj, num) {
			//obj = colors object, num = number of colors to pick from
			var colors = Object.keys(obj);
			return obj[colors[num * Math.random() << 0]];
		},
		fillSquares : function(num) {
			//num defines how many colored squares to get
			for(var i=1; i <= num; i++) {
				var randomId = Math.floor(Math.random() * 49 +1);
				var squareToFill = document.getElementById('sq'+randomId);
				squareToFill.style.backgroundColor = gameUtils.draw.pickRandomColor(gameUtils.colors, 3);
			}
		},
		fillEmptySquares: function(num) {
			for(var i = 1; i<= num; i++) {
				var randomId = Math.floor(Math.random() * 49 + 1);
				var squareToFill = document.getElementById('sq'+randomId);
				if(squareToFill.style.backgroundColor) {
					console.log('picked a full square!');
					i--;
				}
				else {
					squareToFill.style.backgroundColor = gameUtils.draw.pickRandomColor(gameUtils.colors, 3);
				}
			}
		}
	},
	colors : {
		'blue' : '#2882ff',
		'red' : '#ff141d',
		'green' : '#00f40d',
		'orange' : '#ff9300',
		'purple' : '#ff00bd',
		'cyan' : '#14fcff'
	}
};

function Game() {
	//main game is here
	console.log('game class constructed');

	this.init();

	//listeners for squares
	var squareListeners = document.getElementsByClassName('square');
	for(var i = 0; i < squareListeners.length; i++){
		squareListeners[i].addEventListener('click', this.onclick, false);
	}

	window.requestAnimationFrame =
	    window.requestAnimationFrame ||
	    window.mozRequestAnimationFrame ||
	    window.webkitRequestAnimationFrame ||
	    window.oRequestAnimationFrame;

	window.requestAnimationFrame(this.draw.bind(this));
}

Game.prototype.draw = function() {
	tick++;
	// console.log(tick);
	if(tick > 100) {
		tick = 0;
	}

	this.drawNumbers();
	this.update();

	requestAnimationFrame(this.draw.bind(this));
};

Game.prototype.update = function() {

};

Game.prototype.onclick = function() {
	gameData.stats.clicks++;
	var squareIsActive = squareIsActive || false;

	function highlightSquare(hasColor, isActive) {
		if(hasColor && !isActive) {
			this.style.transform = 'scale(1.1)';
			squareIsActive = true;
			console.log('made active');
		}
		console.log('else');
	}
	//move square
	// if(!this.style.backgroundColor && !squareIsActive) {
	// 	squareIsActive = false;
	// }

	var wat = highlightSquare.bind(this, this.style.backgroundColor, squareIsActive);
	wat();

};

Game.prototype.drawNumbers = function() {
	var stats = stats || document.getElementById('clicks');
	stats.innerHTML = gameData.stats.clicks;

};
Game.prototype.init = function() {
	console.log('init fired');

	drawBoard();
	gameUtils.draw.fillEmptySquares(3);
};

//init the game here and stuff
var game = new Game();

});
<commit_msg>backup before os rollback<commit_after>/* jshint -W058 */
document.addEventListener('DOMContentLoaded', function(event) {

var tick = 0;

function drawBoard() {
	var board = document.getElementById('boardcontainer');

	//make 49 squares. board is 7x7, duh.
	for(var i = 1; i <= 49; i++) {
		var sq = document.createElement('div');
		sq.setAttribute('id','sq'+i);
		sq.setAttribute('class','square');
		sq.dataset.active = false;
		board.appendChild(sq);
	}
}

gameData = {
	level : 1,
	score : {},
	stats : {
		clicks: 0,
		moves: 0
	},
	squares : {

	}
};

gameUtils = {
	draw : {
		pickRandomColor : function(obj, num) {
			//obj = colors object, num = number of colors to pick from
			var colors = Object.keys(obj);
			return obj[colors[num * Math.random() << 0]];
		},
		fillSquares : function(num) {
			//num defines how many colored squares to get
			for(var i=1; i <= num; i++) {
				var randomId = Math.floor(Math.random() * 49 +1);
				var squareToFill = document.getElementById('sq'+randomId);
				squareToFill.style.backgroundColor = gameUtils.draw.pickRandomColor(gameUtils.colors, 3);
			}
		},
		fillEmptySquares: function(num) {
			for(var i = 1; i<= num; i++) {
				var randomId = Math.floor(Math.random() * 49 + 1);
				var squareToFill = document.getElementById('sq'+randomId);
				if(squareToFill.style.backgroundColor) {
					console.log('picked a full square!');
					i--;
				}
				else {
					squareToFill.style.backgroundColor = gameUtils.draw.pickRandomColor(gameUtils.colors, 3);
				}
			}
		}
	},
	update: {
		checkActiveSquares: function(activeObj) {
			//returns true if more than one square is higlighted
			//takes gameData.squares.active as preferred object.
			var size = 0, s;
			for(s in activeObj) {
				if(activeObj.hasOwnProperty(s)){
					size++;
				}
			}
			if(size > 1) {
				return true;
			}
			else {
				return false;
			}
		},
		highlightFunction: function(hasColor, isActive) {
			// console.log(this);
			function highlightSquare() {
				console.log(this);
				this.style.transform = 'scale(1.1)';
				this.dataset.active = true;
				// squareIsActive = true;
				console.log('made active');
			}
			function unhighlightSquare() {
				this.style.transform = 'scale(1.0)';
				this.dataset.active = false;
				console.log('already active');
			}
			function makeAllSquaresInactive() {

			}
			if(hasColor && isActive === 'true') {
				unhighlightSquare.bind(this);
			}
			else if(gameUtils.update.checkActiveSquares(gameData.squares.active) === true) {
				var activeSquares = document.querySelector('[data-active="true"]');
				activeSquares.dataset.active = 'false';
				unhighlightSquare(this);
				console.log(activeSquares);
				console.log('another square is active');

			}
			else if(hasColor && isActive === 'false') {
				highlightSquare.bind(this);

			}
			else {
				console.log('not active');
			}
		}

	},
	init: {
		squareObjGenerator : function() {
			var defaults = {
				'color' : '#fff',
				'selected' : false
			};
			for(var j = 1; j <= 49; j++) {
				// gameData.squares['sq'+j] = new gameData.squares(defaults);
				var sqName = 'sq'+j;
				gameData.squares[sqName] = defaults;
			}
		},
	},

	squareListeners : function() {
		//listeners for squares
		//get this working with bind duh

	},
	colors : {
		'blue' : '#2882ff',
		'red' : '#ff141d',
		'green' : '#00f40d',
		'orange' : '#ff9300',
		'purple' : '#ff00bd',
		'cyan' : '#14fcff'
	}
};

function Game() {
	//main game is here
	console.log('game class constructed');

	this.init();

	window.requestAnimationFrame =
	    window.requestAnimationFrame ||
	    window.mozRequestAnimationFrame ||
	    window.webkitRequestAnimationFrame ||
	    window.oRequestAnimationFrame;

	window.requestAnimationFrame(this.draw.bind(this));
}

Game.prototype.draw = function() {
	tick++;
	// console.log(tick);
	if(tick > 100) {
		tick = 0;
	}

	this.update();

	requestAnimationFrame(this.draw.bind(this));
};

Game.prototype.update = function() {
	this.updateNumbers();

	this.statusUpdateLoop();

};

Game.prototype.onClick = function() {
	gameData.stats.clicks++;
	// var squareIsActive = squareIsActive || false;
	var isActive = this.dataset.active;
	console.log(gameData);

	//move square
	// if(!this.style.backgroundColor && !squareIsActive) {
	// 	squareIsActive = false;
	// }

	var wat = gameUtils.update.highlightFunction.bind(this, this.style.backgroundColor, isActive);
	wat();

};

Game.prototype.updateNumbers = function() {
	var stats = stats || document.getElementById('clicks');
	stats.innerHTML = gameData.stats.clicks;

};
Game.prototype.statusUpdateLoop = function() {
	var squareCollection = document.getElementsByClassName('square');
	gameData.squares.active = {};
	for(var i = 0; i < squareCollection.length; i++ ) {
		if(squareCollection[i].dataset.active === 'true') {
			var tmp = {};
			tmp[squareCollection[i].id] = true;
			gameData.squares.active += tmp;
		}

	}
};
Game.prototype.init = function() {
	console.log('init fired');

	drawBoard();

	// gameUtils.squareListeners();
	var squareListeners = document.getElementsByClassName('square');
	for(var i = 0; i < squareListeners.length; i++){
		squareListeners[i].addEventListener('click', this.onClick, false);
	}

	gameUtils.init.squareObjGenerator();
	console.log(gameData);

	gameUtils.draw.fillEmptySquares(3);
};

//init the game here and stuff
var game = new Game();

});
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// 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
//
//     https://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.
//import {ProgressBar} from  './script'
/*

/* exported initAutocomplete, getCurrentAddress */
/* global google */

const defaultCenter = {
  lat: 40.712776,
  lng:-74.005974
};
Object.freeze(defaultCenter);
let userlatlng = {lat:null , lng: null};

/*
* Creates map and search boxes with autocomplete
*/
function initAutocomplete() {
  const map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: defaultCenter.lat, lng: defaultCenter.lng },
    zoom: 13,
    mapTypeId: "roadmap"
  });

  //navigator is an HTML geolocation API variable to get information about the users current location
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      userlatlng = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      map.setCenter(userlatlng);
    }, function() {
         map.setCenter(defaultCenter);
        });
  }
  else {
    window.alert("Geolocation failed");
  }
  // Create the search boxes and link them to the UI elements.
  const START_SEARCH_BOX = 'start-search-box';
  const DESTINATIONS_SEARCH_BOX= 'destinations-search-box';
  createSearchBox(map,START_SEARCH_BOX);
  createSearchBox(map,DESTINATIONS_SEARCH_BOX);

}

/*
 * Creates a search box
 * @param {google.maps.Map} map
 * @param {string} container
 */
function createSearchBox(map,container){
  const start = document.getElementById(container);
  const searchBox = new google.maps.places.SearchBox(start);

   map.addListener("bounds_changed", () => {
    searchBox.setBounds(map.getBounds());
  });
  let markers = [];

  searchBox.addListener("places_changed", () => {
    const places = searchBox.getPlaces();

    if (places.length == 0) {
      return;
    }
    // Clear out the old markers.
    markers.forEach(marker => {
      marker.setMap(null);
    });
    markers = [];
    // For each place, get the icon, name and location.
    const bounds = new google.maps.LatLngBounds();
    places.forEach(place => {
      if (!place.geometry) {
        console.log("Returned place contains no geometry");
        return;
      }
      const icon = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };
      // Create a marker for each place.
      markers.push(
        new google.maps.Marker({
          map,
          icon,
          title: place.name,
          position: place.geometry.location
        })
      );

      if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
      } else {
        bounds.extend(place.geometry.location);
      }
    });
    map.fitBounds(bounds);
  });

}

/*
* fetches start location and destinations from DestinationsServlet and adds to DOM
*/
function getLocations(){
  fetchDestinations().then((userLocations) => {
    document.getElementById('start-location').innerText = "Start Location :" + userLocations.start;
    const container = document.getElementById('destinations-container');
    container.innerText = "Destinations:";
    let destinationArray= userLocations.destinations;
    destinationArray.forEach((destination) => {
      let destinationToAdd = document.createElement('p');
      destinationToAdd.innerText = destination;
      container.appendChild(destinationToAdd);
    })
  });
}

/*
* fills Start location Searchbox with previously input
*/
function getStartDestination(){
  fetchDestinations().then((userLocations)=>{
    if (userLocations.start == null){
      document.getElementById('start-search-box').value = "";
    }
    else{
      document.getElementById('start-search-box').value = userLocations.start;
    }
  });
}

/*
* fetches data from servlet
*/
function fetchDestinations(){
  let promise = fetch('/api/destinations').then(response => response.json());
  return promise;
}

/*
* Gets users current location
*/
function getCurrentAddress(){
  const geocoder = new google.maps.Geocoder();
  geocoder.geocode({ 'location': userlatlng}, (results, status) => {
    if (status === "OK") {
      if (results[0]) {
          console.log(results[0].formatted_address);
        document.getElementById("start-search-box").value=results[0].formatted_address;
      } else {
          window.alert("No results found");
        }
    } else {
        window.alert("Geocoder failed due to: " + status);
      }
  });
}

/*
* add event listener for submit button
*/
window.onload = function(){
  document.getElementById('user-input-form').addEventListener('submit', (event) => {
    event.preventDefault();
    const params = new URLSearchParams();
    params.append('start-location', document.getElementById('start-search-box').value);
    params.append('destinations', document.getElementById('destinations-search-box').value);
    fetch('/api/destinations', {method: 'POST', body:params}).then(function(response){
      return response.text();
    }).then(function(text){
      console.log(text)
    }).then(() => {
      getLocations()
    }).then(() => {
      getStartDestination();
    });
  });
}

<commit_msg>simplified fetchDestinations fucntion<commit_after>// Copyright 2019 Google LLC
//
// 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
//
//     https://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.
//import {ProgressBar} from  './script'
/*

/* exported initAutocomplete, getCurrentAddress */
/* global google */

const defaultCenter = {
  lat: 40.712776,
  lng:-74.005974
};
Object.freeze(defaultCenter);
let userlatlng = {lat:null , lng: null};

/*
* Creates map and search boxes with autocomplete
*/
function initAutocomplete() {
  const map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: defaultCenter.lat, lng: defaultCenter.lng },
    zoom: 13,
    mapTypeId: "roadmap"
  });

  //navigator is an HTML geolocation API variable to get information about the users current location
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      userlatlng = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      map.setCenter(userlatlng);
    }, function() {
         map.setCenter(defaultCenter);
        });
  }
  else {
    window.alert("Geolocation failed");
  }
  // Create the search boxes and link them to the UI elements.
  const START_SEARCH_BOX = 'start-search-box';
  const DESTINATIONS_SEARCH_BOX= 'destinations-search-box';
  createSearchBox(map,START_SEARCH_BOX);
  createSearchBox(map,DESTINATIONS_SEARCH_BOX);

}

/*
 * Creates a search box
 * @param {google.maps.Map} map
 * @param {string} container
 */
function createSearchBox(map,container){
  const start = document.getElementById(container);
  const searchBox = new google.maps.places.SearchBox(start);

   map.addListener("bounds_changed", () => {
    searchBox.setBounds(map.getBounds());
  });
  let markers = [];

  searchBox.addListener("places_changed", () => {
    const places = searchBox.getPlaces();

    if (places.length == 0) {
      return;
    }
    // Clear out the old markers.
    markers.forEach(marker => {
      marker.setMap(null);
    });
    markers = [];
    // For each place, get the icon, name and location.
    const bounds = new google.maps.LatLngBounds();
    places.forEach(place => {
      if (!place.geometry) {
        console.log("Returned place contains no geometry");
        return;
      }
      const icon = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };
      // Create a marker for each place.
      markers.push(
        new google.maps.Marker({
          map,
          icon,
          title: place.name,
          position: place.geometry.location
        })
      );

      if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
      } else {
        bounds.extend(place.geometry.location);
      }
    });
    map.fitBounds(bounds);
  });

}

/*
* fetches start location and destinations from DestinationsServlet and adds to DOM
*/
function getLocations(){
  fetchDestinations().then((userLocations) => {
    document.getElementById('start-location').innerText = "Start Location :" + userLocations.start;
    const container = document.getElementById('destinations-container');
    container.innerText = "Destinations:";
    let destinationArray= userLocations.destinations;
    destinationArray.forEach((destination) => {
      let destinationToAdd = document.createElement('p');
      destinationToAdd.innerText = destination;
      container.appendChild(destinationToAdd);
    })
  });
}

/*
* fills Start location Searchbox with previously input
*/
function getStartDestination(){
  fetchDestinations().then((userLocations)=>{
    if (userLocations.start == null){
      document.getElementById('start-search-box').value = "";
    }
    else{
      document.getElementById('start-search-box').value = userLocations.start;
    }
  });
}

/*
* fetches data from servlet
*/
function fetchDestinations(){
  return fetch('/api/destinations').then(response => response.json());
}

/*
* Gets users current location
*/
function getCurrentAddress(){
  const geocoder = new google.maps.Geocoder();
  geocoder.geocode({ 'location': userlatlng}, (results, status) => {
    if (status === "OK") {
      if (results[0]) {
          console.log(results[0].formatted_address);
        document.getElementById("start-search-box").value=results[0].formatted_address;
      } else {
          window.alert("No results found");
        }
    } else {
        window.alert("Geocoder failed due to: " + status);
      }
  });
}

/*
* add event listener for submit button
*/
window.onload = function(){
  document.getElementById('user-input-form').addEventListener('submit', (event) => {
    event.preventDefault();
    const params = new URLSearchParams();
    params.append('start-location', document.getElementById('start-search-box').value);
    params.append('destinations', document.getElementById('destinations-search-box').value);
    fetch('/api/destinations', {method: 'POST', body:params}).then(function(response){
      return response.text();
    }).then(function(text){
      console.log(text)
    }).then(() => {
      getLocations()
    }).then(() => {
      getStartDestination();
    });
  });
}

<|endoftext|>


<commit_before>var args = arguments[0] || {};

function doClick(e) {
	alert("click!");
	alert("ほげー");
	$.hoge.close();
}
<commit_msg>#1<commit_after>var args = arguments[0] || {};

function doClick(e) {
	alert("click!hoge!");
	alert("ほげー");
	$.hoge.close();
}
<|endoftext|>


<commit_before>import _ from 'lodash'
import util from './util'
import Flexio from './flexio'

export default () => {
  var retval = _.assign({}, {
    // -- state --

    pipe: {
      name: 'Javascript SDK Pipe',
      description: 'This pipe was created using the Flex.io Javascript SDK',
      task: []
    },
    processes: [],
    params: {},
    loading: false,
    saving: false,
    running: false,

    // -- methods --

    getJSON() {
      return _.assign({}, this.pipe)
    },

    getProcesses() {
      return [].concat(this.processes)
    },

    getLastProcess() {
      return _.last(this.processes)
    },

    addTask(task) {
      this.pipe.task.push(task)
      return this
    },

    clearTasks() {
      this.pipe.task = []
      return this
    },

    load() {
      var args = Array.from(arguments)
      var identifier = _.get(args, '[0]')
      var callback = _.get(args, '[1]')

      if (this.loading === true || this.saving === true || this.running === true)
      {
        setTimeout(() => { this.load.apply(this, arguments) }, 50)
        return this
      }

      if (_.isNil(identifier))
        return util.debug.call(this, "The `identifier` parameter is required. Either the pipe's eid or pipe's alias may be used.")

      this.loading = true
      util.debug.call(this, 'Loading Pipe `' + identifier + '`...')

      Flexio.http().get('/pipes/' + identifier)
        .then(response => {
          var obj = _.get(response, 'data', {})
          this.pipe = _.assign({}, obj)
          this.loading = false
          util.debug.call(this, 'Pipe Loaded.')

          if (typeof callback == 'function')
            callback.call(this, null, obj)
        })
        .catch(error => {
          this.loading = false
          util.debug.call(this, 'Pipe Load Failed.')

          if (typeof callback == 'function')
            callback.call(this, error, null)
        })

      return this
    },

    save() {
      var args = Array.from(arguments)
      var params = _.get(args, '[0]')
      var callback = _.get(args, '[0]')

      if (this.loading === true || this.saving === true || this.running === true)
      {
        setTimeout(() => { this.save.apply(this, arguments) }, 50)
        return this
      }

      if (_.isPlainObject(params))
      {
        _.assign(this.pipe, _.pick(params, ['name', 'description', 'ename']))
        callback = _.get(args, '[1]')
      }

      this.saving = true
      util.debug.call(this, 'Saving Pipe `' + _.get(this.pipe, 'name', 'Untitled Pipe') + '`...')

      Flexio.http().post('/pipes', this.pipe)
        .then(response => {
          var pipe = _.get(response, 'data', {})
          this.pipe = _.assign({}, pipe)
          this.saving = false
          util.debug.call(this, 'Pipe Saved.')

          if (typeof callback == 'function')
            callback.call(this, null, this.pipe)
        })
        .catch(error => {
          this.saving = false
          util.debug.call(this, 'Pipe Save Failed.')

          if (typeof callback == 'function')
            callback.call(this, error, null)
        })

      return this
    },

    run() {
      var args = Array.from(arguments)
      var callback = _.get(args, '[0]')

      if (this.loading === true || this.saving === true || this.running === true)
      {
        setTimeout(() => { this.run.apply(this, arguments) }, 50)
        return this
      }

      this.running = true
      util.debug.call(this, 'Running Pipe `' + _.get(this.pipe, 'name', 'Untitled Pipe') + '`...')

      var run_params = _.assign({}, this.pipe)

      // if we have saved this pipe, use the pipe's eid as the parent eid
      var parent_eid = _.get(this.pipe, 'eid', '')
      if (parent_eid.length > 0)
        run_params = { parent_eid }

      // set the process to run mode
      _.assign(run_params, {
        process_mode: 'R'
      })

      Flexio.http().post('/processes', run_params)
        .then(response => {
          var obj = _.get(response, 'data', {})
          var process_eid = _.get(obj, 'eid', '')
          this.processes.push(obj)
          util.debug.call(this, 'Created Process.')

          Flexio.http().post('/processes/'+process_eid+'/run', this.getParams())
            .then(response => {
              var obj2 = _.get(response, 'data', {})
              util.debug.call(this, 'Process Complete.')
              this.running = false

              if (typeof callback == 'function')
                callback.call(this, null, obj2)
            })
        })
        .catch(error => {
          util.debug.call(this, 'Process Create Failed.')
          this.running = false

          if (typeof callback == 'function')
            callback.call(this, error, null)
        })

      return this
    },

    params(params) {
      this.params = _.assign({}, this.params, params)
      return this
    },

    clearParams(keys /* array */) {
      if (_.isArray(keys))
        this.params = _.omit(this.params, keys)
         else if (_.isNil(keys))
        this.params = {}

      return this
    },

    getParams() {
      return _.assign({}, this.params)
    }
  }) /* end assign */

  /*
    iterate through each of the task functions on the `Flexio` object and
    create a function which will add that task's JSON to the pipe when called --
    this will auto-generate these functions and eliminate the need for us
    to keep this list of functions updated every time we add a new task;
    see `./task/*.js` for the list of tasks that are available for use

    so we do this...
  */

  _.each(Flexio.task, function(taskFn, task_name) {
    retval[task_name] = function() { return retval.addTask(taskFn.apply(retval /* scope */, arguments)) }
  })

  /*
    instead of this...

    input()      { return this.addTask(Flexio.task.input.apply(this, arguments))      },
    output()     { return this.addTask(Flexio.task.output.apply(this, arguments))     },
    convert()    { return this.addTask(Flexio.task.convert.apply(this, arguments))    },
    etc...
  */

  return retval
}
<commit_msg>Avoid collision with `params` method name.<commit_after>import _ from 'lodash'
import util from './util'
import Flexio from './flexio'

export default () => {
  var retval = _.assign({}, {
    // -- state --

    pipe: {
      name: 'Javascript SDK Pipe',
      description: 'This pipe was created using the Flex.io Javascript SDK',
      task: []
    },
    processes: [],
    _params: {}, // avoid collision with `params` method name
    loading: false,
    saving: false,
    running: false,

    // -- methods --

    getJSON() {
      return _.assign({}, this.pipe)
    },

    getProcesses() {
      return [].concat(this.processes)
    },

    getLastProcess() {
      return _.last(this.processes)
    },

    addTask(task) {
      this.pipe.task.push(task)
      return this
    },

    clearTasks() {
      this.pipe.task = []
      return this
    },

    load() {
      var args = Array.from(arguments)
      var identifier = _.get(args, '[0]')
      var callback = _.get(args, '[1]')

      if (this.loading === true || this.saving === true || this.running === true)
      {
        setTimeout(() => { this.load.apply(this, arguments) }, 50)
        return this
      }

      if (_.isNil(identifier))
        return util.debug.call(this, "The `identifier` parameter is required. Either the pipe's eid or pipe's alias may be used.")

      this.loading = true
      util.debug.call(this, 'Loading Pipe `' + identifier + '`...')

      Flexio.http().get('/pipes/' + identifier)
        .then(response => {
          var obj = _.get(response, 'data', {})
          this.pipe = _.assign({}, obj)
          this.loading = false
          util.debug.call(this, 'Pipe Loaded.')

          if (typeof callback == 'function')
            callback.call(this, null, obj)
        })
        .catch(error => {
          this.loading = false
          util.debug.call(this, 'Pipe Load Failed.')

          if (typeof callback == 'function')
            callback.call(this, error, null)
        })

      return this
    },

    save() {
      var args = Array.from(arguments)
      var params = _.get(args, '[0]')
      var callback = _.get(args, '[0]')

      if (this.loading === true || this.saving === true || this.running === true)
      {
        setTimeout(() => { this.save.apply(this, arguments) }, 50)
        return this
      }

      if (_.isPlainObject(params))
      {
        _.assign(this.pipe, _.pick(params, ['name', 'description', 'ename']))
        callback = _.get(args, '[1]')
      }

      this.saving = true
      util.debug.call(this, 'Saving Pipe `' + _.get(this.pipe, 'name', 'Untitled Pipe') + '`...')

      Flexio.http().post('/pipes', this.pipe)
        .then(response => {
          var pipe = _.get(response, 'data', {})
          this.pipe = _.assign({}, pipe)
          this.saving = false
          util.debug.call(this, 'Pipe Saved.')

          if (typeof callback == 'function')
            callback.call(this, null, this.pipe)
        })
        .catch(error => {
          this.saving = false
          util.debug.call(this, 'Pipe Save Failed.')

          if (typeof callback == 'function')
            callback.call(this, error, null)
        })

      return this
    },

    run() {
      var args = Array.from(arguments)
      var callback = _.get(args, '[0]')

      if (this.loading === true || this.saving === true || this.running === true)
      {
        setTimeout(() => { this.run.apply(this, arguments) }, 50)
        return this
      }

      this.running = true
      util.debug.call(this, 'Running Pipe `' + _.get(this.pipe, 'name', 'Untitled Pipe') + '`...')

      var run_params = _.assign({}, this.pipe)

      // if we have saved this pipe, use the pipe's eid as the parent eid
      var parent_eid = _.get(this.pipe, 'eid', '')
      if (parent_eid.length > 0)
        run_params = { parent_eid }

      // set the process to run mode
      _.assign(run_params, {
        process_mode: 'R'
      })

      Flexio.http().post('/processes', run_params)
        .then(response => {
          var obj = _.get(response, 'data', {})
          var process_eid = _.get(obj, 'eid', '')
          this.processes.push(obj)
          util.debug.call(this, 'Created Process.')

          Flexio.http().post('/processes/'+process_eid+'/run', this.getParams())
            .then(response => {
              var obj2 = _.get(response, 'data', {})
              util.debug.call(this, 'Process Complete.')
              this.running = false

              if (typeof callback == 'function')
                callback.call(this, null, obj2)
            })
        })
        .catch(error => {
          util.debug.call(this, 'Process Create Failed.')
          this.running = false

          if (typeof callback == 'function')
            callback.call(this, error, null)
        })

      return this
    },

    params(params) {
      this._params = _.assign({}, this.getParams(), params)
      return this
    },

    clearParams(keys /* array */) {
      if (_.isArray(keys))
        this._params = _.omit(this._params, keys)
         else if (_.isNil(keys))
        this._params = {}

      return this
    },

    getParams() {
      return _.assign({}, this._params)
    }
  }) /* end assign */

  /*
    iterate through each of the task functions on the `Flexio` object and
    create a function which will add that task's JSON to the pipe when called --
    this will auto-generate these functions and eliminate the need for us
    to keep this list of functions updated every time we add a new task;
    see `./task/*.js` for the list of tasks that are available for use

    so we do this...
  */

  _.each(Flexio.task, function(taskFn, task_name) {
    retval[task_name] = function() { return retval.addTask(taskFn.apply(retval /* scope */, arguments)) }
  })

  /*
    instead of this...

    input()      { return this.addTask(Flexio.task.input.apply(this, arguments))      },
    output()     { return this.addTask(Flexio.task.output.apply(this, arguments))     },
    convert()    { return this.addTask(Flexio.task.convert.apply(this, arguments))    },
    etc...
  */

  return retval
}
<|endoftext|>


<commit_before>// Copyright 2012 Rackspace Hosting, Inc.
//
// 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.

var trace = require('..').trace;
var node_tracers = require('..').node_tracers;

var express = require('express');
var http = require('http');
var util = require('util');

var mockKeystoneClient = {
  getTenantIdAndToken: function(cb) {
    cb('1', 2, '3');
  }
};

// Asserts (via a nodeunit test object) that the result is a base64 string
var assert_is_base64 = function(test, string) {
  test.ok(string.search(/^([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==)$/) >= 0);
};

// Asserts (via a nodeunit test object) that the result is a json array - if
// it is a string representing a json array, parses the string
var assert_is_json_array = function(test, json) {
  if (typeof json === typeof "") {
    json = JSON.parse(json);
  }
  test.ok(util.isArray(json));
  test.ok(json.length >= 1);
};

// A fake scribe client for testing purposes - rather than send data to scribe,
// it saves the category and message sent to it and allows assertions to be
// made on the data (via a nodeunit test object)
var FakeScribe = function(test) {
  var self = this;
  self.test = test;
  self.results = [];
  self.send = function(category, message) {
    self.results.push([category, message]);
  };
  self.assert_sent = function() {
    self.test.equal(self.results.length, 1);
    self.test.equal(self.results[0].length, 2);
  };
  self.assert_category = function(category) {
    self.test.equal(self.results[0][0], category);
  };
  self.assert_json = function() {
    assert_is_json_array(self.test, self.results[0][1]);
  };
  self.assert_base64 = function() {
    assert_is_base64(self.test, self.results[0][1]);
  };
};

module.exports = {
  setUp: function(cb) {
    var self = this;
    self.trace = new trace.Trace('clientRecv');
    self.annotation = trace.Annotation.clientRecv(2);
    cb();
  },
  test_restkin_tracer: function(test){
    var self = this;
    var app = express();
    var server = http.createServer(app);
    var tracer;

    app.use(express.bodyParser());

    app.post('/', function(request, response){
      test.equal(request.headers['x-auth-token'], '1');
      test.equal(request.headers['x-tenant-id'], '3');
      test.equal(request.headers['content-type'], 'application/json');
      test.notEqual(request.headers['content-length'], '0');
      assert_is_json_array(test, request.body);

      response.end('done');
      server.close();
    });

    server.on('close', function(){
      test.done();
    });

    server.listen(22222, 'localhost');
    tracer = new node_tracers.RESTkinTracer('http://localhost:22222',
                                            mockKeystoneClient);
    tracer.record(self.trace, self.annotation);
  },
  test_zipkin_tracer_default_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.ZipkinTracer(s);
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('zipkin');
    s.assert_base64();
    test.done();
  },
  test_zipkin_tracer_provided_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.ZipkinTracer(s, 'mycategory');
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('mycategory');
    s.assert_base64();
    test.done();
  },
  test_restkin_scribe_tracer_default_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.RESTkinScribeTracer(s);
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('restkin');
    s.assert_json();
    test.done();
  },
  test_restkin_scribe_tracer_provided_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.RESTkinScribeTracer(s, 'mycategory');
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('mycategory');
    s.assert_json();
    test.done();
  }
};
<commit_msg>Update affected test.<commit_after>// Copyright 2012 Rackspace Hosting, Inc.
//
// 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.

var trace = require('..').trace;
var node_tracers = require('..').node_tracers;

var express = require('express');
var http = require('http');
var util = require('util');

var mockKeystoneClient = {
  getTenantIdAndToken: function(cb) {
    cb('1', 2, '3');
  }
};

// Asserts (via a nodeunit test object) that the result is a base64 string
var assert_is_base64 = function(test, string) {
  test.ok(string.search(/^([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==)$/) >= 0);
};

// Asserts (via a nodeunit test object) that the result is a json array - if
// it is a string representing a json array, parses the string
var assert_is_json_array = function(test, json) {
  if (typeof json === typeof "") {
    json = JSON.parse(json);
  }
  test.ok(util.isArray(json));
  test.ok(json.length >= 1);
};

// A fake scribe client for testing purposes - rather than send data to scribe,
// it saves the category and message sent to it and allows assertions to be
// made on the data (via a nodeunit test object)
var FakeScribe = function(test) {
  var self = this;
  self.test = test;
  self.results = [];
  self.send = function(category, message) {
    self.results.push([category, message]);
  };
  self.assert_sent = function() {
    self.test.equal(self.results.length, 1);
    self.test.equal(self.results[0].length, 2);
  };
  self.assert_category = function(category) {
    self.test.equal(self.results[0][0], category);
  };
  self.assert_json = function() {
    assert_is_json_array(self.test, self.results[0][1]);
  };
  self.assert_base64 = function() {
    assert_is_base64(self.test, self.results[0][1]);
  };
};

module.exports = {
  setUp: function(cb) {
    var self = this;
    self.trace = new trace.Trace('clientRecv');
    self.annotation = trace.Annotation.clientRecv(2);
    cb();
  },
  test_restkin_tracer: function(test){
    var self = this;
    var app = express();
    var server = http.createServer(app);
    var tracer;

    app.use(express.bodyParser());

    app.post('/3/trace', function(request, response){
      test.equal(request.headers['x-auth-token'], '1');
      test.equal(request.headers['x-tenant-id'], '3');
      test.equal(request.headers['content-type'], 'application/json');
      test.notEqual(request.headers['content-length'], '0');
      assert_is_json_array(test, request.body);

      response.end('done');
      server.close();
    });

    server.on('close', function(){
      test.done();
    });

    server.listen(22222, 'localhost');
    tracer = new node_tracers.RESTkinTracer('http://localhost:22222',
                                            mockKeystoneClient);
    tracer.record(self.trace, self.annotation);
  },
  test_zipkin_tracer_default_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.ZipkinTracer(s);
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('zipkin');
    s.assert_base64();
    test.done();
  },
  test_zipkin_tracer_provided_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.ZipkinTracer(s, 'mycategory');
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('mycategory');
    s.assert_base64();
    test.done();
  },
  test_restkin_scribe_tracer_default_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.RESTkinScribeTracer(s);
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('restkin');
    s.assert_json();
    test.done();
  },
  test_restkin_scribe_tracer_provided_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.RESTkinScribeTracer(s, 'mycategory');
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('mycategory');
    s.assert_json();
    test.done();
  }
};
<|endoftext|>


<commit_before>const path    = require('path');
const helpers = require('yeoman-test');
const assert  = require('yeoman-assert');

/**
 * Test app generator.
 */
describe('app', () => {
  before((done) => {
    // Mock the options, set up an output folder and run the generator
    helpers.run(path.join(__dirname, '../generators/app'))
      .toPromise()
      .then(() => {
        done();
      });
  });

  it('should generate a README', () => {
    assert.file('README.md');
  });
});
<commit_msg>feat(styles): Unit tests<commit_after>'use strict';

const path = require('path');
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');

/**
 * Test app generator.
 */
describe('app', () => {

  describe('default settings', () => {
    before((done) => {
      this.generator = helpers
        .run(path.join(__dirname, '../generators/app'))
        .toPromise()
        .then(() => done());
    });

    it('should generate a README', () => {
      assert.file('README.md');
    });

    it('should generate a main SASS file', () => {
      assert.file('src/styles/main.scss');
      assert.fileContent('src/styles/main.scss', '');
    });
  });

  describe('when using less', () => {

    before((done) => {
      this.generator = helpers
        .run(path.join(__dirname, '../generators/app'))
        .withPrompts({
          cssPreprocessor: 'less'
        })
        .toPromise()
        .then(() => done());
    });

    it('should generate a main LESS file', () => {
      assert.file('src/styles/main.less');
      assert.fileContent('src/styles/main.less', '');
    });

  });

  describe('when using css', () => {

    before((done) => {
      this.generator = helpers
        .run(path.join(__dirname, '../generators/app'))
        .withPrompts({
          cssPreprocessor: 'css'
        })
        .toPromise()
        .then(() => done());
    });

    it('should generate a main CSS file', () => {
      assert.file('src/styles/main.css');
      assert.fileContent('src/styles/main.css', '');
    });

  });
});
<|endoftext|>


<commit_before>angular.module('starter.controllers', ['ui.router])

.controller('AppCtrl', function($scope, $location, RegistrationService) {
  $scope.logout = function() {
    RegistrationService.logout();
    $location.path("/home");
  }
  $scope.timeleft = '0 secs';
})

.controller('RegisterCtrl', function($scope, $location, RegistrationService) {
  $scope.user = {
    name: '',
    email: '',
    password: '',
    password2: ''
  };

  $scope.$parent.logout_text = 'Logout';

  $scope.register = function() {
    RegistrationService.register($scope.user).then(function() {
      $location.path("/");
    })
  }
})

.controller('LoginCtrl', function($scope, $location, RegistrationService) {
  $scope.user = {
    email: '',
    password: ''
  };

  $scope.$parent.logout_text = 'Register';

  $scope.login = function() {
    RegistrationService.login($scope.user.email, $scope.user.password).then(function() {
      $location.path("/");
    });
  }

})

.controller('LeadersCtrl', function($scope, SocketIO, Answer) {
  $scope.leaders = Answer.leaders();

  SocketIO.on('answer', function(msg) {
    $scope.leaders = Answer.leaders();
  });

  $scope.$on('$destroy', function(event) {
    SocketIO.removeAllListeners('answer');
  });

})

.controller('HomeCtrl', function($scope, $location) {

})

.controller('OneCtrl', function($scope, $location) {
  $scope.$parent.logout_text = 'Home';

  $scope.one = function() {
    (function() {
    $location.path("/");
    });
  }
})

.controller('TwoCtrl', function($scope, $location) {

})

.controller('ThreeCtrl', function($scope, $location) {

})

.controller('AllCtrl', function($scope, $location) {

})

.controller('1B1Ctrl', function($scope, $location) {

})

.controller('1B2Ctrl', function($scope, $location) {

})

.controller('1B3Ctrl', function($scope, $location) {

})

.controller('2B1Ctrl', function($scope, $location) {

})

.controller('2B2Ctrl', function($scope, $location) {

})

.controller('2B3Ctrl', function($scope, $location) {

})
.controller('2B4Ctrl', function($scope, $location) {

})

.controller('2B5Ctrl', function($scope, $location) {

})

.controller('2B6Ctrl', function($scope, $location) {

})

.controller('3B1Ctrl', function($scope, $location) {

})

.controller('3B2Ctrl', function($scope, $location) {

})

.controller('3B3Ctrl', function($scope, $location) {

})
.controller('3B4Ctrl', function($scope, $location) {

})

.controller('3B5Ctrl', function($scope, $location) {

})

.controller('3B6Ctrl', function($scope, $location) {

})
<commit_msg>Update controllers.js<commit_after>angular.module('starter.controllers', ['ui.router'])

.controller('AppCtrl', function($scope, $location, RegistrationService) {
  $scope.logout = function() {
    RegistrationService.logout();
    $location.path("/home");
  }
  $scope.timeleft = '0 secs';
})

.controller('RegisterCtrl', function($scope, $location, RegistrationService) {
  $scope.user = {
    name: '',
    email: '',
    password: '',
    password2: ''
  };

  $scope.$parent.logout_text = 'Logout';

  $scope.register = function() {
    RegistrationService.register($scope.user).then(function() {
      $location.path("/");
    })
  }
})

.controller('LoginCtrl', function($scope, $location, RegistrationService) {
  $scope.user = {
    email: '',
    password: ''
  };

  $scope.$parent.logout_text = 'Register';

  $scope.login = function() {
    RegistrationService.login($scope.user.email, $scope.user.password).then(function() {
      $location.path("/");
    });
  }

})

.controller('LeadersCtrl', function($scope, SocketIO, Answer) {
  $scope.leaders = Answer.leaders();

  SocketIO.on('answer', function(msg) {
    $scope.leaders = Answer.leaders();
  });

  $scope.$on('$destroy', function(event) {
    SocketIO.removeAllListeners('answer');
  });

})

.controller('HomeCtrl', function($scope, $location) {

})

.controller('OneCtrl', function($scope, $location) {
  $scope.$parent.logout_text = 'Home';

  $scope.one = function() {
    (function() {
    $location.path("/");
    });
  }
})

.controller('TwoCtrl', function($scope, $location) {

})

.controller('ThreeCtrl', function($scope, $location) {

})

.controller('AllCtrl', function($scope, $location) {

})

.controller('1B1Ctrl', function($scope, $location) {

})

.controller('1B2Ctrl', function($scope, $location) {

})

.controller('1B3Ctrl', function($scope, $location) {

})

.controller('2B1Ctrl', function($scope, $location) {

})

.controller('2B2Ctrl', function($scope, $location) {

})

.controller('2B3Ctrl', function($scope, $location) {

})
.controller('2B4Ctrl', function($scope, $location) {

})

.controller('2B5Ctrl', function($scope, $location) {

})

.controller('2B6Ctrl', function($scope, $location) {

})

.controller('3B1Ctrl', function($scope, $location) {

})

.controller('3B2Ctrl', function($scope, $location) {

})

.controller('3B3Ctrl', function($scope, $location) {

})
.controller('3B4Ctrl', function($scope, $location) {

})

.controller('3B5Ctrl', function($scope, $location) {

})

.controller('3B6Ctrl', function($scope, $location) {

})
<|endoftext|>