<commit_before>const express = require('express');
const auth = require('../middleware/auth');
const router = express.Router();
const Actions = require('../models/actions');
const Cooperatives = require('../models/cooperatives');
const Log = require('../models').logs;

router.post('/:id/comments', isMongoId('id'), auth.authenticate(), (req, res) => {
  Actions.addComment(req.params.id, req.body, req.user, (err, comment) => {
    if (err) {
      res.status(500).render('/error', { err: err.message });
    } else {
      if (req.accepts('html')) {
        res.redirect(`/actions/${ req.params.id }`);
      } else {
        res.render(comment);
      }
    }
  });

  Log.create({
    userId: req.user._id,
    category: 'Action Comments',
    type: 'create',
    data: req.body
  });
});

router.get('/:id/comments', isMongoId('id'), (req, res) => {
  if (req.accepts('html')) {
    res.redirect(`/actions/${ req.params.id }`);
  } else {
    Actions.get(req.params.id, (err, action) => {
      if (err) {
        res.status(404).render('/error', { err: err.message });
      } else {
        res.render(action.comments);
      }
    });

    Log.create({
      userId: req.user && req.user._id,
      category: 'Action Comments',
      type: 'all',
      data: {
        actionId: req.params.id
      }
    });
  }
});

router.get('/:id/comments/:commentId', isMongoId('id', 'commentId'), (req, res) => {
  if (req.accepts('html')) {
    res.redirect(`/actions/${ req.params.id }`);
  } else {
    Actions.getComment(req.params.commentId, (err, comment) => {
      if (err) {
        res.status(404).render('/error', { err: err.message });
      } else {
        res.render(comment);
      }
    });

    Log.create({
      userId: req.user && req.user._id,
      category: 'Action Comments',
      type: 'get',
      data: {
        actionId: req.params.id,
        commentId: req.params.commentId
      }
    });
  }
});

router.delete('/:id/comments/:commentId', isMongoId('id', 'commentId'), auth.authenticate(), (req, res) => {
  Actions.deleteComment(req.params.commentId, err => {
    if (err) {
      res.status(500).render('/error', { err: err.message });
    } else if (req.accepts('html')) {
      res.redirect(`/actions/${ req.params.id }`);
    } else {
      res.redirect(`/actions/${ req.params.id }/comments`);
    }
  });

  Log.create({
    userId: req.user._id,
    category: 'Action Comments',
    type: 'delete',
    data: req.params
  });
});

router.post('/', auth.authenticate(), (req, res) => {
  req.checkBody('cooperative').isMongoId();

  const err = req.validationErrors();

  if (err) {
    res.status(400).render('/error', err);
  } else {
    Actions.create(req.body, req.user, req.body.cooperative, (err, action) => {
      if (err) {
        res.status(500).render(
          `/actions${ req.url }`,
          Object.assign({ err: err.message}, req.body)
        );
      } else {
        res.render(
          `/actions/${ action._id }`,
          action,
          (data, done) => Cooperatives.get(action.cooperative, (err, cooperative) => {
            if (err) { return done(err); }
            done(null, {
              cooperatives: [ cooperative ],
              actions: [ action ]
            });
          })
        );
      }
    });
  }

  Log.create({
    userId: req.user._id,
    category: 'Action',
    type: 'create',
    data: req.body
  });
});

router.put('/:id', auth.authenticate(), isMongoId('id'), (req, res) => {
  const { body, params: { id }} = req;

  Actions.update(id, body, (err, action) => {
    if (err) {
      res.status(500).render(
        `/cooperatives${ req.url }`,
        Object.assign({ err: err.message }, body)
      );
    } else {
      res.render(
        `/cooperatives${ req.url }`,
        action,
        (data, done) => done(null, {
          cooperatives: [ data.cooperative ],
          actions: [ data ]
        })
      );
    }
  });

  Log.create({
    userId: req.user._id,
    category: 'Cooperative',
    type: 'updateAction',
    data: {
      actionId: id,
      action: body
    }
  });
});

router.get('/:id', isMongoId('id'), (req, res) => {
  Actions.get(req.params.id, (err, action) => {
    if (err) {
      res.status(404).render('/error', { err: err.message });
    } else {
      res.render(
        `/actions${ req.url }`,
        action,
        (data, done) => done(null, {
          cooperatives: [ data.cooperative ],
          actions: [ data ]
        })
      );
    }
  });

  Log.create({
    userId: req.user && req.user._id,
    category: 'Action',
    type: 'get',
    data: {
      actionId: req.params.id
    }
  });
});

router.delete('/:id', isMongoId('id'), auth.authenticate(), (req, res) => {
  Actions.get(req.params.id, (err, action) => {
    if (err) {
      res.status(404).render('/error', { err: err.message });
    }
    else {
      Actions.delete(req.params.id, err => {
        if (err) {
          res.status(500).render('/error', { err: err.message });
        } else {
          res.redirect(`/cooperatives/${ action.cooperative }`);
        }
      });
    }
  });

  Log.create({
    userId: req.user._id,
    category: 'Action',
    type: 'delete',
    data: {
      actionId: req.params.id
    }
  });
});

router.get('/', function(req, res) {
  Actions.getAll(req.query.limit, (err, actions) => {
    if (err) {
      res.status(500).render('/error', { err: err.message });
    } else {
      res.render(
        '/actions',
        actions,
        (data, done) => done(null, { actions: [ data ]})
      );
    }
  });

  Log.create({
    userId: req.user && req.user._id,
    category: 'Action',
    type: 'all',
    data: req.body
  });
});

router.get('/search', (req, res) => {
  Actions.search(req.query.q, (err, actions) => {
    if (err) {
      res.status(500).render('/error', { err: err.message });
    } else {
      res.render('/search', actions, (data, done) => done(null, { actions }));
    }
  });

  Log.create({
    userId: req.user && req.user._id,
    category: 'Action',
    type: 'search',
    data: req.query
  });
});

module.exports = router;

function isMongoId(...params) {
  return (req, res, next) => {
    for (let param of params) {
      req.checkParams(param, `Invalid cooperative ${ param }`).isMongoId();
    }

    const err = req.validationErrors();

    if (err) {
      res.status(404).render('/404', err);
    } else {
      next();
    }
  };
}
<commit_msg>Fix action put render<commit_after>const express = require('express');
const auth = require('../middleware/auth');
const router = express.Router();
const Actions = require('../models/actions');
const Cooperatives = require('../models/cooperatives');
const Log = require('../models').logs;

router.post('/:id/comments', isMongoId('id'), auth.authenticate(), (req, res) => {
  Actions.addComment(req.params.id, req.body, req.user, (err, comment) => {
    if (err) {
      res.status(500).render('/error', { err: err.message });
    } else {
      if (req.accepts('html')) {
        res.redirect(`/actions/${ req.params.id }`);
      } else {
        res.render(comment);
      }
    }
  });

  Log.create({
    userId: req.user._id,
    category: 'Action Comments',
    type: 'create',
    data: req.body
  });
});

router.get('/:id/comments', isMongoId('id'), (req, res) => {
  if (req.accepts('html')) {
    res.redirect(`/actions/${ req.params.id }`);
  } else {
    Actions.get(req.params.id, (err, action) => {
      if (err) {
        res.status(404).render('/error', { err: err.message });
      } else {
        res.render(action.comments);
      }
    });

    Log.create({
      userId: req.user && req.user._id,
      category: 'Action Comments',
      type: 'all',
      data: {
        actionId: req.params.id
      }
    });
  }
});

router.get('/:id/comments/:commentId', isMongoId('id', 'commentId'), (req, res) => {
  if (req.accepts('html')) {
    res.redirect(`/actions/${ req.params.id }`);
  } else {
    Actions.getComment(req.params.commentId, (err, comment) => {
      if (err) {
        res.status(404).render('/error', { err: err.message });
      } else {
        res.render(comment);
      }
    });

    Log.create({
      userId: req.user && req.user._id,
      category: 'Action Comments',
      type: 'get',
      data: {
        actionId: req.params.id,
        commentId: req.params.commentId
      }
    });
  }
});

router.delete('/:id/comments/:commentId', isMongoId('id', 'commentId'), auth.authenticate(), (req, res) => {
  Actions.deleteComment(req.params.commentId, err => {
    if (err) {
      res.status(500).render('/error', { err: err.message });
    } else if (req.accepts('html')) {
      res.redirect(`/actions/${ req.params.id }`);
    } else {
      res.redirect(`/actions/${ req.params.id }/comments`);
    }
  });

  Log.create({
    userId: req.user._id,
    category: 'Action Comments',
    type: 'delete',
    data: req.params
  });
});

router.post('/', auth.authenticate(), (req, res) => {
  req.checkBody('cooperative').isMongoId();

  const err = req.validationErrors();

  if (err) {
    res.status(400).render('/error', err);
  } else {
    Actions.create(req.body, req.user, req.body.cooperative, (err, action) => {
      if (err) {
        res.status(500).render(
          `/actions${ req.url }`,
          Object.assign({ err: err.message}, req.body)
        );
      } else {
        res.render(
          `/actions/${ action._id }`,
          action,
          (data, done) => Cooperatives.get(action.cooperative, (err, cooperative) => {
            if (err) { return done(err); }
            done(null, {
              cooperatives: [ cooperative ],
              actions: [ action ]
            });
          })
        );
      }
    });
  }

  Log.create({
    userId: req.user._id,
    category: 'Action',
    type: 'create',
    data: req.body
  });
});

router.put('/:id', auth.authenticate(), isMongoId('id'), (req, res) => {
  const { body, params: { id }} = req;

  Actions.update(id, body, (err, action) => {
    if (err) {
      res.status(500).render(
        `/actions/${ id }`,
        Object.assign({ err: err.message }, body)
      );
    } else {
      res.render(
        `/actions/${ id }`,
        action,
        (data, done) => done(null, {
          cooperatives: [ data.cooperative ],
          actions: [ data ]
        })
      );
    }
  });

  Log.create({
    userId: req.user._id,
    category: 'Cooperative',
    type: 'updateAction',
    data: {
      actionId: id,
      action: body
    }
  });
});

router.get('/:id', isMongoId('id'), (req, res) => {
  Actions.get(req.params.id, (err, action) => {
    if (err) {
      res.status(404).render('/error', { err: err.message });
    } else {
      res.render(
        `/actions${ req.url }`,
        action,
        (data, done) => done(null, {
          cooperatives: [ data.cooperative ],
          actions: [ data ]
        })
      );
    }
  });

  Log.create({
    userId: req.user && req.user._id,
    category: 'Action',
    type: 'get',
    data: {
      actionId: req.params.id
    }
  });
});

router.delete('/:id', isMongoId('id'), auth.authenticate(), (req, res) => {
  Actions.get(req.params.id, (err, action) => {
    if (err) {
      res.status(404).render('/error', { err: err.message });
    }
    else {
      Actions.delete(req.params.id, err => {
        if (err) {
          res.status(500).render('/error', { err: err.message });
        } else {
          res.redirect(`/cooperatives/${ action.cooperative }`);
        }
      });
    }
  });

  Log.create({
    userId: req.user._id,
    category: 'Action',
    type: 'delete',
    data: {
      actionId: req.params.id
    }
  });
});

router.get('/', function(req, res) {
  Actions.getAll(req.query.limit, (err, actions) => {
    if (err) {
      res.status(500).render('/error', { err: err.message });
    } else {
      res.render(
        '/actions',
        actions,
        (data, done) => done(null, { actions: [ data ]})
      );
    }
  });

  Log.create({
    userId: req.user && req.user._id,
    category: 'Action',
    type: 'all',
    data: req.body
  });
});

router.get('/search', (req, res) => {
  Actions.search(req.query.q, (err, actions) => {
    if (err) {
      res.status(500).render('/error', { err: err.message });
    } else {
      res.render('/search', actions, (data, done) => done(null, { actions }));
    }
  });

  Log.create({
    userId: req.user && req.user._id,
    category: 'Action',
    type: 'search',
    data: req.query
  });
});

module.exports = router;

function isMongoId(...params) {
  return (req, res, next) => {
    for (let param of params) {
      req.checkParams(param, `Invalid cooperative ${ param }`).isMongoId();
    }

    const err = req.validationErrors();

    if (err) {
      res.status(404).render('/404', err);
    } else {
      next();
    }
  };
}
<|endoftext|>


<commit_before>/**
* Variables
*/
var iframeOpen;

/**
* Functions and callbacks
*/
var receiveMessage = function(event) {
	var commentPath,
		frameURL;

	commentPath = event.data.commentURL;

	// if statement required as "external" messages are often passed
	if ( commentPath ) {
		frameURL = "https://news.ycombinator.com/" + commentPath;
		toggleComments( frameURL )
	}
}

var toggleComments = function( URL ) {
	var commentFrame,
		frameset,
		frameHasSrc;
	commentDiv = document.querySelector( "#bttc-comment-div" );
	commentFrame = document.querySelector( "#bttc-comment-frame" );
    body = document.querySelector( "body" );
	frameHasSrc = commentFrame.getAttribute("src");

	// set frame src if none is present
	if ( ! frameHasSrc ) {
		commentFrame.setAttribute( "src", URL );
	}

	// open/close iframe
	if ( ! iframeOpen ) {
        commentDiv.style.width = "50%";
        commentDiv.style.display = "block";
	} else {
        commentDiv.style.width = "0";
        commentDiv.style.display = "none";
	}

	// toggle iframeOpen flag
	iframeOpen = Math.abs( iframeOpen - 1 );

}

var drawIframe = function() {
	var frameset,
		pageURL,
		pageFrame,
		commentFrame,
		html,
		body;

	html = document.querySelector( "html" );
	body = document.querySelector( "body" );
    iframeContainer = document.createElement( "div" );
	iframe = document.createElement( "iframe" );
    iframeContainer.setAttribute("id", "bttc-comment-div");
    iframe.setAttribute("id", "bttc-comment-frame");

    iframeContainer.appendChild( iframe );
	html.insertBefore( iframeContainer, body );
}

/**
* Events
*/
iframeOpen = 0;
drawIframe();
window.addEventListener("message", receiveMessage, false);
<commit_msg>Added opacity change to body to fade it out when comments open.<commit_after>/**
* Variables
*/
var iframeOpen;

/**
* Functions and callbacks
*/
var receiveMessage = function(event) {
	var commentPath,
		frameURL;

	commentPath = event.data.commentURL;

	// if statement required as "external" messages are often passed
	if ( commentPath ) {
		frameURL = "https://news.ycombinator.com/" + commentPath;
		toggleComments( frameURL )
	}
}

var toggleComments = function( URL ) {
	var commentFrame,
		frameset,
		frameHasSrc;
	commentDiv = document.querySelector( "#bttc-comment-div" );
	commentFrame = document.querySelector( "#bttc-comment-frame" );
    body = document.querySelector( "body" );
	frameHasSrc = commentFrame.getAttribute("src");

	// set frame src if none is present
	if ( ! frameHasSrc ) {
		commentFrame.setAttribute( "src", URL );
	}

	// open/close iframe
	if ( ! iframeOpen ) {
        commentDiv.style.width = "50%";
        commentDiv.style.display = "block";
        body.style.opacity = 0.4;
	} else {
        commentDiv.style.width = "0";
        commentDiv.style.display = "none";
        body.style.opacity = 1;
	}

	// toggle iframeOpen flag
	iframeOpen = Math.abs( iframeOpen - 1 );

}

var drawIframe = function() {
	var frameset,
		pageURL,
		pageFrame,
		commentFrame,
		html,
		body;

	html = document.querySelector( "html" );
	body = document.querySelector( "body" );
    iframeContainer = document.createElement( "div" );
	iframe = document.createElement( "iframe" );
    iframeContainer.setAttribute("id", "bttc-comment-div");
    iframe.setAttribute("id", "bttc-comment-frame");

    iframeContainer.appendChild( iframe );
	html.insertBefore( iframeContainer, body );
}

/**
* Events
*/
iframeOpen = 0;
drawIframe();
window.addEventListener("message", receiveMessage, false);
<|endoftext|>


<commit_before>/*
 * grunt-build-gh-pages
 * https://github.com/pajtai/grunt-build-gh-pages
 *
 * Copyright (c) 2013 Peter Ajtai
 * Licensed under the MIT license.
 */

'use strict';

/*
 Make sure you have built the project to the "dist" directory
 'shell:getRef',
 'shell:getBranch',
 'shell:switch',
 'bumpBuild',
 */
module.exports = function(grunt) {

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('build_gh_pages', 'Take a build from this branch to another branch.', function() {

        // this.name
        // this.target
        // Merge task-specific and/or target-specific options with these defaults.
        // things coming through options are automatically run through the grunt templater
        var options = this.options({
            dist: "dist",
            build_branch: "gh-pages",
            pull: true
        }),
            shell = "shell",
            prefix = "build_gh_pages_,",

            // Get the SHA reference of the current commit
            getRef = {
                options: {
                    callback: function(err, out, stderr, cb) {
                        var version = grunt.file.readJSON("package.json").version,
                            shaRef =  out.substring(0, 7);

                        grunt.log.writeln("sha ref is: " + shaRef)
                            .writeln("version is: " + version);

                        options.shaRef =  shaRef;
                        options.version = version;

                        cb();
                    }
                },

                command: "git rev-parse HEAD"
            },

            // Get the name of the current branch
            getBranch = {
                options: {
                    callback: function(err, out, stderr, cb) {
                        grunt.log.writeln("branch is: " + out);
                        options.branch = out;
                        cb();
                    }
                },

                command: "git rev-parse --abbrev-ref HEAD"
            },

            // Switch to the build branch and make sure it is up to date if desired
            switchBranch = {
                options: {
                    stderr: true,
                        stdout: true
                },

                command: (function() {
                    var command = "git checkout " + options.build_branch;

                    if (options.pull) {
                        command += " && git pull --rebase";
                    }
                    return command;
                }())
            },

            finish =  {
                options: {
                    stderr: true,
                    stdout: true
                },

                command:

// get a list of all files in stage and delete everything except for targets, node_modules, cache, temp, and logs
// rm does not delete root level hidden files
                    'ls | grep -v ^' + options.dist + '$ | grep -v ^node_modules$ | xargs rm -r ' +

// copy from the stage folder to the current (root) folder
                    '&& cp -r ' + options.dist + '/* . ' +
                    '&& rm -r ' + options.dist + ' ' +

// add any files that may have been created
                    '&& git add -A ' +

// commit all files using the version number as the commit message
// <%= %> is grunt templating
                    '&& git commit -am "Build: <%= grunt.file.read(".build") %> Branch: ' + options.branch + ' ' + options.version + ' SHA: ' + options.shaRef +

// push changes to gitlab
                    '&& git push origin ' + options.build_branch +

// now that everything is done, we have to switch back to the branch we started from
// the - is a shortcutl for @{-1} which means we go back to the previous branch
                    '&& git checkout -'
            };

        grunt.log.writeln(JSON.stringify(options));

        // dynamically create desired shell tasks
        grunt.config.set("shell." + prefix + "getRef", getRef);
        grunt.config.set("shell." + prefix + "getBranch", getBranch);
        grunt.config.set("shell." + prefix + "switchBranch", switchBranch);
        grunt.config.set("shell." + prefix + "finish", finish);

        // run created shell tasks
        grunt.task.run([
            "shell:" + prefix + "getRef",
            "shell:" + prefix + "getBranch",
            "shell:" + prefix + "switchBranch",
            "shell:" + prefix + "finsih"
        ]);
    });

};
<commit_msg>fixing typos<commit_after>/*
 * grunt-build-gh-pages
 * https://github.com/pajtai/grunt-build-gh-pages
 *
 * Copyright (c) 2013 Peter Ajtai
 * Licensed under the MIT license.
 */

'use strict';

/*
 Make sure you have built the project to the "dist" directory
 'shell:getRef',
 'shell:getBranch',
 'shell:switch',
 'bumpBuild',
 */
module.exports = function(grunt) {

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('build_gh_pages', 'Take a build from this branch to another branch.', function() {

        // this.name
        // this.target
        // Merge task-specific and/or target-specific options with these defaults.
        // things coming through options are automatically run through the grunt templater
        var options = this.options({
            dist: "dist",
            build_branch: "gh-pages",
            pull: true
        }),
            shell = "shell",
            prefix = "build_gh_pages_",

            // Get the SHA reference of the current commit
            getRef = {
                options: {
                    callback: function(err, out, stderr, cb) {
                        var version = grunt.file.readJSON("package.json").version,
                            shaRef =  out.substring(0, 7);

                        grunt.log.writeln("sha ref is: " + shaRef)
                            .writeln("version is: " + version);

                        options.shaRef =  shaRef;
                        options.version = version;

                        cb();
                    }
                },

                command: "git rev-parse HEAD"
            },

            // Get the name of the current branch
            getBranch = {
                options: {
                    callback: function(err, out, stderr, cb) {
                        grunt.log.writeln("branch is: " + out);
                        options.branch = out;
                        cb();
                    }
                },

                command: "git rev-parse --abbrev-ref HEAD"
            },

            // Switch to the build branch and make sure it is up to date if desired
            switchBranch = {
                options: {
                    stderr: true,
                        stdout: true
                },

                command: (function() {
                    var command = "git checkout " + options.build_branch;

                    if (options.pull) {
                        command += " && git pull --rebase";
                    }
                    return command;
                }())
            },

            finish =  {
                options: {
                    stderr: true,
                    stdout: true
                },

                command:

// get a list of all files in stage and delete everything except for targets, node_modules, cache, temp, and logs
// rm does not delete root level hidden files
                    'ls | grep -v ^' + options.dist + '$ | grep -v ^node_modules$ | xargs rm -r ' +

// copy from the stage folder to the current (root) folder
                    '&& cp -r ' + options.dist + '/* . ' +
                    '&& rm -r ' + options.dist + ' ' +

// add any files that may have been created
                    '&& git add -A ' +

// commit all files using the version number as the commit message
// <%= %> is grunt templating
                    '&& git commit -am "Build: <%= grunt.file.read(".build") %> Branch: ' + options.branch + ' ' + options.version + ' SHA: ' + options.shaRef +

// push changes to gitlab
                    '&& git push origin ' + options.build_branch +

// now that everything is done, we have to switch back to the branch we started from
// the - is a shortcutl for @{-1} which means we go back to the previous branch
                    '&& git checkout -'
            };

        grunt.log.writeln(JSON.stringify(options));

        // dynamically create desired shell tasks
        grunt.config.set("shell." + prefix + "getRef", getRef);
        grunt.config.set("shell." + prefix + "getBranch", getBranch);
        grunt.config.set("shell." + prefix + "switchBranch", switchBranch);
        grunt.config.set("shell." + prefix + "finish", finish);

        // run created shell tasks
        grunt.task.run([
            "shell:" + prefix + "getRef",
            "shell:" + prefix + "getBranch",
            "shell:" + prefix + "switchBranch",
            "shell:" + prefix + "finish"
        ]);
    });

};
<|endoftext|>


<commit_before>angular.module('just.common')
    .directive('passwordMatch', function () {
        return {
            restrict: 'A',
            scope: true,
            require: 'ngModel',
            link: function (scope, elem, attrs, control) {
                var checker = function () {
                    var e1 = scope.$eval(attrs.ngModel);
                    var e2 = scope.$eval(attrs.passwordMatch);
                    return e1 === e2;
                };
                scope.$watch(checker, function (n) {
                    control.$setValidity("unique", n);
                });
            }
        };
    })
    .controller('RegisterCtrl', ['authService', 'userService', 'justFlowService', 'justRoutes', '$scope',
        function (authService, userService, flow, routes, $scope) {
            var that = this;

            if (authService.isAuthenticated()) {
                flow.redirect(routes.user.user.url);
            }

            this.data = userService.registerModel;
            this.message = userService.registerMessage;

            if (flow.next_data) {
                if(flow.next_data.data){
                    this.data.company_id = flow.next_data.data.id;
                }
            }

            $scope.$watch('form', function (form) {
                if (form) {
                    if (that.message.data) {
                        angular.forEach(that.message.data.errors, function (obj, key) {
                            var pointer_arr = obj.source.pointer.split("/");
                            var field_name = pointer_arr[pointer_arr.length - 1];
                            field_name = field_name.replace(/-/g, "_");
                            $scope.form[field_name].error_detail = obj.detail;
                        });

                    }
                }
            });

            this.process = function () {
                var element0 = angular.element("#file_upload");
                if (element0[0].files[0]) {
                    var formData = new FormData();
                    var element = angular.element("#file_upload");
                    formData.append("image", element[0].files[0]);
                    userService.register(that.data, formData);
                } else {
                    userService.register(that.data);
                }

            };
        }]);
<commit_msg>Fix redirect page from logged in register<commit_after>angular.module('just.common')
    .directive('passwordMatch', function () {
        return {
            restrict: 'A',
            scope: true,
            require: 'ngModel',
            link: function (scope, elem, attrs, control) {
                var checker = function () {
                    var e1 = scope.$eval(attrs.ngModel);
                    var e2 = scope.$eval(attrs.passwordMatch);
                    return e1 === e2;
                };
                scope.$watch(checker, function (n) {
                    control.$setValidity("unique", n);
                });
            }
        };
    })
    .controller('RegisterCtrl', ['authService', 'userService', 'justFlowService', 'justRoutes', '$scope',
        function (authService, userService, flow, routes, $scope) {
            var that = this;

            if (authService.isAuthenticated()) {
                flow.replace(routes.user.user.url);
            }

            this.data = userService.registerModel;
            this.message = userService.registerMessage;

            if (flow.next_data) {
                if(flow.next_data.data){
                    this.data.company_id = flow.next_data.data.id;
                }
            }

            $scope.$watch('form', function (form) {
                if (form) {
                    if (that.message.data) {
                        angular.forEach(that.message.data.errors, function (obj, key) {
                            var pointer_arr = obj.source.pointer.split("/");
                            var field_name = pointer_arr[pointer_arr.length - 1];
                            field_name = field_name.replace(/-/g, "_");
                            $scope.form[field_name].error_detail = obj.detail;
                        });

                    }
                }
            });

            this.process = function () {
                var element0 = angular.element("#file_upload");
                if (element0[0].files[0]) {
                    var formData = new FormData();
                    var element = angular.element("#file_upload");
                    formData.append("image", element[0].files[0]);
                    userService.register(that.data, formData);
                } else {
                    userService.register(that.data);
                }

            };
        }]);
<|endoftext|>


<commit_before>// returns length of array or collection
function len (thing) {
    if (typeof thing == 'undefined' || thing == null) return 0;
    try {
        return thing.size();
    } catch (err) {
        return thing.length;
    }
}

// returns item[0] of item['0'] from array or collection
function first (thing) {
    return _get_element(thing, 0);
}

// returns true if item is in arr array
function found (item, arr) { return (typeof arr != 'undefined') && arr != null && _findIndex(arr, function(o){return ''+o == item}) != -1; }

// returns true if any element in items array is found in arr array
function found_any (items, arr) {
    if (typeof items == 'undefined' || typeof arr == 'undefined' || items == null || arr == null) return false;
    for (var i = 0; i < len(items); i++) if (found(_get_element(items, i), arr)) return true;
    return false;
}

// calculate a percent value, where percentage is between 0 and 100, and amount is some number
function pct (percentage, amount) { return (parseFloat(percentage) / 100.0) * parseFloat(amount); }

// standard comparison functions
function gt (x, compare) { return x > compare; }
function ge (x, compare) { return x >= compare; }
function lt (x, compare) { return x < compare; }
function le (x, compare) { return x <= compare; }
function eq (x, compare) { return x == compare; }
function ne (x, compare) { return x != compare; }
function startsWith (x, compare) { return x.startsWith(compare); }

function _inner_get_element(not_null_arr, field) {
    var v = not_null_arr[field];
    if ((v === undefined || v === null) && typeof not_null_arr.get === 'function') return not_null_arr.get(field);
    return v;
}

function _get_element(arr, field) {
    if (arr == null) return null;
    var v = _inner_get_element(arr, field);
    if ((v === undefined || v === null) && typeof field === 'number') return _inner_get_element(arr, '' + field);
    return v;
}

function match_object (field, value, comparison, found) {
    return function (obj) {
        if (typeof obj == 'undefined' || obj == null) return false;
        var target = obj;
        var path = field;
        var dotPos = path.indexOf('.');
        var v;
        while (dotPos != -1) {
            var prop = path.substring(0, dotPos);
            v = _get_element(target, prop);
            if (!v) return false;
            target = v;
            path = path.substring(dotPos+1);
            dotPos = path.indexOf('.');
        }
        v = _get_element(target, path);
        if (v && comparison(v, value)) {
            if (typeof found != 'undefined') {
                found.push(obj);
                return false;
            } else {
                return true;
            }
        }
        return false;
    };
}

// function to find the first object in array that matches field==value
// field may contain embedded dots to navigate within each object element of the array
function find (arr, field, value, comparison) {
    if (typeof comparison == 'undefined') comparison = eq;
    return _find(arr, match_object(field, value, comparison));
    // arr.find(match_object(field, value, comparison));
}

function _find (arr, func) {
    if ((typeof arr == 'undefined') || arr == null) return null;
    for (var i = 0; i < len(arr); i++) {
        var v = _get_element(arr, i);
        if (func(v)) return v;
    }
    return null;
}

function _findIndex (arr, func) {
    if ((typeof arr == 'undefined') || arr == null) return null;
    for (var i = 0; i < len(arr); i++) {
        if (func(_get_element(arr, i))) return i;
    }
    return -1;
}

function contains (arr, field, comparison, value) {
    var found = find(arr, field, value, comparison);
    return (typeof found !== 'undefined') && found !== null && found !== false;
}

// function to find the all object in array that match field==value
// field may contain embedded dots to navigate within each object element of the array
function find_all (arr, field, value, comparison) {
    if (typeof comparison == 'undefined') comparison = eq;
    var found = [];
    if ((typeof arr == 'undefined') || arr == null || len(arr) == 0) return found;
    _find(arr, match_object(field, value, comparison, found));
    // arr.find(match_object(field, value, comparison, found));
    return found;
}

// return sum total of array elements
function sum_total (arr, field) {
    var hasField = (typeof field != 'undefined');
    var sum = 0;
    for (var i = 0; i < len(arr); i++) {
        var v = _get_element(arr, i);
        sum += (hasField ? _get_element(v, field) : v);
    }
    return sum;
}

// returns a function that:
// 1) applies itemFunc function to an item, 2) uses comparison function to compare the result against compareVal
function compare (itemFunc, comparison, compareVal) {
    return function (item) {
        if ((typeof item != 'undefined') && item != null) {
            var val = itemFunc(item);
            if ((typeof val != 'undefined') && val != null) {
                return comparison(itemFunc(item), compareVal);
            }
        }
        return false;
    };
}

// return an itemFunc that treats item.field as a percentage, and multiplies it by total, and compares it against compareVal
function compare_pct (field, total, comparison, compareVal) {
    return function (item) {
        if ((typeof item == 'undefined') || item == null) return false;
        var val = _get_element(item, field);
        return (typeof val != 'undefined') && val != null && comparison(pct(val, total), compareVal);
    }
}

// apply itemFunc to each item in array arr. if any such invocation of itemFunc returns true, then this function returns true
function match_any (arr, itemFunc) {
    if ((typeof arr == 'undefined') || arr == null || len(arr) == 0) return false;
    // var found = arr.find(itemFunc);
    var found = _find(arr, itemFunc);
    return (typeof found != 'undefined') && found != null;
}

// functions for rounding up/down to nearest multiple
function up (x, multiple) { return multiple * parseInt(Math.ceil(parseFloat(x)/parseFloat(multiple))); }
function down (x, multiple) { return multiple * parseInt(Math.floor(parseFloat(x)/parseFloat(multiple))); }

// percentage difference between two numbers, as a floating-point number (1% == 1.0, 100% == 100.0, -5.4% == -5.4)
function pct_diff (x, y) {
    var d1 = 100 * (x/y);
    var d2 = 100 * (y/x);
    return d1 > d2 ? d1 : d2;
}

// return true if x is "close enough" to y, in terms of max_pct (default is 1%)
function is_close_enough (x, y, max_pct) {
    return 100 - pct_diff(x, y) <= ((typeof max_pct == "undefined") ? 1.0 : max_pct);
}
<commit_msg>add is_within<commit_after>// returns length of array or collection
function len (thing) {
    if (typeof thing == 'undefined' || thing == null) return 0;
    try {
        return thing.size();
    } catch (err) {
        return thing.length;
    }
}

// returns item[0] of item['0'] from array or collection
function first (thing) {
    return _get_element(thing, 0);
}

// returns true if item is in arr array
function found (item, arr) { return (typeof arr != 'undefined') && arr != null && _findIndex(arr, function(o){return ''+o == item}) != -1; }

// returns true if any element in items array is found in arr array
function found_any (items, arr) {
    if (typeof items == 'undefined' || typeof arr == 'undefined' || items == null || arr == null) return false;
    for (var i = 0; i < len(items); i++) if (found(_get_element(items, i), arr)) return true;
    return false;
}

// calculate a percent value, where percentage is between 0 and 100, and amount is some number
function pct (percentage, amount) { return (parseFloat(percentage) / 100.0) * parseFloat(amount); }

// standard comparison functions
function gt (x, compare) { return x > compare; }
function ge (x, compare) { return x >= compare; }
function lt (x, compare) { return x < compare; }
function le (x, compare) { return x <= compare; }
function eq (x, compare) { return x == compare; }
function ne (x, compare) { return x != compare; }
function startsWith (x, compare) { return x.startsWith(compare); }

function _inner_get_element(not_null_arr, field) {
    var v = not_null_arr[field];
    if ((v === undefined || v === null) && typeof not_null_arr.get === 'function') return not_null_arr.get(field);
    return v;
}

function _get_element(arr, field) {
    if (arr == null) return null;
    var v = _inner_get_element(arr, field);
    if ((v === undefined || v === null) && typeof field === 'number') return _inner_get_element(arr, '' + field);
    return v;
}

function match_object (field, value, comparison, found) {
    return function (obj) {
        if (typeof obj == 'undefined' || obj == null) return false;
        var target = obj;
        var path = field;
        var dotPos = path.indexOf('.');
        var v;
        while (dotPos != -1) {
            var prop = path.substring(0, dotPos);
            v = _get_element(target, prop);
            if (!v) return false;
            target = v;
            path = path.substring(dotPos+1);
            dotPos = path.indexOf('.');
        }
        v = _get_element(target, path);
        if (v && comparison(v, value)) {
            if (typeof found != 'undefined') {
                found.push(obj);
                return false;
            } else {
                return true;
            }
        }
        return false;
    };
}

// function to find the first object in array that matches field==value
// field may contain embedded dots to navigate within each object element of the array
function find (arr, field, value, comparison) {
    if (typeof comparison == 'undefined') comparison = eq;
    return _find(arr, match_object(field, value, comparison));
    // arr.find(match_object(field, value, comparison));
}

function _find (arr, func) {
    if ((typeof arr == 'undefined') || arr == null) return null;
    for (var i = 0; i < len(arr); i++) {
        var v = _get_element(arr, i);
        if (func(v)) return v;
    }
    return null;
}

function _findIndex (arr, func) {
    if ((typeof arr == 'undefined') || arr == null) return null;
    for (var i = 0; i < len(arr); i++) {
        if (func(_get_element(arr, i))) return i;
    }
    return -1;
}

function contains (arr, field, comparison, value) {
    var found = find(arr, field, value, comparison);
    return (typeof found !== 'undefined') && found !== null && found !== false;
}

// function to find the all object in array that match field==value
// field may contain embedded dots to navigate within each object element of the array
function find_all (arr, field, value, comparison) {
    if (typeof comparison == 'undefined') comparison = eq;
    var found = [];
    if ((typeof arr == 'undefined') || arr == null || len(arr) == 0) return found;
    _find(arr, match_object(field, value, comparison, found));
    // arr.find(match_object(field, value, comparison, found));
    return found;
}

// return sum total of array elements
function sum_total (arr, field) {
    var hasField = (typeof field != 'undefined');
    var sum = 0;
    for (var i = 0; i < len(arr); i++) {
        var v = _get_element(arr, i);
        sum += (hasField ? _get_element(v, field) : v);
    }
    return sum;
}

// returns a function that:
// 1) applies itemFunc function to an item, 2) uses comparison function to compare the result against compareVal
function compare (itemFunc, comparison, compareVal) {
    return function (item) {
        if ((typeof item != 'undefined') && item != null) {
            var val = itemFunc(item);
            if ((typeof val != 'undefined') && val != null) {
                return comparison(itemFunc(item), compareVal);
            }
        }
        return false;
    };
}

// return an itemFunc that treats item.field as a percentage, and multiplies it by total, and compares it against compareVal
function compare_pct (field, total, comparison, compareVal) {
    return function (item) {
        if ((typeof item == 'undefined') || item == null) return false;
        var val = _get_element(item, field);
        return (typeof val != 'undefined') && val != null && comparison(pct(val, total), compareVal);
    }
}

// apply itemFunc to each item in array arr. if any such invocation of itemFunc returns true, then this function returns true
function match_any (arr, itemFunc) {
    if ((typeof arr == 'undefined') || arr == null || len(arr) == 0) return false;
    // var found = arr.find(itemFunc);
    var found = _find(arr, itemFunc);
    return (typeof found != 'undefined') && found != null;
}

// functions for rounding up/down to nearest multiple
function up (x, multiple) { return multiple * parseInt(Math.ceil(parseFloat(x)/parseFloat(multiple))); }
function down (x, multiple) { return multiple * parseInt(Math.floor(parseFloat(x)/parseFloat(multiple))); }

// percentage difference between two numbers, as a floating-point number (1% == 1.0, 100% == 100.0, -5.4% == -5.4)
function pct_diff (x, y) {
    var d1 = 100 * (x/y);
    var d2 = 100 * (y/x);
    return d1 > d2 ? d1 : d2;
}

// return true if x is "close enough" to y, in terms of max_pct (default is 1%)
function is_close_enough (x, y, max_pct) {
    return 100 - pct_diff(x, y) <= ((typeof max_pct == "undefined") ? 1.0 : max_pct);
}

// return true if x is "within" max_delta of y
function is_within (x, y, max_delta) {
    return Math.abs(x - y) < max_delta;
}
<|endoftext|>


<commit_before>if('serviceWorker' in navigator){

    navigator.serviceWorker
        .register('./service-worker.js', { scope: './' })
        .then(function(registration){
            console.log("Service Worker Registered", registration.scope);
        })
        .catch(function(err){
            console.log("Service worker failed to register", err);
        })
}<commit_msg>d<commit_after>// if('serviceWorker' in navigator){

//     navigator.serviceWorker
//         .register('./service-worker.js', { scope: './' })
//         .then(function(registration){
//             console.log("Service Worker Registered", registration.scope);
//         })
//         .catch(function(err){
//             console.log("Service worker failed to register", err);
//         })
// }

if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
      navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
        // Registration was successful
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
      }, function(err) {
        // registration failed :(
        console.log('ServiceWorker registration failed: ', err);
      });
    });
  }
<|endoftext|>


<commit_before><commit_msg>Update script.js<commit_after><|endoftext|>


<commit_before>var _ = require('underscore');
var async = require('async');
var Promise = require('bluebird');

var models = require('../../models');
var config = require('../../config');
var logger = require('../../logger');
var db = require('../../db');

module.exports = {
    sync: function(courseInfo, testDB, questionDB, callback) {
        var that = module.exports;
        // find all the testInstances in mongo
        db.accessCollect.find({}, function(err, cursor) {
            if (err) return callback(err);
            cursor.count(function(err, nObj) {
                if (err) return callback(err);
                var i = 0;
                (function handle() {
                    cursor.next(function(err, a) {
                        if (err) return callback(err);
                        if (a == null) return callback(null);
                        if (i % 1000 === 0) logger.infoOverride("accesses: " + i + " of " + nObj);
                        i++;
                        if (a.method !== "GET") return setTimeout(handle, 0);
                        if (a.userUID !== a.authUID) return setTimeout(handle, 0);
                        var result = /^\/qInstances\/([^\/]+)\/client.js/.exec(a.path);
                        if (result == null) return setTimeout(handle, 0);
                        var qiid = result[1];
                        Promise.try(function() {
                            var questionInstance;
                            return Promise.try(function() {
                                return models.QuestionInstance.findOne({where: {
                                    qiid: qiid,
                                }});
                            }).then(function(findQuestionInstance) {
                                questionInstance = findQuestionInstance;
                                if (!questionInstance) throw Error('no questionInstance where qiid = ' + qiid + ' for aid = ' + a.aid);
                                return models.QuestionView.findOrCreate({where: {
                                    mongoId: String(a._id),
                                }});
                            }).spread(function(newQuestionView, created) {
                                questionView = newQuestionView;
                                return questionView.update({
                                    date: a.timestamp,
                                    questionInstanceId: questionInstance.id,
                                });
                            }).then(function() {
                                setTimeout(handle, 0);
                            }).catch(function(err) {
                                logger.error(err);
                                setTimeout(handle, 0);
                            });
                        });
                    });
                })();
            });
        });
    },
};
<commit_msg>speed up async iteration in sync of questionViews<commit_after>var _ = require('underscore');
var async = require('async');
var Promise = require('bluebird');

var models = require('../../models');
var config = require('../../config');
var logger = require('../../logger');
var db = require('../../db');

module.exports = {
    sync: function(courseInfo, testDB, questionDB, callback) {
        var that = module.exports;
        db.accessCollect.find({}, function(err, cursor) {
            if (err) return callback(err);
            cursor.count(function(err, nObj) {
                if (err) return callback(err);
                var i = 0;
                (function handle() {
                    cursor.next(function(err, a) {
                        if (err) return callback(err);
                        if (a == null) return callback(null);
                        if (i % 1000 === 0) logger.infoOverride("accesses: " + i + " of " + nObj);
                        i++;
                        if (a.method !== "GET") return setTimeout(handle, 0);
                        if (a.userUID !== a.authUID) return setTimeout(handle, 0);
                        var result = /^\/qInstances\/([^\/]+)\/client.js/.exec(a.path);
                        if (result == null) return setTimeout(handle, 0);
                        var qiid = result[1];
                        Promise.try(function() {
                            var questionInstance;
                            return Promise.try(function() {
                                return models.QuestionInstance.findOne({where: {
                                    qiid: qiid,
                                }});
                            }).then(function(findQuestionInstance) {
                                questionInstance = findQuestionInstance;
                                if (!questionInstance) throw Error('no questionInstance where qiid = ' + qiid + ' for aid = ' + a.aid);
                                return models.QuestionView.findOrCreate({where: {
                                    mongoId: String(a._id),
                                }});
                            }).spread(function(newQuestionView, created) {
                                questionView = newQuestionView;
                                return questionView.update({
                                    date: a.timestamp,
                                    questionInstanceId: questionInstance.id,
                                });
                            }).then(function() {
                                if (i % 1000 == 0) {
                                    setTimeout(handle, 0);
                                } else {
                                    handle();
                                }
                            }).catch(function(err) {
                                logger.error(err);
                                setTimeout(handle, 0);
                            });
                        });
                    });
                })();
            });
        });
    },
};
<|endoftext|>


<commit_before>/**
 *
 *    Copyright (c) 2020 Silicon Labs
 *
 *    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.
 */
import Vue from 'vue'

export function updateInformationText(state, text) {
  state.informationText = text
}

export function updateClusters(state, clusters) {
  state.clusters = clusters
}

export function updateSelectedCluster(state, cluster) {
  state.clustersView.selected = cluster
}

export function updateSelectedEndpoint(state, endpoint) {
  state.endpointView.selectedEndpoint = endpoint
}

export function updateAttributes(state, attributes) {
  attributes.forEach((attribute) => {
    if (state.attributeView.defaultValues[attribute.id] === undefined) {
      Vue.set(
        state.attributeView.defaultValues,
        attribute.id,
        attribute.defaultValue
      )
    }
    if (state.attributeView.reportingMin[attribute.id] === undefined) {
      Vue.set(state.attributeView.reportingMin, attribute.id, 0)
    }
    if (state.attributeView.reportingMax[attribute.id] === undefined) {
      Vue.set(state.attributeView.reportingMax, attribute.id, 65344)
    }
    if (state.attributeView.reportableChange[attribute.id] === undefined) {
      Vue.set(state.attributeView.reportableChange, attribute.id, 0)
    }
  })
  state.attributes = attributes
}

export function initializeDefaultEndpoints(state, defaultEndpoints) {
  defaultEndpoints.forEach((endpoint) => {
    if (state.endpointView.endpointId[endpoint.id] === undefined) {
      Vue.set(state.endpointView.endpointId, endpoint.id, endpoint.eptId)
    }
    if (state.endpointView.endpointType[endpoint.id] === undefined) {
      Vue.set(
        state.endpointView.endpointType,
        endpoint.id,
        endpoint.endpointType
      )
    }
    if (state.endpointView.networkId[endpoint.id] === undefined) {
      Vue.set(state.endpointView.networkId, endpoint.id, endpoint.network)
    }
  })
}

export function addEndpoint(state, endpoint) {
  Vue.set(state.endpointView.endpointId, endpoint.id, endpoint.eptId)
  Vue.set(state.endpointView.endpointType, endpoint.id, endpoint.endpointType)
  Vue.set(state.endpointView.networkId, endpoint.id, endpoint.network)
  Vue.set(
    state.endpointView.endpointIdValidationIssues,
    endpoint.id,
    endpoint.endpointIdValidationIssues
  )
  Vue.set(
    state.endpointView.networkIdValidationIssues,
    endpoint.id,
    endpoint.networkIdValidationIssues
  )
}

export function updateEndpoint(state, context) {
  context.changes.forEach((data) => {
    Vue.set(state.endpointView[data.updatedKey], context.id, data.value)
  })
  Vue.set(
    state.endpointView.endpointIdValidationIssues,
    context.id,
    context.endpointIdValidationIssues
  )
  Vue.set(
    state.endpointView.networkIdValidationIssues,
    context.id,
    context.networkIdValidationIssues
  )
}

export function initializeDefaultEndpointsTypes(state, defaultEndpointsTypes) {
  defaultEndpointsTypes.forEach((endpointType) => {
    if (state.endpointTypeView.name[endpointType.id] === undefined) {
      Vue.set(state.endpointTypeView.name, endpointType.id, endpointType.name)
    }
    if (state.endpointTypeView.deviceTypeRef[endpointType.id] === undefined) {
      Vue.set(
        state.endpointTypeView.deviceTypeRef,
        endpointType.id,
        endpointType.deviceTypeRef
      )
    }
  })
}

export function addEndpointType(state, endpointType) {
  Vue.set(state.endpointTypeView.name, endpointType.id, endpointType.name)
  Vue.set(
    state.endpointTypeView.deviceTypeRef,
    endpointType.id,
    endpointType.deviceTypeRef
  )
}

export function updateAttributeDefaults(state, selectionContext) {
  Vue.set(
    state.attributeView.defaultValues,
    selectionContext.id,
    selectionContext.newDefaultValue
  )
  Vue.set(
    state.attributeView.defaultValueValidationIssues,
    selectionContext.id,
    selectionContext.defaultValueValidationIssues
  )
}

export function updateCommands(state, commands) {
  state.commands = commands
}

export function updateZclDeviceTypes(state, zclDeviceTypes) {
  state.zclDeviceTypes = zclDeviceTypes
}

export function updateEndpointConfigs(state, endpoints) {
  state.endpoints = endpoints
}

export function selectConfiguration(state, configurationName) {
  state.configurationView.selected = configurationName
}

export function updateInclusionList(state, selectionContext) {
  var inclusionList = state[selectionContext.view][selectionContext.listType]
  if (selectionContext.added) {
    inclusionList.push(selectionContext.id)
  } else {
    var elementIndex = inclusionList.indexOf(selectionContext.id)
    inclusionList.splice(elementIndex, 1)
  }
  state[selectionContext.view][selectionContext.listType] = inclusionList
}

export function setDeviceTypeReference(state, endpointIdDeviceTypeRefPair) {
  Vue.set(
    state.endpointTypeView.deviceTypeRef,
    endpointIdDeviceTypeRefPair.endpointId,
    endpointIdDeviceTypeRefPair.deviceTypeRef
  )
}

export function updateSelectedEndpointType(state, endpointType) {
  state.endpointTypeView.selectedEndpointType = endpointType
}

export function removeEndpointType(state, endpointType) {
  state.endpointTypeView.selectedEndpointType = []
  Vue.delete(state.endpointTypeView.name, endpointType.id)
  Vue.delete(state.endpointTypeView.deviceTypeRef, endpointType.id)
}

export function deleteEndpoint(state, endpoint) {
  state.endpointView.selectedEndpoint = []
  Vue.delete(state.endpointView.endpointId, endpoint.id)
  Vue.delete(state.endpointView.endpointType, endpoint.id)
  Vue.delete(state.endpointView.networkId, endpoint.id)
}

export function setClusterList(state, data) {
  state.clustersView.selectedClients = data.clients
  state.clustersView.selectedServers = data.servers
}

export function resetAttributeDefaults(state) {
  state.attributeView.defaultValues = {}
  state.attributeView.reportingMin = {}
  state.attributeView.reportingMin = {}
  state.attributeView.reportableChange = {}

  state.attributes.forEach((attribute) => {
    Vue.set(
      state.attributeView.defaultValues,
      attribute.id,
      attribute.defaultValue
    )
    Vue.set(state.attributeView.reportingMin, attribute.id, 0)
    Vue.set(state.attributeView.reportingMax, attribute.id, 65344)
    Vue.set(state.attributeView.reportableChange, attribute.id, 0)
  })
}

export function setAttributeLists(state, data) {
  state.attributeView.selectedAttributes = data.included
  state.attributeView.selectedExternal = data.external
  state.attributeView.selectedFlash = data.flash
  state.attributeView.selectedSingleton = data.singleton
  state.attributeView.selectedBounded = data.bounded
  state.attributeView.selectedReporting = data.includedReportable

  resetAttributeDefaults(state)
  Object.entries(data.defaultValue).forEach(([attributeRef, defaultVal]) => {
    Vue.set(state.attributeView.defaultValues, attributeRef, defaultVal)
  })
  Object.entries(data.minInterval).forEach(([attributeRef, defaultVal]) => {
    Vue.set(state.attributeView.reportingMin, attributeRef, defaultVal)
  })

  Object.entries(data.maxInterval).forEach(([attributeRef, defaultVal]) => {
    Vue.set(state.attributeView.reportingMax, attributeRef, defaultVal)
  })
  Object.entries(data.reportableChange).forEach(
    ([attributeRef, defaultVal]) => {
      Vue.set(state.attributeView.reportableChange, attributeRef, defaultVal)
    }
  )
}

export function setCommandLists(state, data) {
  state.commandView.selectedIn = data.incoming
  state.commandView.selectedOut = data.outgoing
}

export function setRecommendedClusterList(state, data) {
  Vue.set(state.clustersView, 'recommendedClients', data.recommendedClients)
  Vue.set(state.clustersView, 'recommendedServers', data.recommendedServers)
}

export function setRequiredAttributesList(state, data) {
  Vue.set(state.attributeView, 'requiredAttributes', data.requiredAttributes)
}

export function setRequiredCommandsList(state, data) {
  Vue.set(state.commandView, 'requiredCommands', data.requiredCommands)
}

export function setLeftDrawerState(state, data) {
  state.leftDrawerOpenState = data
}

export function setMiniState(state, data) {
  state.miniState = data
}

export function initializeEndpoints(state, endpoints) {
  endpoints.forEach((e) => {
    Vue.set(state.endpointView.endpoint, e.endpointRef, e.endpointId)
  })
}

export function initializeEndpointTypes(state, endpointTypes) {
  endpointTypes.forEach((et) => {
    Vue.set(state.endpointTypeView.name, et.id, et.name)
  })
}

export function setOptions(state, data) {
  Vue.set(state.genericOptions, data.option, [
    ...new Set(
      data.data
        .filter((d) => {
          return d.optionCategory === data.option
        })
        .map((d) => {
          return { optionCode: d.optionCode, optionLabel: d.optionLabel }
        })
    ),
  ])
}

export function setSelectedGenericOption(state, keyValue) {
  Vue.set(state.selectedGenericOptions, keyValue.key, keyValue.value)
}
<commit_msg>Fix typo<commit_after>/**
 *
 *    Copyright (c) 2020 Silicon Labs
 *
 *    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.
 */
import Vue from 'vue'

export function updateInformationText(state, text) {
  state.informationText = text
}

export function updateClusters(state, clusters) {
  state.clusters = clusters
}

export function updateSelectedCluster(state, cluster) {
  state.clustersView.selected = cluster
}

export function updateSelectedEndpoint(state, endpoint) {
  state.endpointView.selectedEndpoint = endpoint
}

export function updateAttributes(state, attributes) {
  attributes.forEach((attribute) => {
    if (state.attributeView.defaultValues[attribute.id] === undefined) {
      Vue.set(
        state.attributeView.defaultValues,
        attribute.id,
        attribute.defaultValue
      )
    }
    if (state.attributeView.reportingMin[attribute.id] === undefined) {
      Vue.set(state.attributeView.reportingMin, attribute.id, 0)
    }
    if (state.attributeView.reportingMax[attribute.id] === undefined) {
      Vue.set(state.attributeView.reportingMax, attribute.id, 65344)
    }
    if (state.attributeView.reportableChange[attribute.id] === undefined) {
      Vue.set(state.attributeView.reportableChange, attribute.id, 0)
    }
  })
  state.attributes = attributes
}

export function initializeDefaultEndpoints(state, defaultEndpoints) {
  defaultEndpoints.forEach((endpoint) => {
    if (state.endpointView.endpointId[endpoint.id] === undefined) {
      Vue.set(state.endpointView.endpointId, endpoint.id, endpoint.eptId)
    }
    if (state.endpointView.endpointType[endpoint.id] === undefined) {
      Vue.set(
        state.endpointView.endpointType,
        endpoint.id,
        endpoint.endpointType
      )
    }
    if (state.endpointView.networkId[endpoint.id] === undefined) {
      Vue.set(state.endpointView.networkId, endpoint.id, endpoint.network)
    }
  })
}

export function addEndpoint(state, endpoint) {
  Vue.set(state.endpointView.endpointId, endpoint.id, endpoint.eptId)
  Vue.set(state.endpointView.endpointType, endpoint.id, endpoint.endpointType)
  Vue.set(state.endpointView.networkId, endpoint.id, endpoint.network)
  Vue.set(
    state.endpointView.endpointIdValidationIssues,
    endpoint.id,
    endpoint.endpointIdValidationIssues
  )
  Vue.set(
    state.endpointView.networkIdValidationIssues,
    endpoint.id,
    endpoint.networkIdValidationIssues
  )
}

export function updateEndpoint(state, context) {
  context.changes.forEach((data) => {
    Vue.set(state.endpointView[data.updatedKey], context.id, data.value)
  })
  Vue.set(
    state.endpointView.endpointIdValidationIssues,
    context.id,
    context.endpointIdValidationIssues
  )
  Vue.set(
    state.endpointView.networkIdValidationIssues,
    context.id,
    context.networkIdValidationIssues
  )
}

export function initializeDefaultEndpointsTypes(state, defaultEndpointsTypes) {
  defaultEndpointsTypes.forEach((endpointType) => {
    if (state.endpointTypeView.name[endpointType.id] === undefined) {
      Vue.set(state.endpointTypeView.name, endpointType.id, endpointType.name)
    }
    if (state.endpointTypeView.deviceTypeRef[endpointType.id] === undefined) {
      Vue.set(
        state.endpointTypeView.deviceTypeRef,
        endpointType.id,
        endpointType.deviceTypeRef
      )
    }
  })
}

export function addEndpointType(state, endpointType) {
  Vue.set(state.endpointTypeView.name, endpointType.id, endpointType.name)
  Vue.set(
    state.endpointTypeView.deviceTypeRef,
    endpointType.id,
    endpointType.deviceTypeRef
  )
}

export function updateAttributeDefaults(state, selectionContext) {
  Vue.set(
    state.attributeView.defaultValues,
    selectionContext.id,
    selectionContext.newDefaultValue
  )
  Vue.set(
    state.attributeView.defaultValueValidationIssues,
    selectionContext.id,
    selectionContext.defaultValueValidationIssues
  )
}

export function updateCommands(state, commands) {
  state.commands = commands
}

export function updateZclDeviceTypes(state, zclDeviceTypes) {
  state.zclDeviceTypes = zclDeviceTypes
}

export function updateEndpointConfigs(state, endpoints) {
  state.endpoints = endpoints
}

export function selectConfiguration(state, configurationName) {
  state.configurationView.selected = configurationName
}

export function updateInclusionList(state, selectionContext) {
  var inclusionList = state[selectionContext.view][selectionContext.listType]
  if (selectionContext.added) {
    inclusionList.push(selectionContext.id)
  } else {
    var elementIndex = inclusionList.indexOf(selectionContext.id)
    inclusionList.splice(elementIndex, 1)
  }
  state[selectionContext.view][selectionContext.listType] = inclusionList
}

export function setDeviceTypeReference(state, endpointIdDeviceTypeRefPair) {
  Vue.set(
    state.endpointTypeView.deviceTypeRef,
    endpointIdDeviceTypeRefPair.endpointId,
    endpointIdDeviceTypeRefPair.deviceTypeRef
  )
}

export function updateSelectedEndpointType(state, endpointType) {
  state.endpointTypeView.selectedEndpointType = endpointType
}

export function removeEndpointType(state, endpointType) {
  state.endpointTypeView.selectedEndpointType = []
  Vue.delete(state.endpointTypeView.name, endpointType.id)
  Vue.delete(state.endpointTypeView.deviceTypeRef, endpointType.id)
}

export function deleteEndpoint(state, endpoint) {
  state.endpointView.selectedEndpoint = []
  Vue.delete(state.endpointView.endpointId, endpoint.id)
  Vue.delete(state.endpointView.endpointType, endpoint.id)
  Vue.delete(state.endpointView.networkId, endpoint.id)
}

export function setClusterList(state, data) {
  state.clustersView.selectedClients = data.clients
  state.clustersView.selectedServers = data.servers
}

export function resetAttributeDefaults(state) {
  state.attributeView.defaultValues = {}
  state.attributeView.reportingMin = {}
  state.attributeView.reportingMin = {}
  state.attributeView.reportableChange = {}

  state.attributes.forEach((attribute) => {
    Vue.set(
      state.attributeView.defaultValues,
      attribute.id,
      attribute.defaultValue
    )
    Vue.set(state.attributeView.reportingMin, attribute.id, 0)
    Vue.set(state.attributeView.reportingMax, attribute.id, 65344)
    Vue.set(state.attributeView.reportableChange, attribute.id, 0)
  })
}

export function setAttributeLists(state, data) {
  state.attributeView.selectedAttributes = data.included
  state.attributeView.selectedExternal = data.external
  state.attributeView.selectedFlash = data.flash
  state.attributeView.selectedSingleton = data.singleton
  state.attributeView.selectedBounded = data.bounded
  state.attributeView.selectedReporting = data.includedReportable

  resetAttributeDefaults(state)
  Object.entries(data.defaultValue).forEach(([attributeRef, defaultVal]) => {
    Vue.set(state.attributeView.defaultValues, attributeRef, defaultVal)
  })
  Object.entries(data.minInterval).forEach(([attributeRef, defaultVal]) => {
    Vue.set(state.attributeView.reportingMin, attributeRef, defaultVal)
  })

  Object.entries(data.maxInterval).forEach(([attributeRef, defaultVal]) => {
    Vue.set(state.attributeView.reportingMax, attributeRef, defaultVal)
  })
  Object.entries(data.reportableChange).forEach(
    ([attributeRef, defaultVal]) => {
      Vue.set(state.attributeView.reportableChange, attributeRef, defaultVal)
    }
  )
}

export function setCommandLists(state, data) {
  state.commandView.selectedIn = data.incoming
  state.commandView.selectedOut = data.outgoing
}

export function setRecommendedClusterList(state, data) {
  Vue.set(state.clustersView, 'recommendedClients', data.recommendedClients)
  Vue.set(state.clustersView, 'recommendedServers', data.recommendedServers)
}

export function setRequiredAttributesList(state, data) {
  Vue.set(state.attributeView, 'requiredAttributes', data.requiredAttributes)
}

export function setRequiredCommandsList(state, data) {
  Vue.set(state.commandView, 'requiredCommands', data.requiredCommands)
}

export function setLeftDrawerState(state, data) {
  state.leftDrawerOpenState = data
}

export function setMiniState(state, data) {
  state.miniState = data
}

export function initializeEndpoints(state, endpoints) {
  endpoints.forEach((e) => {
    Vue.set(state.endpointView.endpointId, e.endpointRef, e.endpointId)
  })
}

export function initializeEndpointTypes(state, endpointTypes) {
  endpointTypes.forEach((et) => {
    Vue.set(state.endpointTypeView.name, et.id, et.name)
  })
}

export function setOptions(state, data) {
  Vue.set(state.genericOptions, data.option, [
    ...new Set(
      data.data
        .filter((d) => {
          return d.optionCategory === data.option
        })
        .map((d) => {
          return { optionCode: d.optionCode, optionLabel: d.optionLabel }
        })
    ),
  ])
}

export function setSelectedGenericOption(state, keyValue) {
  Vue.set(state.selectedGenericOptions, keyValue.key, keyValue.value)
}
<|endoftext|>


<commit_before>(function(){
  game.state.add('gameOver', {create:create});

  // var addScore;
  var topTenScores;
  getScoresFromFirebase();

  function create(){
    console.log(topTenScores);
    game.add.text(100, 120, 'HIGH SCORE LEADERBOARD', { fontSize: '48px', fill: 'white' });
    game.add.text(200, 170, topTenScores[0].initials + '     ' + topTenScores[0].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 200, topTenScores[1].initials + '     ' + topTenScores[1].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 230, topTenScores[2].initials + '     ' + topTenScores[2].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 260, topTenScores[3].initials + '     ' + topTenScores[3].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 290, topTenScores[4].initials + '     ' + topTenScores[4].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 320, topTenScores[5].initials + '     ' + topTenScores[5].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 350, topTenScores[6].initials + '     ' + topTenScores[6].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 380, topTenScores[7].initials + '     ' + topTenScores[7].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 410, topTenScores[8].initials + '     ' + topTenScores[8].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 440, topTenScores[9].initials + '     ' + topTenScores[9].score, { fontSize: '32px', fill: 'white' });
    game.add.text(130, 490, '- press SPACE to restart -', { fontSize: '32px', fill: 'white' });

    //addScore();
    var spacebar = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    spacebar.onDown.add(restartGame);
  }

  function restartGame() {
    this.game.state.start('ready');
  }

  function getScoresFromFirebase () {
  var fb = new Firebase('https://bitblaster.firebaseio.com/');
  fb.once('value', function(snapshot) {
    var storedScores = snapshot.val();
    var sortedScores =  _.sortBy(storedScores, 'score');
    topTenScores = sortedScores.slice(sortedScores.length -10, sortedScores.length).reverse();
    _.forEach(topTenScores, function(scoreObj) {
    console.log(scoreObj.initials + ": " + scoreObj.score);
    });
  });
}
})();<commit_msg>high scores update in realtime<commit_after>(function(){
  game.state.add('gameOver', {create:create});

  function create(){
    getScoresFromFirebase();
  }

  function restartGame() {
    this.game.state.start('ready');
  }

  function getScoresFromFirebase () {
  var fb = new Firebase('https://bitblaster.firebaseio.com/');
  fb.once('value', function(snapshot) {
    var storedScores = snapshot.val();
    var sortedScores =  _.sortBy(storedScores, 'score');
    leaderboard = sortedScores.slice(sortedScores.length -10, sortedScores.length).reverse();
    // _.forEach(leaderboard, function(scoreObj) {
    // console.log(scoreObj.initials + ": " + scoreObj.score);
    // });
    game.add.text(100, 120, 'HIGH SCORE LEADERBOARD', { fontSize: '48px', fill: 'white' });
    game.add.text(200, 170, " 1.  " + leaderboard[0].initials + '     ' + leaderboard[0].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 200, " 2.  " +leaderboard[1].initials + '     ' + leaderboard[1].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 230, " 3.  " +leaderboard[2].initials + '     ' + leaderboard[2].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 260, " 4.  " +leaderboard[3].initials + '     ' + leaderboard[3].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 290, " 5.  " +leaderboard[4].initials + '     ' + leaderboard[4].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 320, " 6.  " +leaderboard[5].initials + '     ' + leaderboard[5].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 350, " 7.  " +leaderboard[6].initials + '     ' + leaderboard[6].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 380, " 8.  " +leaderboard[7].initials + '     ' + leaderboard[7].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 410, " 9.  " +leaderboard[8].initials + '     ' + leaderboard[8].score, { fontSize: '32px', fill: 'white' });
    game.add.text(200, 440, "10. " +leaderboard[9].initials + '     ' + leaderboard[9].score, { fontSize: '32px', fill: 'white' });
    game.add.text(130, 490, '- press SPACE to restart -', { fontSize: '32px', fill: 'white' });

    //addScore();
    var spacebar = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    spacebar.onDown.add(restartGame);
  });
}
})();<|endoftext|>


<commit_before>import {
  TOGGLE_DEVELOPER_MODE
} from '../action-types'

const toggleDeveloperMode = developerMode => {
  return {
    type: TOGGLE_DEVELOPER_MODE,
    developerMode
  }
}

export {
  toggleDeveloperMode
}<commit_msg>Fixed linting error<commit_after>import {
  TOGGLE_DEVELOPER_MODE
} from '../action-types'

const toggleDeveloperMode = developerMode => {
  return {
    type: TOGGLE_DEVELOPER_MODE,
    developerMode
  }
}

export {
  toggleDeveloperMode
}
<|endoftext|>