<commit_before>var XXHash = require('xxhash');

module.exports = {
    getWeld : function (ctx, step) {
        var table = ctx.current.module.name;
        var dataParam = ctx.current.module.param;

        var hash = ctx.current.module.getMid();
        for(var i in dataParam) {
            hash += dataParam[i][0] + dataParam[i][1];
        }
        if(ctx.current.module.list) {
            hash += "key" + ctx.req.param.key;
        }
        hash = XXHash.hash(new Buffer(hash), 0x654C6162).toString(16);

        ctx.db.query(hash, function (db) {
            var where = "";
            var data = [];
            for(var i in dataParam) {
                where += "`" + dataParam[i][0] + "_" + dataParam[i][1] + "`=0x" + ctx.param.get(dataParam[i][0], dataParam[i][1]) + " and ";
            }
            where += "`key`=?";
            data.push(XXHash.hash(new Buffer(ctx.req.param.key), 0x654C6162));

            db.query("SELECT hex(`uid`) AS `uid`, `value` FROM `" + table + "` WHERE " + where, data, function(err, rows) {
                if(err) {
                    throw err;
                }
                if(rows.length < 1)  {
                    throw ctx.current.module.error('key.notfound');
                } else {
                    ctx.param.set(ctx.current.module.getMid(), "key", rows[0].uid.toString());
                    step();
                }
            });
        });
        return null;
    },
    get : function (ctx, step) {
        var table = ctx.current.module.name;
        var dataParam = ctx.current.module.param;

        var hash = ctx.current.module.getMid();
        for(var i in dataParam) {
            hash += dataParam[i][0] + dataParam[i][1];
        }
        if(ctx.current.module.list) {
            hash += "key" + ctx.req.param.key;
        }
        hash = XXHash.hash(new Buffer(hash), 0x654C6162).toString(16);

        ctx.db.query(hash, function (db) {
            var where = "";
            var data = [];
            for(var i in dataParam) {
                where += "`" + dataParam[i][0] + "_" + dataParam[i][1] + "`=0x" + ctx.param.get(dataParam[i][0], dataParam[i][1]) + " and ";
            }
            where += "`key`=?";
            data.push(XXHash.hash(new Buffer(ctx.req.param.key), 0x654C6162));

            db.query("SELECT hex(`uid`) AS `uid`, `value` FROM `" + table + "` WHERE " + where, data, function(err, rows) {
                if(err) {
                    throw err;
                }
                if(rows.length < 1)  {
                    throw ctx.current.module.error('key.notfound');
                } else {
                    ctx.res.send({uid:rows[0].uid.toString(),  value:rows[0].value});
                }

                step();
            });
        });
        return null;
    },
    set : function (ctx, step) {
        var table = ctx.current.module.name;
        var dataParam = ctx.current.module.param;

        var hash = ctx.current.module.getMid();
        for(var i in dataParam) {
            hash += dataParam[i][0] + dataParam[i][1];
        }
        if(ctx.current.module.list) {
            hash += "key" + ctx.req.param.key;
        }
        hash = XXHash.hash(new Buffer(hash), 0x654C6162).toString(16);

        ctx.saram.generateUID(function (uid) {
            ctx.db.query(hash, function (db) {
                var query = "INSERT INTO `" + table + "` VALUES(0x" + uid;
                for(var i in dataParam) {
                    query += ", 0x" + ctx.param.get(dataParam[i][0], dataParam[i][1]);
                }
                query += ", ?, ?, ?)  ON DUPLICATE KEY UPDATE `str`=?, `value`=?;"
                var values = [];
                values.push(XXHash.hash(new Buffer(ctx.req.param.key), 0x654C6162));
                for(var i=0; i<2; i++) {
                    values.push(ctx.req.param.key);
                    values.push(ctx.req.body.value);
                }

                db.query(query, values, function(err, rows) {
                    if(err) {
                        throw err;
                    } else {
                        ctx.res.send({state:"OK", uid:uid});
                    }

                    step();
                });
            });
        });

        return null;
    },
    list : function (ctx, step) {
        if(!ctx.current.module.list) {
            ctx.res.send({});
            step();
            return;
        }

        var table = ctx.current.module.name;
        var dataParam = ctx.current.module.param;

        var hash = ctx.current.module.getMid();
        for(var i in dataParam) {
            hash += dataParam[i][0] + dataParam[i][1];
        }
        hash = XXHash.hash(new Buffer(hash), 0x654C6162).toString(16);

        ctx.db.query(hash, function (db) {
            var where = "WHERE ";
            for(var i in dataParam) {
                where += "`" + dataParam[i][0] + "_" + dataParam[i][1] + "`=0x" + ctx.param.get(dataParam[i][0], dataParam[i][1]) + " and ";
            }
            where = where.substring(0, where.length - 5);
            if(where.length == 6) {
                where = "";
            }

            db.query("SELECT hex(`uid`) AS `uid`, `str` as `key`, `value` FROM `" + table + "` WHERE " + where, [], function(err, rows) {
                if(err) {
                    throw err;
                }
                ctx.res.send(rows);
                step();
            });
        });
        return null;
    }
};<commit_msg>fix keyvalue list bug<commit_after>var XXHash = require('xxhash');

module.exports = {
    getWeld : function (ctx, step) {
        var table = ctx.current.module.name;
        var dataParam = ctx.current.module.param;

        var hash = ctx.current.module.getMid();
        for(var i in dataParam) {
            hash += dataParam[i][0] + dataParam[i][1];
        }
        if(ctx.current.module.list) {
            hash += "key" + ctx.req.param.key;
        }
        hash = XXHash.hash(new Buffer(hash), 0x654C6162).toString(16);

        ctx.db.query(hash, function (db) {
            var where = "";
            var data = [];
            for(var i in dataParam) {
                where += "`" + dataParam[i][0] + "_" + dataParam[i][1] + "`=0x" + ctx.param.get(dataParam[i][0], dataParam[i][1]) + " and ";
            }
            where += "`key`=?";
            data.push(XXHash.hash(new Buffer(ctx.req.param.key), 0x654C6162));

            db.query("SELECT hex(`uid`) AS `uid`, `value` FROM `" + table + "` WHERE " + where, data, function(err, rows) {
                if(err) {
                    throw err;
                }
                if(rows.length < 1)  {
                    throw ctx.current.module.error('key.notfound');
                } else {
                    ctx.param.set(ctx.current.module.getMid(), "key", rows[0].uid.toString());
                    step();
                }
            });
        });
        return null;
    },
    get : function (ctx, step) {
        var table = ctx.current.module.name;
        var dataParam = ctx.current.module.param;

        var hash = ctx.current.module.getMid();
        for(var i in dataParam) {
            hash += dataParam[i][0] + dataParam[i][1];
        }
        if(ctx.current.module.list) {
            hash += "key" + ctx.req.param.key;
        }
        hash = XXHash.hash(new Buffer(hash), 0x654C6162).toString(16);

        ctx.db.query(hash, function (db) {
            var where = "";
            var data = [];
            for(var i in dataParam) {
                where += "`" + dataParam[i][0] + "_" + dataParam[i][1] + "`=0x" + ctx.param.get(dataParam[i][0], dataParam[i][1]) + " and ";
            }
            where += "`key`=?";
            data.push(XXHash.hash(new Buffer(ctx.req.param.key), 0x654C6162));

            db.query("SELECT hex(`uid`) AS `uid`, `value` FROM `" + table + "` WHERE " + where, data, function(err, rows) {
                if(err) {
                    throw err;
                }
                if(rows.length < 1)  {
                    throw ctx.current.module.error('key.notfound');
                } else {
                    ctx.res.send({uid:rows[0].uid.toString(),  value:rows[0].value});
                }

                step();
            });
        });
        return null;
    },
    set : function (ctx, step) {
        var table = ctx.current.module.name;
        var dataParam = ctx.current.module.param;

        var hash = ctx.current.module.getMid();
        for(var i in dataParam) {
            hash += dataParam[i][0] + dataParam[i][1];
        }
        if(ctx.current.module.list) {
            hash += "key" + ctx.req.param.key;
        }
        hash = XXHash.hash(new Buffer(hash), 0x654C6162).toString(16);

        ctx.saram.generateUID(function (uid) {
            ctx.db.query(hash, function (db) {
                var query = "INSERT INTO `" + table + "` VALUES(0x" + uid;
                for(var i in dataParam) {
                    query += ", 0x" + ctx.param.get(dataParam[i][0], dataParam[i][1]);
                }
                query += ", ?, ?, ?)  ON DUPLICATE KEY UPDATE `str`=?, `value`=?;"
                var values = [];
                values.push(XXHash.hash(new Buffer(ctx.req.param.key), 0x654C6162));
                for(var i=0; i<2; i++) {
                    values.push(ctx.req.param.key);
                    values.push(ctx.req.body.value);
                }

                db.query(query, values, function(err, rows) {
                    if(err) {
                        throw err;
                    } else {
                        ctx.res.send({state:"OK", uid:uid});
                    }

                    step();
                });
            });
        });

        return null;
    },
    list : function (ctx, step) {
        if(!ctx.current.module.list) {
            ctx.res.send({});
            step();
            return;
        }

        var table = ctx.current.module.name;
        var dataParam = ctx.current.module.param;

        var hash = ctx.current.module.getMid();
        for(var i in dataParam) {
            hash += dataParam[i][0] + dataParam[i][1];
        }
        hash = XXHash.hash(new Buffer(hash), 0x654C6162).toString(16);

        ctx.db.query(hash, function (db) {
            var where = "WHERE ";
            for(var i in dataParam) {
                where += "`" + dataParam[i][0] + "_" + dataParam[i][1] + "`=0x" + ctx.param.get(dataParam[i][0], dataParam[i][1]) + " and ";
            }
            where = where.substring(0, where.length - 5);
            if(where.length == 6) {
                where = "";
            }

            db.query("SELECT hex(`uid`) AS `uid`, `str` as `key`, `value` FROM `" + table + "` " + where, [], function(err, rows) {
                if(err) {
                    throw err;
                }
                ctx.res.send(rows);
                step();
            });
        });
        return null;
    }
};<|endoftext|>


<commit_before>(function () {
  'use strict';
  // Polls controller
  angular
    .module('polls')
    .controller('PollInputController', PollInputController);

  PollInputController.$inject = [
    '$rootScope',
    '$scope',
    '$state',
    '$window',
    'Authentication',
    'pollResolve',
    'notifResolve',
    '$bsModal',
    '$bsAside',
    'OptsService',
    'Socket',
    'CategorysService',
    'toastr',
    'Action',
    'ngDialog'
  ];

  function PollInputController(
    $rootScope,
    $scope,
    $state,
    $window,
    Authentication,
    poll,
    notif,
    $bsModal,
    $bsAside,
    Opts,
    Socket,
    Categorys,
    toast,
    Action,
    dialog
  ) {
    var vm = this;

    vm.authentication = Authentication;
    vm.isLogged = vm.authentication.user ? true : false;
    vm.poll = poll;
    vm.poll.close = vm.poll.close ? moment(vm.poll.close) : vm.poll.close;
    vm.isClosed = moment(vm.poll.close).isAfter(new moment());
    vm.categorys = Categorys.query();
    vm.bk_poll = _.clone(poll);
    vm.form = {};
    vm.opts = vm.poll.opts;

    vm.optionToggle = -1;

    $scope.sharedDate = new Date(new Date().setMinutes(0, 0));
    function init() {
      if (vm.poll._id) {
        initSocket();
      }
      analysic_nofif();

      $scope.$watch('vm.poll', function() {
        alert('hey, myVar has changed!');
    });
    }

    init();
    // Init Socket
    function initSocket() {
      if (!Socket.socket) {
        Socket.connect();
      }
      Socket.emit('subscribe_poll', {
        pollId: vm.poll._id,
        userId: vm.authentication.user._id
      });
      Socket.on('poll_delete', res => {
        toast.error('This poll has been deleted.', 'Error!');
        $state.go('polls.list');
      });
      Socket.on('opts_request', res => {
        console.log('Has option request');
        Action.get_poll(vm.poll._id)
          .then(_poll => {
            vm.poll = _poll;
            vm.opts = vm.poll.opts;
            $scope.$apply();
          }, err => {
            toast.error(err.message, 'Error!');
          });
      });
      $scope.$on('$destroy', function () {
        Socket.emit('unsubscribe', {
          pollId: vm.poll._id,
          userId: vm.authentication.user._id
        });
        Socket.removeListener('poll_delete');
        Socket.removeListener('opts_request');
      });
    }

    function analysic_nofif() {
      if (notif) {
        if (notif.status === 0) {
          notif.status = 1;
          notif.$update(() => {
            $rootScope.$emit('changeNotif');
          });
        }
      }
    }
    // function get_opts() {
    //   Action.get_opts(vm.poll._id)
    //     .then(res => {
    //       vm.opts = res.data || [];
    //       $scope.$apply();
    //     })
    //     .catch(err => {
    //       toast.error(err.message, 'Error!');
    //     });
    // }

    // function get_tags() {
    //   Action.get_tags(vm.poll._id)
    //     .then(res => {
    //       angular.forEach(res.data, (polltag, index) => {
    //         vm.poll.tags.push(polltag.tag);
    //       });
    //     })
    //     .catch(err => {
    //       toast.error(err.message, 'Error!');
    //     });
    // }

    function isCanUpdate() {
      return true;
      // const update = moment(vm.poll.updated);
      // const now = moment(new Date());
      // var duration = moment.duration(now.diff(update)).asHours();
      // return duration >= 1;
    }
    // Function
    vm.remove = () => {
      $scope.message_title = 'Delete poll!';
      $scope.message_content = 'Are you sure you want to delete?';
      $scope.dialog_type = 3;
      $scope.buton_label = 'Delete';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_delete();
      }, reject => {
      });
      function handle_delete() {
        vm.poll.$remove(() => {
          Socket.emit('poll_delete', { pollId: vm.poll._id });
          $state.go('polls.list');
        });
      }
    };

    vm.save = () => {
      if (!vm.validateBody() || !vm.validateCategory() || !vm.validateTitle() || !vm.validateCloseDate()) {
        toast.error('You have not entered enough information.', 'Error!');
        return;
      }
      if (!vm.poll.isPublic) {
        $scope.message_title = 'Save poll!';
        $scope.message_content = 'You want to save a private poll?';
        $scope.dialog_type = 1;
        $scope.buton_label = 'Save';
        dialog.openConfirm({
          scope: $scope,
          templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
        }).then(confirm => {
          handle_save();
        }, reject => {
        });
      } else {
        handle_save();
      }
      function handle_save() {
        vm.poll.opts = vm.opts;
        Action.save_poll(vm.poll)
          .then(res => {
            $state.go('polls.view', { pollId: res._id });
          })
          .catch(err => {
            toast.error(err.message, 'Error!');
          });
      }
    };

    vm.validateCategory = () => {
      return (vm.poll.category) ? true : false;
    };
    vm.validateTitle = () => {
      return (vm.poll.title) ? true : false;
    };
    vm.validateBody = () => {
      return (vm.poll.body) ? true : false;
    };
    vm.validateCloseDate = () => {
      if (!vm.poll.close) {
        return true;
      }
      return moment(vm.poll.close).isAfter(new moment());
    };
    vm.discard = () => {
      if (angular.equals(vm.poll, vm.bk_poll)) {
        handle_discard();
      } else {
        $scope.message_title = 'Discard poll!';
        $scope.message_content = 'Are you sure you want to discard?';
        $scope.dialog_type = 2;
        $scope.buton_label = 'Discard';
        dialog.openConfirm({
          scope: $scope,
          templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
        }).then(confirm => {
          handle_discard();
        }, reject => {
        });
      }
    };
    function handle_discard() {
      if (vm.poll._id) {
        $state.go('polls.view', { pollId: vm.poll._id });
      } else {
        $state.go('polls.list');
      }
    }

    // OPTIONS
    vm.tmp_opt = {};
    vm.show_colorpicker = false;
    var opt_aside = $bsAside({
      scope: $scope,
      controllerAs: vm,
      templateUrl: 'modules/polls/client/views/new-opt.client.view.html',
      title: 'Add new option',
      placement: 'bottom',
      animation: 'am-fade-and-slide-bottom',
      show: false
    });
    vm.input_opt = opt => {
      vm.tmp_opt = (!opt) ? { poll: vm.poll._id, title: '', body: '', status: 1 } : opt;
      opt_aside.$promise.then(opt_aside.show);
    };
    vm.remove_opt = opt => {
      $scope.message_title = 'Delete option!';
      $scope.message_content = 'Are you sure you want to delete this option?';
      $scope.dialog_type = 3;
      $scope.buton_label = 'Delete';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_delete();
      }, reject => {
      });
      function handle_delete() {
        vm.opts = _.without(vm.opts, opt);
        if (opt._id) {
          var _opt = new Opts(opt);
          _opt.$remove(() => {
            Socket.emit('opts_update', { pollId: vm.poll._id });
          });
        }
      }
    };
    vm.approve_opt = opt => {
      $scope.message_title = 'Approve option!';
      $scope.message_content = 'Are you sure you want to approve this option?';
      $scope.dialog_type = 1;
      $scope.buton_label = 'Approve';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_approve();
      }, reject => {
      });
      function handle_approve() {
        opt.status = 1;
        var _opt = new Opts(opt);
        _opt.$update(() => {
          Socket.emit('opts_update', { pollId: vm.poll._id });
        });
      }
    };
    vm.reject_opt = opt => {
      $scope.message_title = 'Reject option!';
      $scope.message_content = 'Are you sure you want to reject this option?';
      $scope.dialog_type = 2;
      $scope.buton_label = 'Reject';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_reject();
      }, reject => {
      });
      function handle_reject() {
        opt.status = 3;
        var _opt = new Opts(opt);
        _opt.$update(() => {
        });
      }
    };
    vm.save_opt = isValid => {
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.optForm');
        return false;
      }
      if (!vm.tmp_opt._id && !_.contains(vm.opts, vm.tmp_opt)) {
        vm.opts.push(vm.tmp_opt);
      }
      opt_aside.$promise.then(opt_aside.hide);
    };
  }
})();
<commit_msg>Commited from lenh at Wed, Jul 26, 2017  1:38:46 PM<commit_after>(function () {
  'use strict';
  // Polls controller
  angular
    .module('polls')
    .controller('PollInputController', PollInputController);

  PollInputController.$inject = [
    '$rootScope',
    '$scope',
    '$state',
    '$window',
    'Authentication',
    'pollResolve',
    'notifResolve',
    '$bsModal',
    '$bsAside',
    'OptsService',
    'Socket',
    'CategorysService',
    'toastr',
    'Action',
    'ngDialog'
  ];

  function PollInputController(
    $rootScope,
    $scope,
    $state,
    $window,
    Authentication,
    poll,
    notif,
    $bsModal,
    $bsAside,
    Opts,
    Socket,
    Categorys,
    toast,
    Action,
    dialog
  ) {
    var vm = this;

    vm.authentication = Authentication;
    vm.isLogged = vm.authentication.user ? true : false;
    vm.poll = poll;
    vm.poll.close = vm.poll.close ? moment(vm.poll.close) : vm.poll.close;
    vm.isClosed = moment(vm.poll.close).isAfter(new moment());
    vm.categorys = Categorys.query();
    vm.bk_poll = _.clone(poll);
    vm.form = {};
    vm.opts = vm.poll.opts;

    vm.optionToggle = -1;

    $scope.sharedDate = new Date(new Date().setMinutes(0, 0));
    function init() {
      if (vm.poll._id) {
        initSocket();
      }
      analysic_nofif();
    }

    init();
    // Init Socket
    function initSocket() {
      if (!Socket.socket) {
        Socket.connect();
      }
      Socket.emit('subscribe_poll', {
        pollId: vm.poll._id,
        userId: vm.authentication.user._id
      });
      Socket.on('poll_delete', res => {
        toast.error('This poll has been deleted.', 'Error!');
        $state.go('polls.list');
      });
      Socket.on('opts_request', res => {
        console.log('Has option request');
        Action.get_poll(vm.poll._id)
          .then(_poll => {
            vm.poll = _poll;
            vm.opts = vm.poll.opts;
            $scope.$apply();
          }, err => {
            toast.error(err.message, 'Error!');
          });
      });
      $scope.$on('$destroy', function () {
        Socket.emit('unsubscribe', {
          pollId: vm.poll._id,
          userId: vm.authentication.user._id
        });
        Socket.removeListener('poll_delete');
        Socket.removeListener('opts_request');
      });
    }

    function analysic_nofif() {
      if (notif) {
        if (notif.status === 0) {
          notif.status = 1;
          notif.$update(() => {
            $rootScope.$emit('changeNotif');
          });
        }
      }
    }
    // function get_opts() {
    //   Action.get_opts(vm.poll._id)
    //     .then(res => {
    //       vm.opts = res.data || [];
    //       $scope.$apply();
    //     })
    //     .catch(err => {
    //       toast.error(err.message, 'Error!');
    //     });
    // }

    // function get_tags() {
    //   Action.get_tags(vm.poll._id)
    //     .then(res => {
    //       angular.forEach(res.data, (polltag, index) => {
    //         vm.poll.tags.push(polltag.tag);
    //       });
    //     })
    //     .catch(err => {
    //       toast.error(err.message, 'Error!');
    //     });
    // }

    function isCanUpdate() {
      return true;
      // const update = moment(vm.poll.updated);
      // const now = moment(new Date());
      // var duration = moment.duration(now.diff(update)).asHours();
      // return duration >= 1;
    }
    // Function
    vm.remove = () => {
      $scope.message_title = 'Delete poll!';
      $scope.message_content = 'Are you sure you want to delete?';
      $scope.dialog_type = 3;
      $scope.buton_label = 'Delete';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_delete();
      }, reject => {
      });
      function handle_delete() {
        vm.poll.$remove(() => {
          Socket.emit('poll_delete', { pollId: vm.poll._id });
          $state.go('polls.list');
        });
      }
    };

    vm.save = () => {
      if (!vm.validateBody() || !vm.validateCategory() || !vm.validateTitle() || !vm.validateCloseDate()) {
        toast.error('You have not entered enough information.', 'Error!');
        return;
      }
      if (!vm.poll.isPublic) {
        $scope.message_title = 'Save poll!';
        $scope.message_content = 'You want to save a private poll?';
        $scope.dialog_type = 1;
        $scope.buton_label = 'Save';
        dialog.openConfirm({
          scope: $scope,
          templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
        }).then(confirm => {
          handle_save();
        }, reject => {
        });
      } else {
        handle_save();
      }
      function handle_save() {
        vm.poll.opts = vm.opts;
        Action.save_poll(vm.poll)
          .then(res => {
            $state.go('polls.view', { pollId: res._id });
          })
          .catch(err => {
            toast.error(err.message, 'Error!');
          });
      }
    };

    vm.validateCategory = () => {
      return (vm.poll.category) ? true : false;
    };
    vm.validateTitle = () => {
      return (vm.poll.title) ? true : false;
    };
    vm.validateBody = () => {
      return (vm.poll.body) ? true : false;
    };
    vm.validateCloseDate = () => {
      if (!vm.poll.close) {
        return true;
      }
      return moment(vm.poll.close).isAfter(new moment());
    };
    vm.discard = () => {
      if (angular.equals(vm.poll, vm.bk_poll)) {
        handle_discard();
      } else {
        $scope.message_title = 'Discard poll!';
        $scope.message_content = 'Are you sure you want to discard?';
        $scope.dialog_type = 2;
        $scope.buton_label = 'Discard';
        dialog.openConfirm({
          scope: $scope,
          templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
        }).then(confirm => {
          handle_discard();
        }, reject => {
        });
      }
    };
    function handle_discard() {
      if (vm.poll._id) {
        $state.go('polls.view', { pollId: vm.poll._id });
      } else {
        $state.go('polls.list');
      }
    }

    // OPTIONS
    vm.tmp_opt = {};
    vm.show_colorpicker = false;
    var opt_aside = $bsAside({
      scope: $scope,
      controllerAs: vm,
      templateUrl: 'modules/polls/client/views/new-opt.client.view.html',
      title: 'Add new option',
      placement: 'bottom',
      animation: 'am-fade-and-slide-bottom',
      show: false
    });
    vm.input_opt = opt => {
      vm.tmp_opt = (!opt) ? { poll: vm.poll._id, title: '', body: '', status: 1 } : opt;
      opt_aside.$promise.then(opt_aside.show);
    };
    vm.remove_opt = opt => {
      $scope.message_title = 'Delete option!';
      $scope.message_content = 'Are you sure you want to delete this option?';
      $scope.dialog_type = 3;
      $scope.buton_label = 'Delete';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_delete();
      }, reject => {
      });
      function handle_delete() {
        vm.opts = _.without(vm.opts, opt);
        if (opt._id) {
          var _opt = new Opts(opt);
          _opt.$remove(() => {
            Socket.emit('opts_update', { pollId: vm.poll._id });
          });
        }
      }
    };
    vm.approve_opt = opt => {
      $scope.message_title = 'Approve option!';
      $scope.message_content = 'Are you sure you want to approve this option?';
      $scope.dialog_type = 1;
      $scope.buton_label = 'Approve';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_approve();
      }, reject => {
      });
      function handle_approve() {
        opt.status = 1;
        var _opt = new Opts(opt);
        _opt.$update(() => {
          Socket.emit('opts_update', { pollId: vm.poll._id });
        });
      }
    };
    vm.reject_opt = opt => {
      $scope.message_title = 'Reject option!';
      $scope.message_content = 'Are you sure you want to reject this option?';
      $scope.dialog_type = 2;
      $scope.buton_label = 'Reject';
      dialog.openConfirm({
        scope: $scope,
        templateUrl: 'modules/core/client/views/templates/confirm.dialog.template.html'
      }).then(confirm => {
        handle_reject();
      }, reject => {
      });
      function handle_reject() {
        opt.status = 3;
        var _opt = new Opts(opt);
        _opt.$update(() => {
        });
      }
    };
    vm.save_opt = isValid => {
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.optForm');
        return false;
      }
      if (!vm.tmp_opt._id && !_.contains(vm.opts, vm.tmp_opt)) {
        vm.opts.push(vm.tmp_opt);
      }
      opt_aside.$promise.then(opt_aside.hide);
    };
  }
})();
<|endoftext|>


<commit_before>$.register({
  rule: {
    host: /adv\.li$/,
  },
  ready: function () {
    'use strict';

    $.removeNodes('iframe');
    $.openLink(unsafeWindow._url);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>adv.li<commit_after><|endoftext|>


<commit_before>import * as utils from 'src/utils';
import { registerBidder } from 'src/adapters/bidderFactory';

const BIDDER_CODE = 'pollux';
const PLX_ENDPOINT_URL = '//adn.plxnt.com/prebid/v1';
const PLX_CURRENCY = 'EUR';
const PLX_TTL = 3600;
const PLX_NETREVENUE = true;

export const spec = {
  code: BIDDER_CODE,
  aliases: ['plx'],
  /**
     * Determines whether or not the given bid request is valid.
     *
     * @param {BidRequest} bid The bid params to validate.
     * @return boolean True if this is a valid bid, and false otherwise.
     */
  isBidRequestValid: function(bid) {
    if (!bid.hasOwnProperty('params') || !bid.params.hasOwnProperty('zone')) {
      utils.logError('required param "zone" is missing for == ' + BIDDER_CODE + ' ==');
      return false;
    }
    return true;
  },
  /**
     * Make a server request from the list of BidRequests.
     *
     * @param {validBidRequests[]} - an array of bids
     * @return ServerRequest Info describing the request to the server.
     */
  buildRequests: function (validBidRequests) {
    if (!Array.isArray(validBidRequests) || !validBidRequests.length) {
      return [];
    }
    const payload = [];
    let custom_url = null;
    for (let i = 0; i < validBidRequests.length; i++) {
      const bid = validBidRequests[i];
      const request = {
        bidId: bid.bidId,
        zones: bid.params.zone,
        sizes: bid.sizes
      };
      if (bid.bidderUrl && !custom_url) {
        custom_url = bid.bidderUrl;
      }
      payload.push(request);
    }
    const payloadString = JSON.stringify(payload);
    // build url parameters
    const domain = utils.getParameterByName('domain');
    const tracker2 = utils.getParameterByName('tracker2');
    const url_params = {};
    if (domain) {
      url_params.domain = domain;
    } else {
      url_params.domain = utils.getTopWindowUrl();
    }
    if (tracker2) {
      url_params.tracker2 = tracker2;
    }
    // build url
    let bidder_url = custom_url || PLX_ENDPOINT_URL;
    if (url_params) {
      bidder_url = bidder_url + '?' + utils.parseQueryStringParameters(url_params);
    }
    utils.logMessage('== ' + BIDDER_CODE + ' == request built: ' + bidder_url);
    return {
      method: 'POST',
      url: bidder_url,
      data: payloadString
    };
  },
  /**
     * Unpack the response from the server into a list of bids.
     *
     * @param {*} serverResponse A successful response from the server.
     * @return {Bid[]} An array of bids which were nested inside the server.
     */
  interpretResponse: function(serverResponse, bidRequest) {
    let bidResponses = [];
    if (!serverResponse || typeof serverResponse === 'object' && !serverResponse.hasOwnProperty('body')) {
      utils.logMessage('No prebid response from == ' + BIDDER_CODE + ' == for bid requests:');
      utils.logMessage(bidRequest);
      return bidResponses;
    }
    serverResponse = serverResponse.body;
    if (!Array.isArray(serverResponse) || !serverResponse.length) {
      utils.logMessage('No prebid response from == ' + BIDDER_CODE + ' == for bid requests:');
      utils.logMessage(bidRequest);
      return bidResponses;
    }
    // loop through serverResponses
    for (let b in serverResponse) {
      let bid = serverResponse[b];
      const bidResponse = {
        requestId: bid.bidId, // not request id, it's bid's id
        cpm: parseFloat(bid.cpm),
        width: parseInt(bid.width),
        height: parseInt(bid.height),
        ttl: PLX_TTL,
        creativeId: bid.creativeId,
        netRevenue: PLX_NETREVENUE,
        currency: PLX_CURRENCY
      };
      if (bid.ad_type === 'url') {
        bidResponse.adUrl = bid.ad;
      } else {
        bidResponse.ad = bid.ad;
      }
      if (bid.referrer) {
        bidResponse.referrer = bid.referrer;
      }
      bidResponses.push(bidResponse);
    }
    return bidResponses;
  }
};
registerBidder(spec);
<commit_msg>Fix lint errors on push for commit cc653a<commit_after>import * as utils from 'src/utils';
import { registerBidder } from 'src/adapters/bidderFactory';

const BIDDER_CODE = 'pollux';
const PLX_ENDPOINT_URL = '//adn.plxnt.com/prebid/v1';
const PLX_CURRENCY = 'EUR';
const PLX_TTL = 3600;
const PLX_NETREVENUE = true;

export const spec = {
  code: BIDDER_CODE,
  aliases: ['plx'],
  /**
     * Determines whether or not the given bid request is valid.
     *
     * @param {BidRequest} bid The bid params to validate.
     * @return boolean True if this is a valid bid, and false otherwise.
     */
  isBidRequestValid: function(bid) {
    if (!bid.hasOwnProperty('params') || !bid.params.hasOwnProperty('zone')) {
      utils.logError('required param "zone" is missing for == ' + BIDDER_CODE + ' ==');
      return false;
    }
    return true;
  },
  /**
     * Make a server request from the list of BidRequests.
     *
     * @param {validBidRequests[]} - an array of bids
     * @return ServerRequest Info describing the request to the server.
     */
  buildRequests: function (validBidRequests) {
    if (!Array.isArray(validBidRequests) || !validBidRequests.length) {
      return [];
    }
    const payload = [];
    let custom_url = null;
    for (let i = 0; i < validBidRequests.length; i++) {
      const bid = validBidRequests[i];
      const request = {
        bidId: bid.bidId,
        zones: bid.params.zone,
        sizes: bid.sizes
      };
      if (bid.bidderUrl && !custom_url) {
        custom_url = bid.bidderUrl;
      }
      payload.push(request);
    }
    const payloadString = JSON.stringify(payload);
    // build url parameters
    const domain = utils.getParameterByName('domain');
    const tracker2 = utils.getParameterByName('tracker2');
    const url_params = {};
    if (domain) {
      url_params.domain = domain;
    } else {
      url_params.domain = utils.getTopWindowUrl();
    }
    if (tracker2) {
      url_params.tracker2 = tracker2;
    }
    // build url
    let bidder_url = custom_url || PLX_ENDPOINT_URL;
    if (url_params) {
      bidder_url = bidder_url + '?' + utils.parseQueryStringParameters(url_params);
    }
    utils.logMessage('== ' + BIDDER_CODE + ' == request built: ' + bidder_url);
    return {
      method: 'POST',
      url: bidder_url,
      data: payloadString
    };
  },
  /**
     * Unpack the response from the server into a list of bids.
     *
     * @param {*} serverResponse A successful response from the server.
     * @return {Bid[]} An array of bids which were nested inside the server.
     */
  interpretResponse: function(serverResponse, bidRequest) {
    let bidResponses = [];
    if (!serverResponse || (typeof serverResponse === 'object' && !serverResponse.hasOwnProperty('body'))) {
      utils.logMessage('No prebid response from == ' + BIDDER_CODE + ' == for bid requests:');
      utils.logMessage(bidRequest);
      return bidResponses;
    }
    serverResponse = serverResponse.body;
    if (!Array.isArray(serverResponse) || !serverResponse.length) {
      utils.logMessage('No prebid response from == ' + BIDDER_CODE + ' == for bid requests:');
      utils.logMessage(bidRequest);
      return bidResponses;
    }
    // loop through serverResponses
    for (let b in serverResponse) {
      let bid = serverResponse[b];
      const bidResponse = {
        requestId: bid.bidId, // not request id, it's bid's id
        cpm: parseFloat(bid.cpm),
        width: parseInt(bid.width),
        height: parseInt(bid.height),
        ttl: PLX_TTL,
        creativeId: bid.creativeId,
        netRevenue: PLX_NETREVENUE,
        currency: PLX_CURRENCY
      };
      if (bid.ad_type === 'url') {
        bidResponse.adUrl = bid.ad;
      } else {
        bidResponse.ad = bid.ad;
      }
      if (bid.referrer) {
        bidResponse.referrer = bid.referrer;
      }
      bidResponses.push(bidResponse);
    }
    return bidResponses;
  }
};
registerBidder(spec);
<|endoftext|>


<commit_before>var BatteryTemplateUpdater = (function () {
    'use strict';

    var defaultPercentage = 20.0,
        batteryToggles = ".editable.profile",
        batteries = [
            "congestion_battery",
            "households_flexibility_p2p_electricity"
        ],
        sliderSettings = {
            tooltip: 'hide',
            formatter: function (value) {
                return value + "%";
            }
        };

    function setSlideStopValue() {
        var sliderValue = $(this).val();

        $(this).parents(".editable").find(".tick.value").text(sliderValue + "%");
    }

    BatteryTemplateUpdater.prototype = {
        update: function () {
            var isBattery           = (batteries.indexOf(this.data.type) > -1),
                isCongestionBattery = ("congestion_battery" === this.data.type),
                batterySlider       = this.template.find(".battery-slider"),
                sliderInput         = batterySlider.find("input");

            this.template.find(batteryToggles).toggleClass("hidden", isBattery);

            batterySlider.toggleClass("hidden", !isCongestionBattery);

            if (isCongestionBattery) {
                sliderInput.slider(sliderSettings)
                    .slider('setValue', defaultPercentage)
                    .on('slide', setSlideStopValue)
                    .trigger('slide');

                this.template.set(sliderInput.data('type'), defaultPercentage);
            }

            return this.template;
        }
    };

    function BatteryTemplateUpdater(context) {
        this.data     = context.data;
        this.template = context.template;
    }

    return BatteryTemplateUpdater;
}());
<commit_msg>Fix non-default congestion percentage slider values<commit_after>var BatteryTemplateUpdater = (function () {
    'use strict';

    var defaultPercentage = 20.0,
        batteryToggles = ".editable.profile",
        batteries = [
            "congestion_battery",
            "households_flexibility_p2p_electricity"
        ],
        sliderSettings = {
            tooltip: 'hide',
            formatter: function (value) {
                return value + "%";
            }
        };

    function setSlideStopValue() {
        var sliderValue = $(this).val();

        $(this).parents(".editable").find(".tick.value").text(sliderValue + "%");
    }

    BatteryTemplateUpdater.prototype = {
        update: function () {
            var isBattery           = (batteries.indexOf(this.data.type) > -1),
                isCongestionBattery = ("congestion_battery" === this.data.type),
                batterySlider       = this.template.find(".battery-slider"),
                sliderInput         = batterySlider.find("input"),
                reserveValue;

            this.template.find(batteryToggles).toggleClass("hidden", isBattery);

            batterySlider.toggleClass("hidden", !isCongestionBattery);

            if (isCongestionBattery) {
                if (this.data.hasOwnProperty('congestionReservePercentage')) {
                    reserveValue = parseFloat(
                        this.data.congestionReservePercentage
                    );
                } else {
                    reserveValue = defaultPercentage;
                }

                sliderInput.slider(sliderSettings)
                    .slider('setValue', reserveValue)
                    .on('slide', setSlideStopValue)
                    .trigger('slide');

                this.template.set(sliderInput.data('type'), defaultPercentage);
            }

            return this.template;
        }
    };

    function BatteryTemplateUpdater(context) {
        this.data     = context.data;
        this.template = context.template;
    }

    return BatteryTemplateUpdater;
}());
<|endoftext|>


<commit_before>var argon2 = process.env.ARGON2_COVERAGE
  ? require('./index-cov')
  : require('./index');

module.exports = {
  test_hash: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.equal(hash, "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_argon2d: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/\$argon2d\$/.test(hash), "Should have argon2d signature.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_long_salt: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesaltwaytoobig", function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Salt too long, maximum 16 characters.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_time_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: 4
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/t=4/.test(hash), "Should have correct time cost.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_invalid_time_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid time cost, must be a number.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: 13
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=8192/.test(hash), "Should have correct memory cost.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_invalid_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid memory cost, must be a number.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_high_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: 32
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Memory cost too high, maximum of 32.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_parallelism: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      parallelism: 2
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/p=2/.test(hash), "Should have correct parallelism.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_invalid_parallelism: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      parallelism: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid parallelism, must be a number.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_all_options: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: 4,
      memoryCost: 13,
      parallelism: 2
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=8192,t=4,p=2/.test(hash), "Should have correct options.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_sync: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt");
    assert.equal(hash, "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs");
    assert.done();
  },

  test_hash_argon2d_sync: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      argon2d: true
    });
    assert.ok(/\$argon2d\$/.test(hash), "Should use argon2d signature.");
    assert.done();
  },

  test_hash_sync_time_cost: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      timeCost: 4
    });
    assert.ok(/t=4/.test(hash), "Should have correct time cost.");
    assert.done();
  },

  test_hash_sync_invalid_time_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        timeCost: "foo"
      });
    });
    assert.done();
  },

  test_hash_sync_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      memoryCost: 13
    });
    assert.ok(/m=8192/.test(hash), "Should have correct memory cost.");
    assert.done();
  },

  test_hash_sync_invalid_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        memoryCost: "foo"
      });
    });
    assert.done();
  },

  test_hash_sync_high_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      argon2.encryptSync("password", "somesalt", {
        memoryCost: 32
      });
    });
    assert.done();
  },

  test_hash_sync_parallelism: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      parallelism: 2
    });
    assert.ok(/p=2/.test(hash), "Should have correct parallelism.");
    assert.done();
  },

  test_hash_sync_invalid_parallelism: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        parallelism: "foo"
      });
    });
    assert.done();
  },

  test_hash_sync_all_options: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      timeCost: 4,
      memoryCost: 13,
      parallelism: 2
    });
    assert.ok(/m=8192,t=4,p=2/.test(hash), "Should have correct options.");
    assert.done();
  },

  test_hash_sync_long_salt: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      argon2.encryptSync("password", "somesaltwaytoobig");
    });
    assert.done();
  },

  test_generate_salt: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.generateSalt(function (err, salt) {
      assert.ok(salt.length <= 16);
      assert.done();
    });
  },

  test_generate_salt_sync: function (assert) {
    "use strict";

    assert.expect(1);

    assert.ok(argon2.generateSaltSync().length <= 16);
    assert.done();
  },

  test_verify_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.verify(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "password", function (err) {
        assert.equal(undefined, err);
        assert.done();
      });
  },

  test_verify_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.verify(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "passwolrd", function (err) {
        assert.ok(err, "Error should be defined.");
        assert.done();
      });
  },

  test_verify_argon2d_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      argon2.verify(hash, "password", function (err) {
        assert.equal(undefined, err);
        assert.done();
      });
    });
  },

  test_verify_argon2d_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      argon2.verify(hash, "passwolrd", function (err) {
        assert.ok(err, "Error should be defined.");
        assert.done();
      });
    });
  },

  test_verify_sync_ok: function (assert) {
    "use strict";

    assert.expect(1);

    assert.equal(true, argon2.verifySync(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "password"));
    assert.done();
  },

  test_verify_sync_fail: function (assert) {
    "use strict";

    assert.expect(1);

    assert.equal(false, argon2.verifySync(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "passwolrd"));
    assert.done();
  },

  test_verify_argon2d_sync_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.equal(true, argon2.verifySync(hash, "password"));
      assert.done();
    });
  },

  test_verify_argon2d_sync_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.equal(false, argon2.verifySync(hash, "passwolrd"));
      assert.done();
    });
  }
};
<commit_msg>Test with functions instead of hardcoded hashes<commit_after>var argon2 = process.env.ARGON2_COVERAGE
  ? require('./index-cov')
  : require('./index');

module.exports = {
  test_hash: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.equal(hash, "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_argon2d: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/\$argon2d\$/.test(hash), "Should have argon2d signature.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_long_salt: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesaltwaytoobig", function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Salt too long, maximum 16 characters.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_time_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: 4
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/t=4/.test(hash), "Should have correct time cost.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_invalid_time_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid time cost, must be a number.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: 13
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=8192/.test(hash), "Should have correct memory cost.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_invalid_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid memory cost, must be a number.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_high_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: 32
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Memory cost too high, maximum of 32.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_parallelism: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      parallelism: 2
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/p=2/.test(hash), "Should have correct parallelism.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_invalid_parallelism: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      parallelism: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid parallelism, must be a number.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_all_options: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: 4,
      memoryCost: 13,
      parallelism: 2
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=8192,t=4,p=2/.test(hash), "Should have correct options.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_sync: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt");
    assert.equal(hash, "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs");
    assert.done();
  },

  test_hash_argon2d_sync: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      argon2d: true
    });
    assert.ok(/\$argon2d\$/.test(hash), "Should use argon2d signature.");
    assert.done();
  },

  test_hash_sync_time_cost: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      timeCost: 4
    });
    assert.ok(/t=4/.test(hash), "Should have correct time cost.");
    assert.done();
  },

  test_hash_sync_invalid_time_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        timeCost: "foo"
      });
    });
    assert.done();
  },

  test_hash_sync_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      memoryCost: 13
    });
    assert.ok(/m=8192/.test(hash), "Should have correct memory cost.");
    assert.done();
  },

  test_hash_sync_invalid_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        memoryCost: "foo"
      });
    });
    assert.done();
  },

  test_hash_sync_high_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      argon2.encryptSync("password", "somesalt", {
        memoryCost: 32
      });
    });
    assert.done();
  },

  test_hash_sync_parallelism: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      parallelism: 2
    });
    assert.ok(/p=2/.test(hash), "Should have correct parallelism.");
    assert.done();
  },

  test_hash_sync_invalid_parallelism: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        parallelism: "foo"
      });
    });
    assert.done();
  },

  test_hash_sync_all_options: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      timeCost: 4,
      memoryCost: 13,
      parallelism: 2
    });
    assert.ok(/m=8192,t=4,p=2/.test(hash), "Should have correct options.");
    assert.done();
  },

  test_hash_sync_long_salt: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      argon2.encryptSync("password", "somesaltwaytoobig");
    });
    assert.done();
  },

  test_generate_salt: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.generateSalt(function (err, salt) {
      assert.ok(salt.length <= 16);
      assert.done();
    });
  },

  test_generate_salt_sync: function (assert) {
    "use strict";

    assert.expect(1);

    assert.ok(argon2.generateSaltSync().length <= 16);
    assert.done();
  },

  test_verify_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.verify(argon2.encryptSync("password", argon2.generateSaltSync()),
      "password", function (err) {
        assert.equal(undefined, err);
        assert.done();
      });
  },

  test_verify_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.verify(argon2.encryptSync("password", argon2.generateSaltSync()),
      "passwolrd", function (err) {
        assert.ok(err, "Error should be defined.");
        assert.done();
      });
  },

  test_verify_argon2d_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", argon2.generateSaltSync(), {
      argon2d: true
    }, function (err, hash) {
      argon2.verify(hash, "password", function (err) {
        assert.equal(undefined, err);
        assert.done();
      });
    });
  },

  test_verify_argon2d_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", argon2.generateSaltSync(), {
      argon2d: true
    }, function (err, hash) {
      argon2.verify(hash, "passwolrd", function (err) {
        assert.ok(err, "Error should be defined.");
        assert.done();
      });
    });
  },

  test_verify_sync_ok: function (assert) {
    "use strict";

    assert.expect(1);

    assert.equal(true, argon2.verifySync(argon2.encryptSync("password",
      argon2.generateSaltSync()), "password"));
    assert.done();
  },

  test_verify_sync_fail: function (assert) {
    "use strict";

    assert.expect(1);

    assert.equal(false, argon2.verifySync(argon2.encryptSync("password",
      argon2.generateSaltSync()), "passworld"));
    assert.done();
  },

  test_verify_argon2d_sync_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", argon2.generateSaltSync(), {
      argon2d: true
    }, function (err, hash) {
      assert.equal(true, argon2.verifySync(hash, "password"));
      assert.done();
    });
  },

  test_verify_argon2d_sync_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", argon2.generateSaltSync(), {
      argon2d: true
    }, function (err, hash) {
      assert.equal(false, argon2.verifySync(hash, "passwolrd"));
      assert.done();
    });
  }
};
<|endoftext|>


<commit_before>//Set the RequireJS configuration

require.config({
  baseUrl : "../backbone_client/",

  paths : {
    // "jasmine" : "../tests/libs/jasmine/jasmine",
    // "jasmine-html" : "../tests/libs/jasmine/jasmine-html",
    /* Tests to ensure jasmine is running */
    "Player" : "../tests/libs/jasmine/src/Player",
    "Song" : "../tests/libs/jasmine/src/Song",
    "PlayerSpec" : "../tests/libs/jasmine/spec/PlayerSpec",
    "SpecHelper" : "../tests/libs/jasmine/spec/SpecHelper",

    "sinon" : "../tests/libs/sinon/sinon",

    /* Additional Jasmine runner files for XML and console output */
    "JUnitReporter" : "../tests/libs/jasmine-reporters/src/jasmine.junit_reporter",

    /* load Backbone dependencies */
    "handlebarsjs" : "libs/handlebars.runtime",
    "handlebars" : "libs/compiled_handlebars",
    "$" : "libs/jquery",
    "_" : "libs/underscore",
    "backbonejs" : "libs/backbone",
    "jquery-couch" : "libs/backbone_couchdb/jquery.couch",
    "backbone" : "libs/backbone_couchdb/backbone-couchdb",

    /* load FieldDB dependencies */
    "text" : "libs/text",
    "CryptoJS" : "libs/Crypto_AES",
    "terminal" : "libs/terminal/terminal",
    "xml2json" : "libs/xml2json",
    "oprime" : "libs/OPrime",
    "OPrime" : "libs/webservicesconfig_devserver",
    // Bootstrap kills click events in jquery, so dont include in tests
    // "bootstrap" : "libs/bootstrap/js/bootstrap.min",

    /* load tests for dependencies */
    "jasmine-jquery" : "../tests/libs/backbone/jasmine-jquery",
    "jasmine-ajax" : "../tests/libs/backbone/mock-ajax",
    "jasmine-jquery-spec" : "../tests/libs/backbone/jasmine-jquery-spec",

  },
  shim : {
    // "jasmine-html" : {
    // deps : [ "jasmine" ],
    // exports : "jasmine"
    // },
    // "SpecHelper" : {
    // deps : [ "jasmine-html" ],
    // exports : "jasmine"
    // },

    "PlayerSpec" : {
      deps : [ "SpecHelper", "Player", "Song" ],
      exports : "PlayerSpec"
    },
//     "JUnitReporter" : {
//     deps : [ "jasmine-html" ],
//     exports : "jasmine"
//     },
    // "sinon" : {
    // deps : [ "jasmine-html" ],
    // exports : "sinon"
    // },

    /* Shim Backbone dependencies for use in require statements */
    "jquery-couch" : {
      deps : [ "$" ],
      exports : "$"
    },
    "backbonejs" : {
      deps : [ "_", "$", "OPrime" ],
      exports : "Backbone"
    },
    "handlebarsjs" : {
      deps : [ "backbonejs", "$" ],
      exports : "Handlebars"
    },
    "handlebars" : {
      deps : [ "handlebarsjs" ],
      exports : "Handlebars"
    },
    "backbone" : {
      deps : [ "backbonejs", "jquery-couch" ],
      exports : "Backbone"
    },

    /* Shim FieldDB dependencies for use in require statements */
    "xml2json" : {
      deps : [ "$" ],
      exports : "X2JS"
    },
    "OPrime" : {
      deps : [ "oprime" ],
      exports : "OPrime"
    },
    "terminal" : {
      deps : [ "$" ],
      exports : "Terminal"
    },

    /* Shim jquery test dependencies to get them to load in the right order */
    "jasmine-jquery" : {
      deps : [ "$" ],
      exports : "jasmine"
    },
    "jasmine-ajax" : {
      deps : [ "jasmine-jquery", "$" ],
      exports : "jasmine"
    },
    "jasmine-jquery-spec" : {
      deps : [ "jasmine-ajax" ],
      exports : "jasmine"
    },
  }

});
/*
 * Initialize Jasmine, and run the tests
 */
require([ //"handlebars",
          "OPrime",
/*
 * For some mysterious reason as yet unknown to us, these tests need to run
 * (first), or no FieldDB tests will run
 */
    "PlayerSpec",
    "../tests/libs/backbone/JQueryTest",

    /* FieldDB tests */
	"../tests/app/AppTest",
	"../tests/activity/ActivityTest",
	"../tests/authentication/AuthenticationTest",
    "../tests/comment/CommentTest",
    "../tests/confidentiality_encryption/ConfidentialTest",
    "../tests/corpus/CorpusTest",
    "../tests/export/ExportTest",
    "../tests/glosser/GlosserTest",
    "../tests/hotkey/HotKeyTest",
    "../tests/import/ImportTest",
    "../tests/insert_unicode/InsertUnicodeTest",
    "../tests/lexicon/LexiconTest",
    "../tests/permission/PermissionTest",
    "../tests/search/SearchTest",
    "../tests/datum/SessionTest",
    "../tests/user/UserTest",

    /* Test dependancies, only run these once in a while */
    "../tests/libs/backbone/BackboneModelTest",
    "../tests/libs/backbone/BackboneCouchdbTest",

    /* Test DOM manipulation, only run these (199 tests) once in a while */
    // "jasmine-jquery-spec"
    "JUnitReporter" ], function() {

  OPrime.debugMode = false;

  var jasmineEnv = jasmine.getEnv();
  jasmineEnv.updateInterval = 1000;

  if (/PhantomJS/.test(navigator.userAgent)) {
    jasmineEnv.addReporter(new jasmine.TrivialReporter());
    jasmineEnv.addReporter(new jasmine.JUnitXmlReporter());
  } else {
    var htmlReporter = new jasmine.HtmlReporter();

    jasmineEnv.addReporter(htmlReporter);

    jasmineEnv.specFilter = function(spec) {
      return htmlReporter.specFilter(spec);
    };
  }

  jasmineEnv.execute();

});
<commit_msg>Triggering Jenkins<commit_after>//Set the RequireJS configuration

require.config({
  baseUrl : "../backbone_client/",

  paths : {
    // "jasmine" : "../tests/libs/jasmine/jasmine",
    // "jasmine-html" : "../tests/libs/jasmine/jasmine-html",
    /* Tests to ensure jasmine is running */
    "Player" : "../tests/libs/jasmine/src/Player",
    "Song" : "../tests/libs/jasmine/src/Song",
    "PlayerSpec" : "../tests/libs/jasmine/spec/PlayerSpec",
    "SpecHelper" : "../tests/libs/jasmine/spec/SpecHelper",

    "sinon" : "../tests/libs/sinon/sinon",

    /* Additional Jasmine runner files for XML and console output */
    "JUnitReporter" : "../tests/libs/jasmine-reporters/src/jasmine.junit_reporter",

    /* load Backbone dependencies */
    "handlebarsjs" : "libs/handlebars.runtime",
    "handlebars" : "libs/compiled_handlebars",
    "$" : "libs/jquery",
    "_" : "libs/underscore",
    "backbonejs" : "libs/backbone",
    "jquery-couch" : "libs/backbone_couchdb/jquery.couch",
    "backbone" : "libs/backbone_couchdb/backbone-couchdb",

    /* load FieldDB dependencies */
    "text" : "libs/text",
    "CryptoJS" : "libs/Crypto_AES",
    "terminal" : "libs/terminal/terminal",
    "xml2json" : "libs/xml2json",
    "oprime" : "libs/OPrime",
    "OPrime" : "libs/webservicesconfig_devserver",
    // Bootstrap kills click events in jquery, so dont include in tests
    // "bootstrap" : "libs/bootstrap/js/bootstrap.min",

    /* load tests for dependencies */
    "jasmine-jquery" : "../tests/libs/backbone/jasmine-jquery",
    "jasmine-ajax" : "../tests/libs/backbone/mock-ajax",
    "jasmine-jquery-spec" : "../tests/libs/backbone/jasmine-jquery-spec",

  },
  shim : {
    // "jasmine-html" : {
    // deps : [ "jasmine" ],
    // exports : "jasmine"
    // },
    // "SpecHelper" : {
    // deps : [ "jasmine-html" ],
    // exports : "jasmine"
    // },

    "PlayerSpec" : {
      deps : [ "SpecHelper", "Player", "Song" ],
      exports : "PlayerSpec"
    },
//     "JUnitReporter" : {
//     deps : [ "jasmine-html" ],
//     exports : "jasmine"
//     },
    // "sinon" : {
    // deps : [ "jasmine-html" ],
    // exports : "sinon"
    // },

    /* Shim Backbone dependencies for use in require statements */
    "jquery-couch" : {
      deps : [ "$" ],
      exports : "$"
    },
    "backbonejs" : {
      deps : [ "_", "$", "OPrime" ],
      exports : "Backbone"
    },
    "handlebarsjs" : {
      deps : [ "backbonejs", "$" ],
      exports : "Handlebars"
    },
    "handlebars" : {
      deps : [ "handlebarsjs" ],
      exports : "Handlebars"
    },
    "backbone" : {
      deps : [ "backbonejs", "jquery-couch" ],
      exports : "Backbone"
    },

    /* Shim FieldDB dependencies for use in require statements */
    "xml2json" : {
      deps : [ "$" ],
      exports : "X2JS"
    },
    "OPrime" : {
      deps : [ "oprime" ],
      exports : "OPrime"
    },
    "terminal" : {
      deps : [ "$" ],
      exports : "Terminal"
    },

    /* Shim jquery test dependencies to get them to load in the right order */
    "jasmine-jquery" : {
      deps : [ "$" ],
      exports : "jasmine"
    },
    "jasmine-ajax" : {
      deps : [ "jasmine-jquery", "$" ],
      exports : "jasmine"
    },
    "jasmine-jquery-spec" : {
      deps : [ "jasmine-ajax" ],
      exports : "jasmine"
    },
  }

});
/*
 * Initialize Jasmine, and run the tests
 */
require([ //"handlebars",
          "OPrime",
/*
 * For some mysterious reason as yet unknown to us, these tests need to run
 * (first), or no FieldDB tests will run
 */
    "PlayerSpec",
    "../tests/libs/backbone/JQueryTest",

    /* FieldDB tests */
	"../tests/app/AppTest",
	"../tests/activity/ActivityTest",
	"../tests/authentication/AuthenticationTest",
    "../tests/comment/CommentTest",
    "../tests/confidentiality_encryption/ConfidentialTest",
    "../tests/corpus/CorpusTest",
    "../tests/export/ExportTest",
    "../tests/glosser/GlosserTest",
    "../tests/hotkey/HotKeyTest",
    "../tests/import/ImportTest",
    "../tests/insert_unicode/InsertUnicodeTest",
    "../tests/lexicon/LexiconTest",
    "../tests/permission/PermissionTest",
    "../tests/search/SearchTest",
    "../tests/datum/SessionTest",
    "../tests/user/UserTest",

    /* Test dependancies, only run these once in a while */
    "../tests/libs/backbone/BackboneModelTest",
    "../tests/libs/backbone/BackboneCouchdbTest",

    /* Test DOM manipulation, only run these (199 tests) once in a while */
    "jasmine-jquery-spec",
    "JUnitReporter" ], function() {

  OPrime.debugMode = false;

  var jasmineEnv = jasmine.getEnv();
  jasmineEnv.updateInterval = 1000;

  if (/PhantomJS/.test(navigator.userAgent)) {
    jasmineEnv.addReporter(new jasmine.TrivialReporter());
    jasmineEnv.addReporter(new jasmine.JUnitXmlReporter());
  } else {
    var htmlReporter = new jasmine.HtmlReporter();

    jasmineEnv.addReporter(htmlReporter);

    jasmineEnv.specFilter = function(spec) {
      return htmlReporter.specFilter(spec);
    };
  }

  jasmineEnv.execute();

});
<|endoftext|>


<commit_before>/*  Copyright (C) 2016 Milan Pässler
    Copyright (C) 2016 HopGlass Server contributors

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

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

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

'use strict'

var fs = require('fs')
var _ = require('lodash')

var config = {
  "aliases": {
    "file": "./aliases.json"
  }
}

module.exports = function(configData) {
  _.merge(config, configData)

  var aliases = {}

  try {
    aliases = JSON.parse(fs.readFileSync(config.aliases.file, 'utf8'))
  } catch (err) {
    console.warn("alias file '" + argv.aliases.file + "' doesn't exist, using empty")
  }

  function getRaw() {
    return aliases
  }

  var exports = {}
  exports.getRaw = getRaw
  exports.overwrite = true

  return exports
}
<commit_msg>fix server chi chi chi to those who merged this!<commit_after>/*  Copyright (C) 2016 Milan Pässler
    Copyright (C) 2016 HopGlass Server contributors

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

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

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

'use strict'

var fs = require('fs')
var _ = require('lodash')

var config = {
  "aliases": {
    "file": "./aliases.json"
  }
}

module.exports = function(configData) {
  _.merge(config, configData)

  var aliases = {}

  try {
    aliases = JSON.parse(fs.readFileSync(config.aliases.file, 'utf8'))
  } catch (err) {
    console.warn("alias file '" + config.aliases.file + "' doesn't exist, using empty")
  }

  function getRaw() {
    return aliases
  }

  var exports = {}
  exports.getRaw = getRaw
  exports.overwrite = true

  return exports
}
<|endoftext|>


<commit_before>(function() {
  "use strict";

  // Module properties
  // -----------------
  // caching references
  // existing Skin is kept as oldSkin
  var root    = this
    , oldSkin = root.Skin;

  // key constants, used in data objects as keys
  // these shouldn't conflict with actual data keys
  var INDEX     = '_index'
    , PARENT    = '_parent'
    , BASE      = '_base'
    , ADD       = '_add'
    , REMOVE    = '_remove'
    , OBSERVERS = '_observers';

  // shortcuts
  var Objects   = Object.prototype
    , Functions = Function.prototype
    , Arrays    = Array.prototype
    , slice     = Arrays.slice
    , has       = Objects.hasOwnProperty;

  // helpers
  var isObject = function(object) { return typeof(object) === 'object' }
  var isFunction = function(object) { return typeof(object) === 'function' }
  var isArray = function(object) { return object instanceof Array }

  // Skin class definition
  // ---------------------
  var Skin = root.Skin = function(key, value) {
    // private
    // -------
    var that = this
        // root data object
      , data = {}
        // instance options
      , options = Skin.defaults
        // cached recipes for cooking components
      , cache = {}
        // loader method, should be assigned after parsing the options
      , load = null;

    // initialize
    var initialize = function() {
      // initialize data object
      data[INDEX] = '';
      data[PARENT] = null;
      // parse options
      parse(options, key, value);
      // assign loader function for internal use
      // TODO: this should be done in update(key, value) after parsing options automatically
      load = options.load;
      // create the skin plugin
      if (options.plug && isObject(options.plug)) {
        options.plug[options.alias] = function(type, options) {
          // the plugin context
          // most probably this refers to an array of elements
          // wrapped in a jQuery or Zepto function
        };
      }
    };

    // parse and update options recursively
    // the method captures ('option-a option-b'), ('key', value) and ({key: value}) formats
    // target is the root or a sub branch in options
    // key can be the source object, or the key in key, value pair
    // value only matters when it is present and the key is a string
    var parse = function(target, key, value) {
      if (typeof(key) === 'object') {
        // we have an object, try to match target with it, discard value
        var source = key;
        for (key in source) {
          if (typeof(source[key]) === 'object') {
            // if the value is an Array, just assign it in target
            if (source[key] instanceof Array) target[key] = source[key];
            else {
              // we have an object
              var base, method;
              base = source[key]['base'] || source[key];
                // means the branch is based on other branch
                // this should be passed and set in target
                // first, check for update methods
              if (source[key]['method']) {}
              if (!target.hasOwnProperty(key)) target[key] = {}
              parse(target[key], source[key]);
            }
          }
        }
      } else if (typeof(key) === 'string') {
        if (!value) {
          // parse options string
          // TODO: implement this
        } else {
          target[key] = value;
          // TODO: call observers methods
        }
      }
    }

    // helpers for internal use
    // ------------------------
    // find and return a data object by its index path
    // e.g. var template = get('hint-hidden-template');
    //      var template = get('hint.hidden.template');
    //      var template = get(['hint', 'hidden', 'template']);
    var get = function(key) {
      var pointer = data
        , keys = (isArray(key))? key : key.split(/[.-]/);
      while (keys.length) {
        key = keys.shift();
        if (has.call(pointer, key)) pointer = pointer[key];
        else return;
      }
      return pointer;
    }
    // set data object
    // e.g. set('hint-hidden-template', newTemplate);
    //      set('hint.hidden.template', newTemplate);
    //      set(['hint', 'hidden', 'template'], newTemplate);
    var set = function(key, value) {
      var pointer = data
        , keys = (isArray(key))? key : key.split(/[.-]/)
        , index = [];
      while (keys.length) {
        key = keys.shift();
        index.push(key);
        if (keys.length) {
          // there are still deeper levels
          // existing or non existing keys should point to next level object
          if (!has.call(pointer, key) || isArray(pointer[key])) {
            // we should check if existing key points to an array
            // if so, pretend it doesn't exist and create a new object
            // otherwise the next level object can be pushed in the existing array
            pointer[key] = {};
            pointer[key][INDEX] = index.slice(0);
            pointer[key][PARENT] = pointer;
          }
          pointer = pointer[key];
        } else {
          // no more levels, last key
          pointer[key] = value;
        }
      }
      // return the modified object
      return pointer;
    }
    // chain of responsibility, ask delegates to perform something if they can
    var can = function(object, action) { return has.call(object, action) && isFunction(object[action]) }
    var ask = function(action) {
      if (can(this, action)) return this[action].apply(this, slice.call(arguments, 1));
      else for(var count in options.delegates) {
        var delegate = options.delegates[count];
        if (can(delegate, action)) return delegate[action].apply(this, slice.call(arguments, 1));
      }
      return false;
    }

    // execute initialize
    initialize();

    // public interface
    // ----------------
    return {
      // capture ('option'), ('key', value) and ({key: value}) formats
      configure: function(key, value) {
        if (value && typeof(key) === 'string') set(key, value);
      }
    };
  };

  // Skin static properties
  // ----------------------
  Skin.VERSION = '0.0.0';
  Skin.defaults = {
    // plugin name, unique id prefix etc.
    alias: 'skin'
    // include the scanner or not
    // scanner will parse HTML,
    // detects Skin related data and
    // wires up events to states and actions
  , scan: true
    // include the sensor or not
    // sensor will detect browsers supported events
    // and hooks them into more complex ones
  , sense: true
    // array of delegates
    // if a method implementation is not found in skin object
    // it will try to call the delegate's equivalent method
    // if the delegate failed, it will try the next delegate in array
    // most of required actions can be delegated to external libraries
    // such as jQuery, Zepto, Backbone, Underscore etc.
    // we could also load a custom module which extends the skin object
    // with custom method implementations such as
    // extend(), select(), bind(), addClass(), removeClass(), each(), map() etc.
  , delegates: [root.$, root._]
    // the object which should hold the skin plugin
    // plugin name will be same as alias of skin instance
    // null means no plugin creation
  , plug: root.$.fn
    // default method to load modules
    // based on define(), proposed by CommonJS
    // for Asynchronous Module Definition (AMD)
  , load: root.require || root.curl
    // default paths for modules
  , pack: {
      baseUrl: './'
    // TODO: this won't be needed, I kept it only for documentation
    // , paths: {
    //     'plug': 'plug.js'
    //   , 'parse': 'parse.js'
    //   , 'sense': 'sense.js'
    //   }
    }
  };

  // Skin static methods
  // -------------------
  // assign cached Skin back and return this object
  // should be at the beginning of other codes
  // e.g. var NewSkin = Skin.noConflict();
  //      var newSkin = new NewSkin({alias: 'newSkin'});
  //      var Skin    = { someOtherObject: 'should be defined after Skin.noConflict()' }
  Skin.noConflict = function() {
    root.Skin = oldSkin;
    return this;
  };

  // View class definition
  // ---------------------
  Skin.View = function(key, value) {
    Skin.View.counter++;
    // private
    // -------
    uniqueId = options.alias + '-' + Skin.View.counter;
    // reuseClass
    //
    // $owner
    // $element
    // $target
    //
    // data:
    // template:
    // map: {}
    //
    // options: {
    //
    // }
    //
    // create:
    // initialize:
    // configure:
    // refresh:
    // finalize:
    //
    // show:
    // hide:
    // enable:
    // disable:
    // activate:
    // inactivate:
    // expose:
    // silent:
    // state: function(state) {}

    // public
    return {

    };
  };

  // View static properties
  // ----------------------
  Skin.View.counter = 0;
  Skin.View.defaults = {
    // plugin name, unique id prefix etc.
    alias: 'view'
  };

}).call(this);<commit_msg>data objects can be based on each other<commit_after>(function() {
  "use strict";

  // Module properties
  // -----------------
  // caching references
  // existing Skin is kept as oldSkin
  var root    = this
    , oldSkin = root.Skin;

  // key constants, used in data objects as keys
  // these shouldn't conflict with actual data keys
  var INDEX     = '_index'
    , PARENT    = '_parent'
    , BASE      = '_base'
    , ADD       = '_add'
    , REMOVE    = '_remove'
    , OBSERVERS = '_observers';

  // shortcuts
  var Objects   = Object.prototype
    , Functions = Function.prototype
    , Arrays    = Array.prototype
    , slice     = Arrays.slice
    , has       = Objects.hasOwnProperty;

  // helpers
  function isObject(object)   { return typeof(object) === 'object' }
  function isFunction(object) { return typeof(object) === 'function' }
  function isString(object)   { return typeof(object) === 'string' }
  function isArray(object)    { return object instanceof Array }
  function isWindow(object)   { return object != null && object == object.window }
  function isDocument(object) { return object != null && object.nodeType == object.DOCUMENT_NODE }
  function isData(object)     { return isObject(object) && !isArray(object) }

  // Skin class definition
  // ---------------------
  var Skin = root.Skin = function(key, value) {
    // private
    // -------
    var that = this
        // cached data object
      , cache = {}
        // loader method, should be assigned after parsing the options
      , load = null;

    // initialize
    function initialize() {
      // instance options
      data('options', { base: Skin.defaults });
      // cached recipes for cooking components
      data('recipes', {});
      // parse options
      //parse(options, key, value);
      // assign loader function for internal use
      // TODO: this should be done in update(key, value) after parsing options automatically
      //load = options.load;
      // create the skin plugin
      //if (options.plug && isObject(options.plug)) {
      //  options.plug[options.alias] = function(type, options) {
          // the plugin context
          // most probably this refers to an array of elements
          // wrapped in a jQuery or Zepto function
      //  };
      //}
    };

    // parse and update data recursively
    // the method captures ('option-a option-b data-c'), ('key', value) and
    // nested ({key: value, otherKey: { someOtherKey: someOtherValue }}) formats
    // target is the target data object, such as cache, recipes, options
    // key can be the source object, or the key of ('key', value) pair
    // value only matters when it is present and key is a string
    function parse(target, key, value) {
      if (isObject(key)) {
        // we have an object, try to match target with it, discard value
        var source = key;
        for (key in source) {
          if (isObject(source[key])) {
            // if the value is an Array, just assign it in target
            if (isArray(source[key])) target[key] = source[key];
            else {
              // we have an object
              var base, method;
              base = source[key][BASE] || source[key];
                // means the branch is based on other branch
                // this should be passed and set in target
                // first, check for update methods
              if (source[key]['method']) {}
              if (!target.hasOwnProperty(key)) target[key] = {}
              parse(target[key], source[key]);
            }
          }
        }
      } else if (typeof(key) === 'string') {
        if (!value) {
          // parse options string
          // TODO: implement this
        } else {
          target[key] = value;
          // TODO: call observers methods
        }
      }
    }

    // helpers for internal use
    // ------------------------
    // get or set a data object by its index path
    // index path can be an array, or string sliced by . or -
    function data(key, value) {
      var pointer = cache
        , keys = (isArray(key))? key : key.split(/[.-]/)
        , index = [];
      while (keys.length) {
        key = keys.shift();
        if (arguments.length == 2) {
          // set value, create, update or delete (set null)
          index.push(key);
          if (keys.length) {
            // there are still deeper levels
            // existing or non existing keys should point to next level object
            if (!has.call(pointer, key) || !isData(pointer[key])) {
              // we should check if existing key points to an array
              // if so, pretend it doesn't exist and create a new object
              // otherwise the next level object can be pushed in the existing array
              pointer[key] = { index: index.slice(0), parent: pointer };
            }
            pointer = pointer[key];
          } else {
            // no more levels, last key
            pointer[key] = value;
            if (isData(value)) {
              // if last value is a data object, set index and parent for it
              value.index = index.slice(0);
              value.parent = pointer;
            }
            pointer = pointer[key];
          }
        } else {
          // get value, read
          if (has.call(pointer, key)) pointer = pointer[key];
          else {
            // check for value in base(s), go back deep!
            while (isData(pointer.base)) {
              pointer = pointer.base;
              if (has.call(pointer, key)) {
                pointer = pointer[key];
                break;
              }
            }
          }
        }
      }
      return pointer;
    }
    function bind(key, type, action) {

    }
    function unbind(key, type, action) {

    }
    // chain of responsibility, ask delegates to perform something if they can
    function can(object, action) { return has.call(object, action) && isFunction(object[action]) }
    function ask(action) {
      if (can(this, action)) return this[action].apply(this, slice.call(arguments, 1));
      else for(var count in options.delegates) {
        var delegate = options.delegates[count];
        if (delegate && can(delegate, action)) return delegate[action].apply(this, slice.call(arguments, 1));
      }
      return false;
    }

    // execute initialize
    initialize();

    // public interface
    // ----------------
    return {
      // capture ('option'), ('key', value) and ({key: value}) formats
      configure: function(key, value) {
        if (value && typeof(key) === 'string') set(key, value);
      }
    };
  };

  // Skin static properties
  // ----------------------
  Skin.VERSION = '0.0.0';
  Skin.defaults = {
    // plugin name, unique id prefix etc.
    alias: 'skin'
    // include the scanner or not
    // scanner will parse HTML,
    // detects Skin related data and
    // wires up events to states and actions
  , scan: true
    // include the sensor or not
    // sensor will detect browsers supported events
    // and hooks them into more complex ones
  , sense: true
    // array of delegates
    // if a method implementation is not found in skin object
    // it will try to call the delegate's equivalent method
    // if the delegate failed, it will try the next delegate in array
    // most of required actions can be delegated to external libraries
    // such as jQuery, Zepto, Backbone, Underscore etc.
    // we could also load a custom module which extends the skin object
    // with custom method implementations such as
    // extend(), select(), bind(), addClass(), removeClass(), each(), map() etc.
  , delegates: [root.$, root._]
    // the object which should hold the skin plugin
    // plugin name will be same as alias of skin instance
    // null means no plugin creation
  , plug: root.$.fn
    // default method to load modules
    // based on define(), proposed by CommonJS
    // for Asynchronous Module Definition (AMD)
  , load: root.require || root.curl
    // default paths for modules
  , pack: {
      baseUrl: './'
    // TODO: this won't be needed, I kept it only for documentation
    // , paths: {
    //     'plug': 'plug.js'
    //   , 'parse': 'parse.js'
    //   , 'sense': 'sense.js'
    //   }
    }
  };

  // Skin static methods
  // -------------------
  // assign cached Skin back and return this object
  // should be at the beginning of other codes
  // e.g. var NewSkin = Skin.noConflict();
  //      var newSkin = new NewSkin({alias: 'newSkin'});
  //      var Skin    = { someOtherObject: 'should be defined after Skin.noConflict()' }
  Skin.noConflict = function() {
    root.Skin = oldSkin;
    return this;
  };

  // View class definition
  // ---------------------
  Skin.View = function(key, value) {
    Skin.View.counter++;
    // private
    // -------
    uniqueId = options.alias + '-' + Skin.View.counter;
    // reuseClass
    //
    // $owner
    // $element
    // $target
    //
    // data:
    // template:
    // map: {}
    //
    // options: {
    //
    // }
    //
    // create:
    // initialize:
    // configure:
    // refresh:
    // finalize:
    //
    // show:
    // hide:
    // enable:
    // disable:
    // activate:
    // inactivate:
    // expose:
    // silent:
    // state: function(state) {}

    // public
    return {

    };
  };

  // View static properties
  // ----------------------
  Skin.View.counter = 0;
  Skin.View.defaults = {
    // plugin name, unique id prefix etc.
    alias: 'view'
  };

}).call(this);<|endoftext|>


<commit_before>angular.module('angularSpinners')
  .directive('spinner', function () {
    return {
      restrict: 'EA',
      replace: true,
      transclude: true,
      scope: {
        name: '@?',
        group: '@?',
        show: '=?',
        imgSrc: '@?',
        register: '@?',
        onLoaded: '&?',
        onShow: '&?',
        onHide: '&?'
      },
      template: [
        '',
        '  ',
        '  ',
        ''
      ].join(''),
      controller: function ($scope, spinnerService) {

        // register should be true by default if not specified.
        if (!$scope.hasOwnProperty('register')) {
          $scope.register = true;
        }

        // Declare a mini-API to hand off to our service so the service
        // doesn't have a direct reference to this directive's scope.
        var api = {
          name: $scope.name,
          group: $scope.group,
          show: function () {
            $scope.show = true;
          },
          hide: function () {
            $scope.show = false;
          },
          toggle: function () {
            $scope.show = !$scope.show;
          }
        };

        // Register this spinner with the spinner service.
        if ($scope.register == true) {
          spinnerService._register(api);
        }

        // If an onShow or onHide expression was provided, register a watcher
        // that will fire the relevant expression when show's value changes.
        if ($scope.onShow || $scope.onHide) {
          $scope.$watch('show', function (show) {
            if (show && $scope.onShow) {
              $scope.onShow({ spinnerService: spinnerService, spinnerApi: api });
            } else if (!show && $scope.onHide) {
              $scope.onHide({ spinnerService: spinnerService, spinnerApi: api });
            }
          });
        }

        // This spinner is good to go. Fire the onLoaded expression.
        if ($scope.onLoaded) {
          $scope.onLoaded({ spinnerService: spinnerService, spinnerApi: api });
        }
      }
    };
  });
<commit_msg>Added explicit type conversion for the register property.<commit_after>angular.module('angularSpinners')
  .directive('spinner', function () {
    return {
      restrict: 'EA',
      replace: true,
      transclude: true,
      scope: {
        name: '@?',
        group: '@?',
        show: '=?',
        imgSrc: '@?',
        register: '@?',
        onLoaded: '&?',
        onShow: '&?',
        onHide: '&?'
      },
      template: [
        '',
        '  ',
        '  ',
        ''
      ].join(''),
      controller: function ($scope, spinnerService) {

        // register should be true by default if not specified.
        if (!$scope.hasOwnProperty('register')) {
          $scope.register = true;
        } else {
          $scope.register = !!$scope.register;
        }

        // Declare a mini-API to hand off to our service so the service
        // doesn't have a direct reference to this directive's scope.
        var api = {
          name: $scope.name,
          group: $scope.group,
          show: function () {
            $scope.show = true;
          },
          hide: function () {
            $scope.show = false;
          },
          toggle: function () {
            $scope.show = !$scope.show;
          }
        };

        // Register this spinner with the spinner service.
        if ($scope.register === true) {
          spinnerService._register(api);
        }

        // If an onShow or onHide expression was provided, register a watcher
        // that will fire the relevant expression when show's value changes.
        if ($scope.onShow || $scope.onHide) {
          $scope.$watch('show', function (show) {
            if (show && $scope.onShow) {
              $scope.onShow({ spinnerService: spinnerService, spinnerApi: api });
            } else if (!show && $scope.onHide) {
              $scope.onHide({ spinnerService: spinnerService, spinnerApi: api });
            }
          });
        }

        // This spinner is good to go. Fire the onLoaded expression.
        if ($scope.onLoaded) {
          $scope.onLoaded({ spinnerService: spinnerService, spinnerApi: api });
        }
      }
    };
  });
<|endoftext|>