<commit_before>fs = require('fs');

var d;
d = fs.readFileSync('tmp/log.txt', 'utf8');

var authorRegexp = /([^<]+)<([^>]+)>/;
var gitLogHeaders = {
  'Author': function(currentCommmit, author) {
    var capture = authorRegexp.exec(author);
    if (capture) {
      currentCommmit.authorName = capture[1].trim();
      currentCommmit.authorEmail = capture[2].trim();
    } else {
      currentCommmit.authorName = author;
    }
  },
  'Commit': function(currentCommmit, author) {
    var capture = authorRegexp.exec(author);
    if (capture) {
      currentCommmit.committerName = capture[1].trim();
      currentCommmit.committerEmail = capture[2].trim();
    } else {
      currentCommmit.committerName = author;
    }
  },
  'AuthorDate': function(currentCommmit, date) {
    currentCommmit.authorDate = date;
  },
  'CommitDate': function(currentCommmit, date) {
    currentCommmit.commitDate = date;
  },
  'Reflog': function(currentCommmit, data) {
    currentCommmit.reflogName = data.substring(0, data.indexOf(' '));
    var author = data.substring(data.indexOf(' ') + 2, data.length - 1);
    var capture = authorRegexp.exec(author);
    if (capture) {
      currentCommmit.reflogAuthorName = capture[1].trim();
      currentCommmit.reflogAuthorEmail = capture[2].trim();
    } else {
      currentCommmit.reflogAuthorName = author;
    }
  },
};

parseGitLog = function(data) {
    var commits = [];
    var currentCommmit;
    var parseCommitLine = function(row) {
        if (!row.trim()) return;
        currentCommmit = { refs: [], fileLineDiffs: [] };
        var ss = row.split('(');
        var sha1s = ss[0].split(' ').slice(1).filter(function(sha1) { return sha1 && sha1.length; });
        currentCommmit.sha1 = sha1s[0];
        currentCommmit.parents = sha1s.slice(1);
        if (ss[1]) {
            var refs = ss[1].slice(0, ss[1].length - 1);
            currentCommmit.refs = refs.split(', ');
        }
        commits.push(currentCommmit);
        parser = parseHeaderLine;
    }
    var parseHeaderLine = function(row) {
        if (row.trim() == '') {
            parser = parseCommitMessage;
        } else {
            for (var key in gitLogHeaders) {
                if (row.indexOf(key + ': ') == 0) {
                    gitLogHeaders[key](currentCommmit, row.slice((key + ': ').length).trim());
                return;
            }
        }
        }
    }
    var parseCommitMessage = function(row, index) {
        if (/[\d-]+\t[\d-]+\t.+/g.test(rows[index + 1])) {
            parser = parseFileChanges;
            return;
        }
        if (rows[index + 1] && rows[index + 1].indexOf('commit ') == 0) {
            parser = parseCommitLine;
            return;
        }
        if (currentCommmit.message) currentCommmit.message += '\n';
        else currentCommmit.message = '';
        currentCommmit.message += row.trim();
    }
    var parseFileChanges = function(row, index) {
        if (rows.length === index + 1 || rows[index + 1] && rows[index + 1].indexOf('commit ') === 0) {
            var total = [0, 0, 'Total'];
            for (var n = 0; n < currentCommmit.fileLineDiffs.length; n++) {
                var fileLineDiff = currentCommmit.fileLineDiffs[n];
                if (!isNaN(parseInt(fileLineDiff[0], 10))) {
                    total[0] += fileLineDiff[0] = parseInt(fileLineDiff[0], 10);
                }
                if (!isNaN(parseInt(fileLineDiff[1], 10))) {
                    total[1] += fileLineDiff[1] = parseInt(fileLineDiff[1], 10);
                }
            }
            currentCommmit.fileLineDiffs.splice(0,0, total);
            parser = parseCommitLine;
            return;
        }
        currentCommmit.fileLineDiffs.push(row.split('\t'));
    }
    var parser = parseCommitLine;
    var rows = data.split('\n');
    rows.forEach(function(row, index) {
        parser(row, index);
    });

    commits.forEach(function(commit) { commit.message = (typeof commit.message) === 'string' ? commit.message.trim() : ''; });
    return commits;
};

parseGitLog(d);
<commit_msg>export logparser as module<commit_after>var authorRegexp = /([^<]+)<([^>]+)>/;
var gitLogHeaders = {
  'Author': function(currentCommmit, author) {
    var capture = authorRegexp.exec(author);
    if (capture) {
      currentCommmit.authorName = capture[1].trim();
      currentCommmit.authorEmail = capture[2].trim();
    } else {
      currentCommmit.authorName = author;
    }
  },
  'Commit': function(currentCommmit, author) {
    var capture = authorRegexp.exec(author);
    if (capture) {
      currentCommmit.committerName = capture[1].trim();
      currentCommmit.committerEmail = capture[2].trim();
    } else {
      currentCommmit.committerName = author;
    }
  },
  'AuthorDate': function(currentCommmit, date) {
    currentCommmit.authorDate = date;
  },
  'CommitDate': function(currentCommmit, date) {
    currentCommmit.commitDate = date;
  },
  'Reflog': function(currentCommmit, data) {
    currentCommmit.reflogName = data.substring(0, data.indexOf(' '));
    var author = data.substring(data.indexOf(' ') + 2, data.length - 1);
    var capture = authorRegexp.exec(author);
    if (capture) {
      currentCommmit.reflogAuthorName = capture[1].trim();
      currentCommmit.reflogAuthorEmail = capture[2].trim();
    } else {
      currentCommmit.reflogAuthorName = author;
    }
  },
};

parseGitLog = function(data) {
    var commits = [];
    var currentCommmit;
    var parseCommitLine = function(row) {
        if (!row.trim()) return;
        currentCommmit = { refs: [], fileLineDiffs: [] };
        var ss = row.split('(');
        var sha1s = ss[0].split(' ').slice(1).filter(function(sha1) { return sha1 && sha1.length; });
        currentCommmit.sha1 = sha1s[0];
        currentCommmit.parents = sha1s.slice(1);
        if (ss[1]) {
            var refs = ss[1].slice(0, ss[1].length - 1);
            currentCommmit.refs = refs.split(', ');
        }
        commits.push(currentCommmit);
        parser = parseHeaderLine;
    }
    var parseHeaderLine = function(row) {
        if (row.trim() == '') {
            parser = parseCommitMessage;
        } else {
            for (var key in gitLogHeaders) {
                if (row.indexOf(key + ': ') == 0) {
                    gitLogHeaders[key](currentCommmit, row.slice((key + ': ').length).trim());
                return;
            }
        }
        }
    }
    var parseCommitMessage = function(row, index) {
        if (/[\d-]+\t[\d-]+\t.+/g.test(rows[index + 1])) {
            parser = parseFileChanges;
            return;
        }
        if (rows[index + 1] && rows[index + 1].indexOf('commit ') == 0) {
            parser = parseCommitLine;
            return;
        }
        if (currentCommmit.message) currentCommmit.message += '\n';
        else currentCommmit.message = '';
        currentCommmit.message += row.trim();
    }
    var parseFileChanges = function(row, index) {
        if (rows.length === index + 1 || rows[index + 1] && rows[index + 1].indexOf('commit ') === 0) {
            var total = [0, 0, 'Total'];
            for (var n = 0; n < currentCommmit.fileLineDiffs.length; n++) {
                var fileLineDiff = currentCommmit.fileLineDiffs[n];
                if (!isNaN(parseInt(fileLineDiff[0], 10))) {
                    total[0] += fileLineDiff[0] = parseInt(fileLineDiff[0], 10);
                }
                if (!isNaN(parseInt(fileLineDiff[1], 10))) {
                    total[1] += fileLineDiff[1] = parseInt(fileLineDiff[1], 10);
                }
            }
            currentCommmit.fileLineDiffs.splice(0,0, total);
            parser = parseCommitLine;
            return;
        }
        currentCommmit.fileLineDiffs.push(row.split('\t'));
    }
    var parser = parseCommitLine;
    var rows = data.split('\n');
    rows.forEach(function(row, index) {
        parser(row, index);
    });

    commits.forEach(function(commit) { commit.message = (typeof commit.message) === 'string' ? commit.message.trim() : ''; });
    return commits;
};

module.exports = parseGitLog;
<|endoftext|>


<commit_before>import Ember from 'ember';

export function initialize(appInstance) {
  const meta = appInstance.lookup('service:meta');
  meta.reopen({
    title: function (value) {
      return value + ' - Ship Shape';
    }
  });
}

export default {
  after: 'meta',
  name: 'after-meta',
  initialize
};
<commit_msg>Fix ESLint<commit_after>export function initialize(appInstance) {
  const meta = appInstance.lookup('service:meta');
  meta.reopen({
    title: function (value) {
      return value + ' - Ship Shape';
    }
  });
}

export default {
  after: 'meta',
  name: 'after-meta',
  initialize
};
<|endoftext|>


<commit_before>angular.module("omniControllers")
	.controller("DExSaleController", ["$scope", "PropertyManager", "Account", "Transaction", "MIN_MINER_FEE", "OMNI_PROTOCOL_COST", "ModalManager",
		function DExSaleController($scope,PropertyManager,Account,Transaction,MIN_MINER_FEE,PROTOCOL_FEE,ModalManager ){

			$scope.editTransactionCost = function(){
				$scope.modalManager.openTransactionCostModal($scope, function(){return;});
			}

			$scope.feeType = 'normal';
			$scope.protocolFee = PROTOCOL_FEE;
			$scope.setAddress = function(address){
				$scope.selectedAddress = address;
				$scope.setAsset($scope.wallet.getAsset($scope.selectedAddress.assets[0].id));
				$scope.selectedAddress.estimateFee().then(function(result){
					$scope.feeData=result;
					if($scope.feeType != 'custom'){
						$scope.minersFee = new Big(result.class_c[$scope.feeType]);
					}
				});
			};

			$scope.setAsset = function(asset){
				$scope.sellingAsset = asset;
				let nextEco = (asset.id < 2147483648 && asset.id != 2) ? 1 : 2;
				if($scope.ecosystem != nextEco){
					$scope.ecosystem = nextEco;
					$scope.loadCurrencies();
				}
			}

			$scope.setDesiredAsset = function(asset){
				$scope.desiredAsset = asset;
			}

			$scope.loadCurrencies = function(){
				PropertyManager.listByEcosystem($scope.ecosystem).then(function(result){
			      $scope.availableTokens = result.data.properties.sort(function(a, b) {
			          var currencyA = a.name.toUpperCase();
			          var currencyB = b.name.toUpperCase();
			          return (currencyA < currencyB) ? -1 : (currencyA > currencyB) ? 1 : 0;
			      });
			      $scope.desiredAsset = $scope.availableTokens[0];
			  	});
			}

			$scope.validateDexSaleForm = function(){
				// TODO: Validations
				var fee = Account.settings.minerFee || $scope.minersFee;
				var dexOffer = new Transaction(25,$scope.selectedAddress,fee,{
						transaction_version:0,
						propertyidforsale:$scope.sellingAsset.id,
						amountforsale: new Big($scope.sellingAmount).valueOf(),
						propertiddesired:$scope.desiredAsset.propertyid,
						amountdesired: new Big($scope.desiredAmount).valueOf()
					});
				let redirectUrl = "/dex/overview";
				ModalManager.openConfirmationModal({
					dataTemplate: '/views/modals/partials/dex_offer.html',
					scope: {
						title:"Confirm DEx Transaction",
						address:$scope.selectedAddress,
						saleCurrency:$scope.sellingAsset.id,
						saleAmount:$scope.sellingAmount,
						desiredCurrency:$scope.desiredAsset.propertyid,
						desiredAmount:$scope.desiredAmount,
						totalCost:dexOffer.totalCost,
						confirmText: "Create Transaction",
						successMessage: "Your order was placed successfully",
						successRedirect:redirectUrl
					},
					transaction:dexOffer
				});

			};

			$scope.setAddress($scope.wallet.omniTradableAddresses()[0])
			$scope.showtesteco = $scope.account.getSetting('showtesteco');
		}])
<commit_msg>remove use of new js let<commit_after>angular.module("omniControllers")
	.controller("DExSaleController", ["$scope", "PropertyManager", "Account", "Transaction", "MIN_MINER_FEE", "OMNI_PROTOCOL_COST", "ModalManager",
		function DExSaleController($scope,PropertyManager,Account,Transaction,MIN_MINER_FEE,PROTOCOL_FEE,ModalManager ){

			$scope.editTransactionCost = function(){
				$scope.modalManager.openTransactionCostModal($scope, function(){return;});
			}

			$scope.feeType = 'normal';
			$scope.protocolFee = PROTOCOL_FEE;
			$scope.setAddress = function(address){
				$scope.selectedAddress = address;
				$scope.setAsset($scope.wallet.getAsset($scope.selectedAddress.assets[0].id));
				$scope.selectedAddress.estimateFee().then(function(result){
					$scope.feeData=result;
					if($scope.feeType != 'custom'){
						$scope.minersFee = new Big(result.class_c[$scope.feeType]);
					}
				});
			};

			$scope.setAsset = function(asset){
				$scope.sellingAsset = asset;
				nextEco = (asset.id < 2147483648 && asset.id != 2) ? 1 : 2;
				if($scope.ecosystem != nextEco){
					$scope.ecosystem = nextEco;
					$scope.loadCurrencies();
				}
			}

			$scope.setDesiredAsset = function(asset){
				$scope.desiredAsset = asset;
			}

			$scope.loadCurrencies = function(){
				PropertyManager.listByEcosystem($scope.ecosystem).then(function(result){
			      $scope.availableTokens = result.data.properties.sort(function(a, b) {
			          var currencyA = a.name.toUpperCase();
			          var currencyB = b.name.toUpperCase();
			          return (currencyA < currencyB) ? -1 : (currencyA > currencyB) ? 1 : 0;
			      });
			      $scope.desiredAsset = $scope.availableTokens[0];
			  	});
			}

			$scope.validateDexSaleForm = function(){
				// TODO: Validations
				var fee = Account.settings.minerFee || $scope.minersFee;
				var dexOffer = new Transaction(25,$scope.selectedAddress,fee,{
						transaction_version:0,
						propertyidforsale:$scope.sellingAsset.id,
						amountforsale: new Big($scope.sellingAmount).valueOf(),
						propertiddesired:$scope.desiredAsset.propertyid,
						amountdesired: new Big($scope.desiredAmount).valueOf()
					});
				redirectUrl = "/dex/overview";
				ModalManager.openConfirmationModal({
					dataTemplate: '/views/modals/partials/dex_offer.html',
					scope: {
						title:"Confirm DEx Transaction",
						address:$scope.selectedAddress,
						saleCurrency:$scope.sellingAsset.id,
						saleAmount:$scope.sellingAmount,
						desiredCurrency:$scope.desiredAsset.propertyid,
						desiredAmount:$scope.desiredAmount,
						totalCost:dexOffer.totalCost,
						confirmText: "Create Transaction",
						successMessage: "Your order was placed successfully",
						successRedirect:redirectUrl
					},
					transaction:dexOffer
				});

			};

			$scope.setAddress($scope.wallet.omniTradableAddresses()[0])
			$scope.showtesteco = $scope.account.getSetting('showtesteco');
		}])
<|endoftext|>


<commit_before>(function () {
    var cogClass = function () {};
    cogClass.prototype.exec = function (params, request, response) {
        var oops = this.utils.apiError;
        var sys = this.sys;
        var getRandomKey = this.sys.getRandomKey;
        var classID = params.classid;
        var getClassMemberships = this.utils.getClassMemberships;
        var stmt = sys.db.prepare('INSERT INTO memberships VALUES(NULL,?,?,?,NULL);');
        for (var i=0,ilen=params.addmembers.length;i<ilen;i+=1) {
            var addmemberID = params.addmembers[i];
            var addmemberKey = getRandomKey(8,36);
            stmt.bind(classID,addmemberID,addmemberKey);
            stmt.run();
            stmt.reset();
        }
        stmt.finalize(function(){
            getClassMemberships(params,request,response);
        });
    }
    exports.cogClass = cogClass;
})();

<commit_msg>Rationalize code in addmembers<commit_after>(function () {
    var cogClass = function () {};
    cogClass.prototype.exec = function (params, request, response) {
        var oops = this.utils.apiError;
        var sys = this.sys;
        var getRandomKey = this.sys.getRandomKey;
        var classID = params.classid;
        var getClassMemberships = this.utils.getClassMemberships;

        sys.db.run('BEGIN TRANSACTION',function(err){
            if (err){return oops(response,err,'class/addmembers(1)')};
            addMembers(0,params.addmembers.length);
        });

        function addMembers(pos,limit) {
            if (pos === limit) {
                endTransaction();
            }
            var sql = 'INSERT INTO memberships VALUES(NULL,?,?,?,NULL);';
            var addmemberID = params.addmembers[pos];
            var addmemberKey = getRandomKey(8,36);
            sys.db.run(sql,[classID,addmemberID,addmemberKey],function(err){
                if (err){return oops(response,err,'class/addmembers(2)')};
                addMembers(pos+1,limit);
            });
        };

        function endTransaction() {
            sys.db.run('END TRANSACTION',function(err){
                if (err){return oops(response,err,'class/addmembers(3)')};
                getClassMemberships(params,request,response);
            });
        };
    }
    exports.cogClass = cogClass;
})();

<|endoftext|>


<commit_before>/**
 @module Math
 @namespace Math
 */
var TW = TW || {};

(function(TW) {

    TW.Math = TW.Math ||  {};
    TW.Math.Vector2D = Vector2D;

    if (typeof window.define === "function" && window.define.amd) {
        define([], function() {
            return Vector2D;
        });
    }

    /**
     The Vector2D class allow you to create a vector2D object

     @class Vector2D
     @param {Number} x the x coordinate of the Vector2D
     @param {Number} y the y coordinate of the Vector2D
     @constructor
     */
    function Vector2D(x, y) {
        /**
         x coordinate
         @property {Number} x
         */
        this.x = x;
        /**
         y coordinate
         @property {Number} y
         */
        this.y = y;
    }

    /**
     * The add method allow you to add two vectors and return the sum of them.
     *
     * @method add
     * @param {Vector2D} vector the Vector2D to add with the current Vector2D object.
     * @return {Vector2D} return the sum of the two Vector2D
     */
    Vector2D.prototype.add = function(vector) {
        return new Vector2D(this.x + vector.x, this.y + vector.y);
    };

    /**
     * The sub method allow you to sub two vectors and return the subtraction of them.
     *
     * @method sub
     * @param {Vector2D} vector the Vector2D to subtract to the current Vector2D object.
     * @return {Vector2D} returns the subtraction of this and vector object.
     */
    Vector2D.prototype.sub = function(vector) {
        return new Vector2D(this.x - vector.x, this.y - vector.y);
    };

    /**
     The mult method allow you to mult the current Vector2D by a scalar and return the result.

     @method mult
     @param {float} scalar the scalar who multiply the current Vector2D
     @return {Vector2D} returns the current Vector2D multiplied by scalar.
     */
    Vector2D.prototype.mult = function(scalar) {
        return new Vector2D(this.x * scalar, this.y * scalar);
    };

    /**
     The div method allow you to div the current Vector2D by a scalar and return the result

     @method div
     @param scalar
     @return {Vector2D} returns the current Vector2D divided by scalar
     */
    Vector2D.prototype.div = function(scalar) {
        return new Vector2D(this.x / scalar, this.y / scalar);
    };

    /**
     get the x coordinate of the current Vector2D

     @method getX
     @return {float} returns the x coordinate of the Vector2D
     @deprecated use directly Vector2D.x
     */
    Vector2D.prototype.getX = function() {
        return this.x;
    };

    /**
     get the y coordinate of the current Vector2D

     @method getY
     @return {float} returns the y coordinate of the Vector2D
     @deprecated use directly Vector2D.y
     */
    Vector2D.prototype.getY = function() {
        return this.y;
    };

    /**
     set the x coordinate of the current Vector2D

     @method setX
     @param {float} x the x coordinate of the Vector2D
     @deprecated use directly Vector2D.x
     */
    Vector2D.prototype.setX = function(x) {
        this.x = x;
    };

    /**
     set the y coordinate of the Vector2D
     @method setY
     @param {float} y the y coordinate of the Vector2D
     @deprecated use directly Vector2D.y
     */
    Vector2D.prototype.setY = function(y) {
        this.y = y;
    };

    /**
     normalize the current Vector2D

     @method normalize
     */
    Vector2D.prototype.normalize = function() {
        var length = Math.sqrt((this.x * this.x) + (this.y * this.y));
        this.x /= length;
        this.y /= length;
    };

    /**
     get the length of the Vector2D

     @method getLength
     @return {Number} returns the length of the Vector2D.
     */
    Vector2D.prototype.getLength = function() {
        return Math.sqrt((this.x * this.x) + (this.y * this.y));
    };

    /**
     set the length of the current Vector2D

     @method setLength
     @param {Number} length the length to apply to the current Vector2D
     */
    Vector2D.prototype.setLength = function(length) {
        this.normalize();
        this.x *= length;
        this.y *= length;
    };

    /**
     * get the angle of the current Vector2D
     *
     * @method getAngle
     * @return {Number} returns the angle of the current Vector2D (expressed in degree).
     */
    Vector2D.prototype.getAngle = function() {
        if (this.x === 0) {
            if (this.y > 0) {
                return 90;
            }
            if (this.y < 0) {
                return -90;
            }
            if (this.y === 0) {
                return 0;
            }
        }
        return Math.atan(this.y / this.x) * 180.0 / Math.PI;
    };

    /**
     set the angle of the current Vector2D

     @method setAngle
     @param {Number} angle the angle to apply to the current Vector2D (angle is expressed in degree)
     */
    Vector2D.prototype.setAngle = function(angle) {
        var length = this.getLength();
        this.x = Math.cos(angle / 180.0 * Math.PI) * length;
        this.y = Math.sin(angle / 180.0 * Math.PI) * length;
    };

    /**
     compute the dot product of the current Vector2D

     @method dotProduct
     @param {Vector2D} vector2 the second vector to compute the dot product
     @return {Number} returns the dot product between the current Vector2D and vector2.
     */
    Vector2D.prototype.dotProduct = function(vector2) {
        return ((this.x * vector2.x) + (this.y * vector2.y));
    };

    /**
     compute the angle between the current Vector2D and vector2

     @method getAngleBetween
     @param {Vector2D} vector2 the second vector to compute the angle between.
     @return {Number} returns the angle between the current Vector2D and vector2 (expressed in degree).
     */
    Vector2D.prototype.getAngleBetween = function(vector2) {
        var dot_prod = this.dotProduct(vector2);
        var length_v1 = this.getLength();
        var length_v2 = vector2.getLength();
        var cos = dot_prod / (length_v1 * length_v2);
        return Math.acos(cos) * 180.0 / Math.PI;
    };

    /**
     compute the cross product of the current Vector2D and vector2

     @method cross product
     @param {Vector2D} vector2 the second vector to use to compute the cross product
     @return {Number} returns the cross product between the current Vector2D and vector2
     */
    Vector2D.prototype.crossProduct = function(vector2) {
        return ((this.x * vector2.y) - (this.y * vector2.x));
    };

    /**
     * get the det of the current Vector2D and vector
     *
     * @method getDet
     * @param {Vector2D} vector the second Vector2D to use to compute the det of the two vectors
     * @return {Number} returns the det of the current Vector2D and vector,
     *  if the return value > 0 then vector is at left of this, if the return value is < 0 then vector is at right
     *  of this, if the return value is equal to 0 then vector is on this.
     */
    Vector2D.prototype.getDet = function(vector) {
        return this.crossProduct(vector);
    };

    /**
     popup the values of the Vector2D through an alert box.

     @method dump
     @deprecated use `window.alert(vector);` instead
     */
    Vector2D.prototype.dump = function() {
        window.alert(this);
    };

    /**
     give a data representation of Vector2D

     @method toString
     @return {String} data representation of Vector2D
     */
    Vector2D.prototype.toString = function() {
        return "[x=" + this.x + "; y=" + this.y + "]";
    };

}(TW));
<commit_msg>Fixed bug about Vector2D.getAngle, now the right angle is returned (there was a bug about atan which only returns an angle beetween -90 and 90)<commit_after>/**
 @module Math
 @namespace Math
 */
var TW = TW || {};

(function(TW) {

    TW.Math = TW.Math ||  {};
    TW.Math.Vector2D = Vector2D;

    if (typeof window.define === "function" && window.define.amd) {
        define([], function() {
            return Vector2D;
        });
    }

    /**
     The Vector2D class allow you to create a vector2D object

     @class Vector2D
     @param {Number} x the x coordinate of the Vector2D
     @param {Number} y the y coordinate of the Vector2D
     @constructor
     */
    function Vector2D(x, y) {
        /**
         x coordinate
         @property {Number} x
         */
        this.x = x;
        /**
         y coordinate
         @property {Number} y
         */
        this.y = y;
    }

    /**
     * The add method allow you to add two vectors and return the sum of them.
     *
     * @method add
     * @param {Vector2D} vector the Vector2D to add with the current Vector2D object.
     * @return {Vector2D} return the sum of the two Vector2D
     */
    Vector2D.prototype.add = function(vector) {
        return new Vector2D(this.x + vector.x, this.y + vector.y);
    };

    /**
     * The sub method allow you to sub two vectors and return the subtraction of them.
     *
     * @method sub
     * @param {Vector2D} vector the Vector2D to subtract to the current Vector2D object.
     * @return {Vector2D} returns the subtraction of this and vector object.
     */
    Vector2D.prototype.sub = function(vector) {
        return new Vector2D(this.x - vector.x, this.y - vector.y);
    };

    /**
     The mult method allow you to mult the current Vector2D by a scalar and return the result.

     @method mult
     @param {float} scalar the scalar who multiply the current Vector2D
     @return {Vector2D} returns the current Vector2D multiplied by scalar.
     */
    Vector2D.prototype.mult = function(scalar) {
        return new Vector2D(this.x * scalar, this.y * scalar);
    };

    /**
     The div method allow you to div the current Vector2D by a scalar and return the result

     @method div
     @param scalar
     @return {Vector2D} returns the current Vector2D divided by scalar
     */
    Vector2D.prototype.div = function(scalar) {
        return new Vector2D(this.x / scalar, this.y / scalar);
    };

    /**
     get the x coordinate of the current Vector2D

     @method getX
     @return {float} returns the x coordinate of the Vector2D
     @deprecated use directly Vector2D.x
     */
    Vector2D.prototype.getX = function() {
        return this.x;
    };

    /**
     get the y coordinate of the current Vector2D

     @method getY
     @return {float} returns the y coordinate of the Vector2D
     @deprecated use directly Vector2D.y
     */
    Vector2D.prototype.getY = function() {
        return this.y;
    };

    /**
     set the x coordinate of the current Vector2D

     @method setX
     @param {float} x the x coordinate of the Vector2D
     @deprecated use directly Vector2D.x
     */
    Vector2D.prototype.setX = function(x) {
        this.x = x;
    };

    /**
     set the y coordinate of the Vector2D
     @method setY
     @param {float} y the y coordinate of the Vector2D
     @deprecated use directly Vector2D.y
     */
    Vector2D.prototype.setY = function(y) {
        this.y = y;
    };

    /**
     normalize the current Vector2D

     @method normalize
     */
    Vector2D.prototype.normalize = function() {
        var length = Math.sqrt((this.x * this.x) + (this.y * this.y));
        this.x /= length;
        this.y /= length;
    };

    /**
     get the length of the Vector2D

     @method getLength
     @return {Number} returns the length of the Vector2D.
     */
    Vector2D.prototype.getLength = function() {
        return Math.sqrt((this.x * this.x) + (this.y * this.y));
    };

    /**
     set the length of the current Vector2D

     @method setLength
     @param {Number} length the length to apply to the current Vector2D
     */
    Vector2D.prototype.setLength = function(length) {
        this.normalize();
        this.x *= length;
        this.y *= length;
    };

    /**
     * get the angle of the current Vector2D
     *
     * @method getAngle
     * @return {Number} returns the angle of the current Vector2D (expressed in degree).
     */
    Vector2D.prototype.getAngle = function() {
        if (this.x === 0) {
            if (this.y > 0) {
                return 90;
            }
            if (this.y < 0) {
                return -90;
            }
            if (this.y === 0) {
                return 0;
            }
        }
	    var temp_x = this.x / this.getLength();
	    var temp_y = this.y / this.getLength();
	    return Math.atan(temp_y / temp_x) * 180.0 / Math.PI + ( temp_x < 0 ? 180 : 0);
    };

    /**
     set the angle of the current Vector2D

     @method setAngle
     @param {Number} angle the angle to apply to the current Vector2D (angle is expressed in degree)
     */
    Vector2D.prototype.setAngle = function(angle) {
        var length = this.getLength();
        this.x = Math.cos(angle / 180.0 * Math.PI) * length;
        this.y = Math.sin(angle / 180.0 * Math.PI) * length;
    };

    /**
     compute the dot product of the current Vector2D

     @method dotProduct
     @param {Vector2D} vector2 the second vector to compute the dot product
     @return {Number} returns the dot product between the current Vector2D and vector2.
     */
    Vector2D.prototype.dotProduct = function(vector2) {
        return ((this.x * vector2.x) + (this.y * vector2.y));
    };

    /**
     compute the angle between the current Vector2D and vector2

     @method getAngleBetween
     @param {Vector2D} vector2 the second vector to compute the angle between.
     @return {Number} returns the angle between the current Vector2D and vector2 (expressed in degree).
     */
    Vector2D.prototype.getAngleBetween = function(vector2) {
        var dot_prod = this.dotProduct(vector2);
        var length_v1 = this.getLength();
        var length_v2 = vector2.getLength();
        var cos = dot_prod / (length_v1 * length_v2);
        return Math.acos(cos) * 180.0 / Math.PI;
    };

    /**
     compute the cross product of the current Vector2D and vector2

     @method cross product
     @param {Vector2D} vector2 the second vector to use to compute the cross product
     @return {Number} returns the cross product between the current Vector2D and vector2
     */
    Vector2D.prototype.crossProduct = function(vector2) {
        return ((this.x * vector2.y) - (this.y * vector2.x));
    };

    /**
     * get the det of the current Vector2D and vector
     *
     * @method getDet
     * @param {Vector2D} vector the second Vector2D to use to compute the det of the two vectors
     * @return {Number} returns the det of the current Vector2D and vector,
     *  if the return value > 0 then vector is at left of this, if the return value is < 0 then vector is at right
     *  of this, if the return value is equal to 0 then vector is on this.
     */
    Vector2D.prototype.getDet = function(vector) {
        return this.crossProduct(vector);
    };

    /**
     popup the values of the Vector2D through an alert box.

     @method dump
     @deprecated use `window.alert(vector);` instead
     */
    Vector2D.prototype.dump = function() {
        window.alert(this);
    };

    /**
     give a data representation of Vector2D

     @method toString
     @return {String} data representation of Vector2D
     */
    Vector2D.prototype.toString = function() {
        return "[x=" + this.x + "; y=" + this.y + "]";
    };

}(TW));
<|endoftext|>


<commit_before>define([

  ],

function () {
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com

Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/

/*
 * Generate a random uuid.
 *
 * USAGE: Math.uuid(length, radix)
 *   length - the desired number of characters
 *   radix  - the number of allowable values for each character.
 *
 * EXAMPLES:
 *   // No arguments  - returns RFC4122, version 4 ID
 *   >>> Math.uuid()
 *   "92329D39-6F5C-4520-ABFC-AAB64544E172"
 *
 *   // One argument - returns ID of the specified length
 *   >>> Math.uuid(15)     // 15 character ID (default base=62)
 *   "VcydxgltxrVZSTV"
 *
 *   // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
 *   >>> Math.uuid(8, 2)  // 8 character ID (base=2)
 *   "01001010"
 *   >>> Math.uuid(8, 10) // 8 character ID (base=10)
 *   "47473046"
 *   >>> Math.uuid(8, 16) // 8 character ID (base=16)
 *   "098F4D35"
 */
  // Private array of chars to use
  var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

  var GUID = {};

  GUID.uuid = function (len, radix) {
    var chars = CHARS, uuid = [], i;
    radix = radix || chars.length;

    if (len) {
      // Compact form
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      // rfc4122, version 4 form
      var r;

      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return uuid.join('');
  };

  // A more performant, but slightly bulkier, RFC4122v4 solution.  We boost performance
  // by minimizing calls to random()
  GUID.uuidFast = function() {
    var chars = CHARS, uuid = new Array(36), rnd=0, r;
    for (var i = 0; i < 36; i++) {
      if (i==8 || i==13 ||  i==18 || i==23) {
        uuid[i] = '-';
      } else if (i==14) {
        uuid[i] = '4';
      } else {
        if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
        r = rnd & 0xf;
        rnd = rnd >> 4;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
    return uuid.join('');
  };

  // A more compact, but less performant, RFC4122v4 solution:
  GUID.uuidCompact = function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    });
  };

  return GUID;
});<commit_msg>added '{}'s to uuid string<commit_after>define([

  ],

function () {
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com

Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/

/*
 * Generate a random uuid.
 *
 * USAGE: Math.uuid(length, radix)
 *   length - the desired number of characters
 *   radix  - the number of allowable values for each character.
 *
 * EXAMPLES:
 *   // No arguments  - returns RFC4122, version 4 ID
 *   >>> Math.uuid()
 *   "92329D39-6F5C-4520-ABFC-AAB64544E172"
 *
 *   // One argument - returns ID of the specified length
 *   >>> Math.uuid(15)     // 15 character ID (default base=62)
 *   "VcydxgltxrVZSTV"
 *
 *   // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
 *   >>> Math.uuid(8, 2)  // 8 character ID (base=2)
 *   "01001010"
 *   >>> Math.uuid(8, 10) // 8 character ID (base=10)
 *   "47473046"
 *   >>> Math.uuid(8, 16) // 8 character ID (base=16)
 *   "098F4D35"
 */
  // Private array of chars to use
  var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

  var GUID = {};

  GUID.uuid = function (len, radix) {
    var chars = CHARS, uuid = [], i;
    radix = radix || chars.length;

    if (len) {
      // Compact form
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      // rfc4122, version 4 form
      var r;

      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return '{' + uuid.join('') + '}';
  };

  // A more performant, but slightly bulkier, RFC4122v4 solution.  We boost performance
  // by minimizing calls to random()
  GUID.uuidFast = function() {
    var chars = CHARS, uuid = new Array(36), rnd=0, r;
    for (var i = 0; i < 36; i++) {
      if (i==8 || i==13 ||  i==18 || i==23) {
        uuid[i] = '-';
      } else if (i==14) {
        uuid[i] = '4';
      } else {
        if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
        r = rnd & 0xf;
        rnd = rnd >> 4;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
    return uuid.join('');
  };

  // A more compact, but less performant, RFC4122v4 solution:
  GUID.uuidCompact = function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    });
  };

  return GUID;
});<|endoftext|>


<commit_before>var SettingsController = function () {
};

SettingsController.prototype = {
    initialize: function () {
        App.showBackButton();
        App.trackView("Settings");

        SettingsController.initCollectionsSection();
        SettingsController.initAlphabeticalOrderFilter();
        SettingsController.initCategorySection();
        SettingsController.initFeedsSection();
        SettingsController.initListeners();
    },
    destroy: function () {
        App.hideBackButton();
        PageLoad.ajxHandle = null;
    }
};

SettingsController.getCollectionDomain = function (key){
    return App.collection[key][1];
};

SettingsController.initCollectionsSection = function () {
    var $collectionSection = $("#collection-section");
    $collectionSection.html("");

    var first = '
' +
                    '' +
                    'TODAS' +
                '
';

    $collectionSection.append(first);

    SettingsController.refreshSelectAll();

    $.each( App.collection, function( key, value ) {
        var imgString;
        if(App.collectionsSelected.indexOf(value[1])> -1){
            imgString =  'img/category/checked.png';
        }else{
            imgString = 'img/category/unchecked.png';
        }
        $collectionSection.append(
            '
' +
                '' +
                ''+value[0]+'' +
            '
'
        );
    });

};

SettingsController.initAlphabeticalOrderFilter = function () {
    var alphaASC = new Array();
    for (var i = 0; i < 256; i++) {
        alphaASC.push(0);
    }
    var magazines = DataMapping.getAllMagazines();
    for (var id in magazines) {
        var magazine = magazines[id];
        var charMag = magazine.magazine_name.charCodeAt(0);
        alphaASC[charMag] = 1;
    }
    for (var i = 0; i < alphaASC.length; i++) {
        if (alphaASC[i+1] === 1) {
            $("#letter-" + String.fromCharCode(i+1)).show();
        }
    }
};

SettingsController.checkAlfabeticSection = function () {
    var leters = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").split("");

    $.each( leters, function( key, letter ) {

        var magazinesByLetter = [];
        var allMagazines = DataMapping.getMagazinesOrder();
        var startCapture = false;
        for(var i in allMagazines){
            var magazineId = allMagazines[i];
            if(DataMapping.getMagazineName(magazineId).charAt(0) === letter){
                startCapture = true;
                magazinesByLetter.push(magazineId);
            }else if(startCapture){
                break;
            }
        }

        var letterInColection  = false;

        $.each( magazinesByLetter, function( key, value ) {
            if( App.collectionsSelected.indexOf( DataMapping.getMagazineDomain(value)) > -1 ){
                letterInColection = true;
            }
        });

        if(letterInColection){
            $("#letter-"+letter).show();
        }else{
             $("#letter-"+letter).hide();
        }

    });

};

SettingsController.initCategorySection = function () {
    var $categorySection = $("#category-section");
    $categorySection.html("");

    // opcao de mostrar todas revistas
    $categorySection.append('
' +
            '' + Localization.getValue("all") + '	' +
            '	' +
            '
');

    var allCategories = DataMapping.getCategoriesOrder();
    for (var i in allCategories) {
        var cat = parseInt(allCategories[i]);

        var magazines = DataMapping.getAllMagazinesIds(cat);
        var categoriaInColection  = false;

        $.each( magazines, function( key, value ) {
            if( App.collectionsSelected.indexOf( DataMapping.getMagazineDomain(value)) > -1 ){
                categoriaInColection = true;
            }
        });

        if(categoriaInColection){
            var html = '
' +
                    '' + DataMapping.getCategoryName(cat) + '	' +
                    '	' +
                    '
';

            $categorySection.append(html);
        }
    }
};

SettingsController.initFeedsSection = function () {
    var $myListsSection = $("#feeds-section");
    $myListsSection.html("");

    var allFeeds = App.currentUser.getFeeds();
    for (var i in allFeeds) {
        var feed = allFeeds[i];

        var html = '
' +
                '	' +
                '' + feed.feed_name + '	' +
                '	' +
                '
';

        $myListsSection.append(html);
    }
};

SettingsController.initListeners = function () {
    $("#collection-container").on('tap', ".collection-checkbox", SettingsController.collectionCheckbox);
    $("#collection-container").on('tap', "#select-all", SettingsController.selectAll);
    $("#collection-container").on('tap', ".collection-checkbox", SettingsController.initCategorySection);
    $("#collection-container").on('tap', "#select-all", SettingsController.initCategorySection);
    $("#collection-container").on('tap', ".collection-checkbox", SettingsController.checkAlfabeticSection);
    $("#collection-container").on('tap', "#select-all", SettingsController.checkAlfabeticSection);
    $("#settings").on("tap", "#btn-search-magazines", SettingsController.filterSearch);
    $("#settings").on("tap", ".settings-letter", SettingsController.filterLetter);
    $("#settings").on("tap", ".settings-category", SettingsController.filterCategory);
    $("#settings").on("tap", ".settings-feed", SettingsController.filterFeed);
};

SettingsController.selectAll = function(){
    var $obj = $(this);

    if ($obj.attr("src") === "img/category/unchecked.png") {
        $obj.attr("src", "img/category/checked.png");
        App.collectionsSelected = App.collectionsSelected.concat(App.collectionsRemoved);
        for(var i in App.collectionsRemoved){
            var collectionKey = App.collectionsRemoved[i];
            $(document.getElementById("cb-img-"+collectionKey)).attr("src", "img/category/checked.png");
        }
        App.collectionsRemoved = [];
    } else {
        $obj.attr("src", "img/category/unchecked.png");
        App.collectionsRemoved = App.collectionsRemoved.concat(App.collectionsSelected);
        for(var i in App.collectionsSelected){
            var collectionKey = App.collectionsSelected[i];
            $(document.getElementById("cb-img-"+collectionKey)).attr("src", "img/category/unchecked.png");
        }
        App.collectionsSelected = [];
    }
};

SettingsController.collectionCheckbox = function(){
    var collectionKey = $(this).data("collection");
    var $obj = $(this);

    if ($obj.attr("src") === "img/category/unchecked.png") {
        $obj.attr("src", "img/category/checked.png");
        App.collectionsSelected.push(collectionKey);
        var index = App.collectionsRemoved.indexOf(collectionKey);
        if (index > -1) {
            App.collectionsRemoved.splice(index, 1);
        }
        SettingsController.refreshSelectAll();
    } else {
        $obj.attr("src", "img/category/unchecked.png");
        App.collectionsRemoved.push(collectionKey);
        var index = App.collectionsSelected.indexOf(collectionKey);
        if (index > -1) {
            App.collectionsSelected.splice(index, 1);
        }
        SettingsController.refreshSelectAll();
    }
};

SettingsController.refreshSelectAll = function(){
    if(App.collectionsSelected.length < 1){
        $("#select-all").attr("src", "img/category/unchecked.png");
    }else if(App.collectionsRemoved.length < 1){
        $("#select-all").attr("src", "img/category/checked.png");
    }else{
        $("#select-all").attr("src", "img/category/checkbox-partial.png");
    }
};

SettingsController.filterSearch = function () {
    App.showLoadingScreen();
    FeedConfigController.selectedType = FeedConfigController.type.SEARCH;
    var searchQuery = $("#search-input").val();

    $.when(
            SciELO.searchMagazines(searchQuery)
            ).then(
            function (data) {
                // It worked
                FeedConfigController.filterData = {query: searchQuery, results: data};
                Navigator.loadPage("feedConfig.html");
                App.hideLoadingScreen();
            },
            function () {
                //TODO: add msg error
                App.hideLoadingScreen();
            }
    );
};

SettingsController.filterLetter = function () {
    FeedConfigController.selectedType = FeedConfigController.type.LETTER;
    FeedConfigController.filterData = $(this).html();
    Navigator.loadPage("feedConfig.html");
};

SettingsController.filterCategory = function () {
    FeedConfigController.selectedType = FeedConfigController.type.CATEGORY;
    FeedConfigController.filterData = $(this).data("categoryid");
    Navigator.loadPage("feedConfig.html");
};

SettingsController.filterFeed = function () {
    FeedConfigController.selectedType = FeedConfigController.type.FEED_EDIT;
    FeedConfigController.filterData = $(this).data("feedid");
    Navigator.loadPage("feedConfig.html");
};<commit_msg>correção<commit_after>var SettingsController = function () {
};

SettingsController.prototype = {
    initialize: function () {
        App.showBackButton();
        App.trackView("Settings");

        SettingsController.initCollectionsSection();
        SettingsController.initAlphabeticalOrderFilter();
        SettingsController.initCategorySection();
        SettingsController.initFeedsSection();
        SettingsController.initListeners();
    },
    destroy: function () {
        App.hideBackButton();
        PageLoad.ajxHandle = null;
    }
};

SettingsController.getCollectionDomain = function (key){
    return App.collection[key][1];
};

SettingsController.initCollectionsSection = function () {
    var $collectionSection = $("#collection-section");
    $collectionSection.html("");

    var first = '
' +
                    '' +
                    'TODAS' +
                '
';

    $collectionSection.append(first);

    SettingsController.refreshSelectAll();

    $.each( App.collection, function( key, value ) {
        var imgString;
        if(App.collectionsSelected.indexOf(value[1])> -1){
            imgString =  'img/category/checked.png';
        }else{
            imgString = 'img/category/unchecked.png';
        }
        $collectionSection.append(
            '
' +
                '' +
                ''+JSON.parse('"' + value[0].replace(/\"/g, '\\"') + '"')+'' +
            '
'
        );
    });

};

SettingsController.initAlphabeticalOrderFilter = function () {
    var alphaASC = new Array();
    for (var i = 0; i < 256; i++) {
        alphaASC.push(0);
    }
    var magazines = DataMapping.getAllMagazines();
    for (var id in magazines) {
        var magazine = magazines[id];
        var charMag = magazine.magazine_name.charCodeAt(0);
        alphaASC[charMag] = 1;
    }
    for (var i = 0; i < alphaASC.length; i++) {
        if (alphaASC[i+1] === 1) {
            $("#letter-" + String.fromCharCode(i+1)).show();
        }
    }
};

SettingsController.checkAlfabeticSection = function () {
    var leters = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").split("");

    $.each( leters, function( key, letter ) {

        var magazinesByLetter = [];
        var allMagazines = DataMapping.getMagazinesOrder();
        var startCapture = false;
        for(var i in allMagazines){
            var magazineId = allMagazines[i];
            if(DataMapping.getMagazineName(magazineId).charAt(0) === letter){
                startCapture = true;
                magazinesByLetter.push(magazineId);
            }else if(startCapture){
                break;
            }
        }

        var letterInColection  = false;

        $.each( magazinesByLetter, function( key, value ) {
            if( App.collectionsSelected.indexOf( DataMapping.getMagazineDomain(value)) > -1 ){
                letterInColection = true;
            }
        });

        if(letterInColection){
            $("#letter-"+letter).show();
        }else{
             $("#letter-"+letter).hide();
        }

    });

};

SettingsController.initCategorySection = function () {
    var $categorySection = $("#category-section");
    $categorySection.html("");

    // opcao de mostrar todas revistas
    $categorySection.append('
' +
            '' + Localization.getValue("all") + '	' +
            '	' +
            '
');

    var allCategories = DataMapping.getCategoriesOrder();
    for (var i in allCategories) {
        var cat = parseInt(allCategories[i]);

        var magazines = DataMapping.getAllMagazinesIds(cat);
        var categoriaInColection  = false;

        $.each( magazines, function( key, value ) {
            if( App.collectionsSelected.indexOf( DataMapping.getMagazineDomain(value)) > -1 ){
                categoriaInColection = true;
            }
        });

        if(categoriaInColection){
            var html = '
' +
                    '' + DataMapping.getCategoryName(cat) + '	' +
                    '	' +
                    '
';

            $categorySection.append(html);
        }
    }
};

SettingsController.initFeedsSection = function () {
    var $myListsSection = $("#feeds-section");
    $myListsSection.html("");

    var allFeeds = App.currentUser.getFeeds();
    for (var i in allFeeds) {
        var feed = allFeeds[i];

        var html = '
' +
                '	' +
                '' + feed.feed_name + '	' +
                '	' +
                '
';

        $myListsSection.append(html);
    }
};

SettingsController.initListeners = function () {
    $("#collection-container").on('tap', ".collection-checkbox", SettingsController.collectionCheckbox);
    $("#collection-container").on('tap', "#select-all", SettingsController.selectAll);
    $("#collection-container").on('tap', ".collection-checkbox", SettingsController.initCategorySection);
    $("#collection-container").on('tap', "#select-all", SettingsController.initCategorySection);
    $("#collection-container").on('tap', ".collection-checkbox", SettingsController.checkAlfabeticSection);
    $("#collection-container").on('tap', "#select-all", SettingsController.checkAlfabeticSection);
    $("#settings").on("tap", "#btn-search-magazines", SettingsController.filterSearch);
    $("#settings").on("tap", ".settings-letter", SettingsController.filterLetter);
    $("#settings").on("tap", ".settings-category", SettingsController.filterCategory);
    $("#settings").on("tap", ".settings-feed", SettingsController.filterFeed);
};

SettingsController.selectAll = function(){
    var $obj = $(this);

    if ($obj.attr("src") === "img/category/unchecked.png") {
        $obj.attr("src", "img/category/checked.png");
        App.collectionsSelected = App.collectionsSelected.concat(App.collectionsRemoved);
        for(var i in App.collectionsRemoved){
            var collectionKey = App.collectionsRemoved[i];
            $(document.getElementById("cb-img-"+collectionKey)).attr("src", "img/category/checked.png");
        }
        App.collectionsRemoved = [];
    } else {
        $obj.attr("src", "img/category/unchecked.png");
        App.collectionsRemoved = App.collectionsRemoved.concat(App.collectionsSelected);
        for(var i in App.collectionsSelected){
            var collectionKey = App.collectionsSelected[i];
            $(document.getElementById("cb-img-"+collectionKey)).attr("src", "img/category/unchecked.png");
        }
        App.collectionsSelected = [];
    }
};

SettingsController.collectionCheckbox = function(){
    var collectionKey = $(this).data("collection");
    var $obj = $(this);

    if ($obj.attr("src") === "img/category/unchecked.png") {
        $obj.attr("src", "img/category/checked.png");
        App.collectionsSelected.push(collectionKey);
        var index = App.collectionsRemoved.indexOf(collectionKey);
        if (index > -1) {
            App.collectionsRemoved.splice(index, 1);
        }
        SettingsController.refreshSelectAll();
    } else {
        $obj.attr("src", "img/category/unchecked.png");
        App.collectionsRemoved.push(collectionKey);
        var index = App.collectionsSelected.indexOf(collectionKey);
        if (index > -1) {
            App.collectionsSelected.splice(index, 1);
        }
        SettingsController.refreshSelectAll();
    }
};

SettingsController.refreshSelectAll = function(){
    if(App.collectionsSelected.length < 1){
        $("#select-all").attr("src", "img/category/unchecked.png");
    }else if(App.collectionsRemoved.length < 1){
        $("#select-all").attr("src", "img/category/checked.png");
    }else{
        $("#select-all").attr("src", "img/category/checkbox-partial.png");
    }
};

SettingsController.filterSearch = function () {
    App.showLoadingScreen();
    FeedConfigController.selectedType = FeedConfigController.type.SEARCH;
    var searchQuery = $("#search-input").val();

    $.when(
            SciELO.searchMagazines(searchQuery)
            ).then(
            function (data) {
                // It worked
                FeedConfigController.filterData = {query: searchQuery, results: data};
                Navigator.loadPage("feedConfig.html");
                App.hideLoadingScreen();
            },
            function () {
                //TODO: add msg error
                App.hideLoadingScreen();
            }
    );
};

SettingsController.filterLetter = function () {
    FeedConfigController.selectedType = FeedConfigController.type.LETTER;
    FeedConfigController.filterData = $(this).html();
    Navigator.loadPage("feedConfig.html");
};

SettingsController.filterCategory = function () {
    FeedConfigController.selectedType = FeedConfigController.type.CATEGORY;
    FeedConfigController.filterData = $(this).data("categoryid");
    Navigator.loadPage("feedConfig.html");
};

SettingsController.filterFeed = function () {
    FeedConfigController.selectedType = FeedConfigController.type.FEED_EDIT;
    FeedConfigController.filterData = $(this).data("feedid");
    Navigator.loadPage("feedConfig.html");
};<|endoftext|>


<commit_before>"use strict";

const {strict: assert} = require("assert");

const {zrequire} = require("../zjsunit/namespace");
const {run_test} = require("../zjsunit/test");

const typeahead = zrequire("../shared/js/typeahead");

const unicode_emojis = [
    ["1f43c", "panda_face"],
    ["1f642", "smile"],
    ["1f604", "big_smile"],
    ["1f368", "ice_cream"],
    ["1f366", "soft_ice_cream"],
    ["1f6a5", "horizontal_traffic_light"],
    ["1f6a6", "traffic_light"],
    ["1f537", "large_blue_diamond"],
    ["1f539", "small_blue_diamond"],
];

const emojis = [
    {emoji_name: "japanese_post_office", url: "TBD"},
    {emoji_name: "tada", random_field: "whatever"},
    ...unicode_emojis.map(([emoji_code, emoji_name]) => ({
        emoji_name,
        emoji_code,
    })),
];

function assert_emoji_matches(query, expected) {
    const matcher = typeahead.get_emoji_matcher(query);
    const matches = emojis.filter((emoji) => matcher(emoji));
    assert.deepEqual(matches.map((emoji) => emoji.emoji_name).sort(), expected);
}

run_test("get_emoji_matcher: nonmatches", () => {
    assert_emoji_matches("notaemoji", []);
    assert_emoji_matches("da_", []);
    assert_emoji_matches("da ", []);
});

run_test("get_emoji_matcher: misc matches", () => {
    assert_emoji_matches("da", ["panda_face", "tada"]);
    assert_emoji_matches("panda ", ["panda_face"]);
    assert_emoji_matches("smil", ["big_smile", "smile"]);
    assert_emoji_matches("mile", ["big_smile", "smile"]);

    assert_emoji_matches("japanese_post_", ["japanese_post_office"]);
    assert_emoji_matches("japanese post ", ["japanese_post_office"]);
});

run_test("matches starting at non-first word, too", () => {
    assert_emoji_matches("ice_cream", ["ice_cream", "soft_ice_cream"]);
    assert_emoji_matches("blue_dia", ["large_blue_diamond", "small_blue_diamond"]);
    assert_emoji_matches("traffic_", ["horizontal_traffic_light", "traffic_light"]);
});

run_test("triage", () => {
    const alice = {name: "alice"};
    const alicia = {name: "Alicia"};
    const joan = {name: "Joan"};
    const jo = {name: "Jo"};
    const steve = {name: "steve"};
    const stephanie = {name: "Stephanie"};

    const names = [alice, alicia, joan, jo, steve, stephanie];

    assert.deepEqual(
        typeahead.triage("a", names, (r) => r.name),
        {
            matches: [alice, alicia],
            rest: [joan, jo, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage("A", names, (r) => r.name),
        {
            matches: [alicia, alice],
            rest: [joan, jo, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage("S", names, (r) => r.name),
        {
            matches: [stephanie, steve],
            rest: [alice, alicia, joan, jo],
        },
    );

    assert.deepEqual(
        typeahead.triage("fred", names, (r) => r.name),
        {
            matches: [],
            rest: [alice, alicia, joan, jo, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage("Jo", names, (r) => r.name),
        {
            matches: [jo, joan],
            rest: [alice, alicia, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage("jo", names, (r) => r.name),
        {
            matches: [jo, joan],
            rest: [alice, alicia, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage(" ", names, (r) => r.name),
        {
            matches: [],
            rest: [alice, alicia, joan, jo, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage(";", names, (r) => r.name),
        {
            matches: [],
            rest: [alice, alicia, joan, jo, steve, stephanie],
        },
    );
});

run_test("sort_emojis th", () => {
    const thumbs_up = {
        emoji_name: "thumbs_up",
        emoji_code: "1f44d",
    };
    const thumbs_down = {
        emoji_name: "thumbs_down",
    };
    const thermometer = {
        emoji_name: "thermometer",
    };
    const mother_nature = {
        emoji_name: "mother_nature",
    };

    const emoji_list = [mother_nature, thermometer, thumbs_down, thumbs_up];

    assert.deepEqual(typeahead.sort_emojis(emoji_list, "th"), [
        thumbs_up,
        thermometer,
        thumbs_down,
        mother_nature,
    ]);
});

run_test("sort_emojis sm", () => {
    const big_smile = {
        emoji_name: "big_smile",
    };
    const slight_smile = {
        emoji_name: "slight_smile",
        emoji_code: "1f642",
    };
    const small_airplane = {
        emoji_name: "small_airplane",
    };

    const emoji_list = [big_smile, slight_smile, small_airplane];

    assert.deepEqual(typeahead.sort_emojis(emoji_list, "sm"), [
        slight_smile,
        small_airplane,
        big_smile,
    ]);
});
<commit_msg>typeahead: Test spaces equivalent to underscores in get_emoji_matcher.<commit_after>"use strict";

const {strict: assert} = require("assert");

const {zrequire} = require("../zjsunit/namespace");
const {run_test} = require("../zjsunit/test");

const typeahead = zrequire("../shared/js/typeahead");

const unicode_emojis = [
    ["1f43c", "panda_face"],
    ["1f642", "smile"],
    ["1f604", "big_smile"],
    ["1f368", "ice_cream"],
    ["1f366", "soft_ice_cream"],
    ["1f6a5", "horizontal_traffic_light"],
    ["1f6a6", "traffic_light"],
    ["1f537", "large_blue_diamond"],
    ["1f539", "small_blue_diamond"],
];

const emojis = [
    {emoji_name: "japanese_post_office", url: "TBD"},
    {emoji_name: "tada", random_field: "whatever"},
    ...unicode_emojis.map(([emoji_code, emoji_name]) => ({
        emoji_name,
        emoji_code,
    })),
];

function emoji_matches(query) {
    const matcher = typeahead.get_emoji_matcher(query);
    return emojis.filter((emoji) => matcher(emoji));
}

function assert_emoji_matches(query, expected) {
    const names = emoji_matches(query).map((emoji) => emoji.emoji_name);
    assert.deepEqual(names.sort(), expected);
}

run_test("get_emoji_matcher: nonmatches", () => {
    assert_emoji_matches("notaemoji", []);
    assert_emoji_matches("da_", []);
});

run_test("get_emoji_matcher: misc matches", () => {
    assert_emoji_matches("da", ["panda_face", "tada"]);
    assert_emoji_matches("smil", ["big_smile", "smile"]);
    assert_emoji_matches("mile", ["big_smile", "smile"]);
    assert_emoji_matches("japanese_post_", ["japanese_post_office"]);
});

run_test("matches starting at non-first word, too", () => {
    assert_emoji_matches("ice_cream", ["ice_cream", "soft_ice_cream"]);
    assert_emoji_matches("blue_dia", ["large_blue_diamond", "small_blue_diamond"]);
    assert_emoji_matches("traffic_", ["horizontal_traffic_light", "traffic_light"]);
});

run_test("get_emoji_matcher: spaces equivalent to underscores", () => {
    function assert_equivalent(query) {
        assert.deepEqual(emoji_matches(query), emoji_matches(query.replace(" ", "_")));
    }
    assert_equivalent("da ");
    assert_equivalent("panda ");
    assert_equivalent("japanese post ");
    assert_equivalent("ice ");
    assert_equivalent("ice cream");
    assert_equivalent("blue dia");
    assert_equivalent("traffic ");
    assert_equivalent("traffic l");
});

run_test("triage", () => {
    const alice = {name: "alice"};
    const alicia = {name: "Alicia"};
    const joan = {name: "Joan"};
    const jo = {name: "Jo"};
    const steve = {name: "steve"};
    const stephanie = {name: "Stephanie"};

    const names = [alice, alicia, joan, jo, steve, stephanie];

    assert.deepEqual(
        typeahead.triage("a", names, (r) => r.name),
        {
            matches: [alice, alicia],
            rest: [joan, jo, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage("A", names, (r) => r.name),
        {
            matches: [alicia, alice],
            rest: [joan, jo, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage("S", names, (r) => r.name),
        {
            matches: [stephanie, steve],
            rest: [alice, alicia, joan, jo],
        },
    );

    assert.deepEqual(
        typeahead.triage("fred", names, (r) => r.name),
        {
            matches: [],
            rest: [alice, alicia, joan, jo, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage("Jo", names, (r) => r.name),
        {
            matches: [jo, joan],
            rest: [alice, alicia, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage("jo", names, (r) => r.name),
        {
            matches: [jo, joan],
            rest: [alice, alicia, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage(" ", names, (r) => r.name),
        {
            matches: [],
            rest: [alice, alicia, joan, jo, steve, stephanie],
        },
    );

    assert.deepEqual(
        typeahead.triage(";", names, (r) => r.name),
        {
            matches: [],
            rest: [alice, alicia, joan, jo, steve, stephanie],
        },
    );
});

run_test("sort_emojis th", () => {
    const thumbs_up = {
        emoji_name: "thumbs_up",
        emoji_code: "1f44d",
    };
    const thumbs_down = {
        emoji_name: "thumbs_down",
    };
    const thermometer = {
        emoji_name: "thermometer",
    };
    const mother_nature = {
        emoji_name: "mother_nature",
    };

    const emoji_list = [mother_nature, thermometer, thumbs_down, thumbs_up];

    assert.deepEqual(typeahead.sort_emojis(emoji_list, "th"), [
        thumbs_up,
        thermometer,
        thumbs_down,
        mother_nature,
    ]);
});

run_test("sort_emojis sm", () => {
    const big_smile = {
        emoji_name: "big_smile",
    };
    const slight_smile = {
        emoji_name: "slight_smile",
        emoji_code: "1f642",
    };
    const small_airplane = {
        emoji_name: "small_airplane",
    };

    const emoji_list = [big_smile, slight_smile, small_airplane];

    assert.deepEqual(typeahead.sort_emojis(emoji_list, "sm"), [
        slight_smile,
        small_airplane,
        big_smile,
    ]);
});
<|endoftext|>


<commit_before>import { permalink } from '../hooks/email'
import filterAllowedFields from '../hooks/filterAllowedFields'

export default (app) => {
  const service = {
    create: async (data) => {
      const { id, type, senderName, senderEmail, text } = data

      const entry = await app
        .service(`${type.toLowerCase()}s`)
        .get(id, { query: { $eager: 'ownerships' } })

      entry.properties.ownerships.forEach((owner) => {
        app.service('emails').create({
          template: 'entry_contact_message',
          message: {
            to: owner.email,
          },
          locals: {
            recipient: owner,
            entry,
            permalink: permalink(owner, entry),
            message: {
              senderName,
              senderEmail,
              text,
            },
          },
        })
      })
      return data
    },
  }

  app.use('/entrycontactmessage', service)

  app
    .service('entrycontactmessage')
    .hooks({
      before: {
        all: [],
        create: [],
      },
      after: {
        all: [],
        create: [],
      },
      error: {
        all: [],
        create: [],
      },
    })
    .hooks({
      after: {
        all: [filterAllowedFields],
      },
    })
}
<commit_msg>add reply to email to contact email.<commit_after>import { permalink } from '../hooks/email'
import filterAllowedFields from '../hooks/filterAllowedFields'

export default (app) => {
  const service = {
    create: async (data) => {
      const { id, type, senderName, senderEmail, text } = data

      const entry = await app
        .service(`${type.toLowerCase()}s`)
        .get(id, { query: { $eager: 'ownerships' } })

      entry.properties.ownerships.forEach((owner) => {
        app.service('emails').create({
          template: 'entry_contact_message',
          message: {
            to: owner.email,
            replyTo: senderEmail,
          },
          locals: {
            recipient: owner,
            entry,
            permalink: permalink(owner, entry),
            message: {
              senderName,
              senderEmail,
              text,
            },
          },
        })
      })
      return data
    },
  }

  app.use('/entrycontactmessage', service)

  app
    .service('entrycontactmessage')
    .hooks({
      before: {
        all: [],
        create: [],
      },
      after: {
        all: [],
        create: [],
      },
      error: {
        all: [],
        create: [],
      },
    })
    .hooks({
      after: {
        all: [filterAllowedFields],
      },
    })
}
<|endoftext|>


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

var hlc = require('../..');
var test = require('tape');
var util = require('util');
var fs = require('fs');

var keyValStorePath = "/tmp/keyValStore"
var keyValStorePath2 = keyValStorePath + "2";

//
// Run the registrar test
//
test('registrar test', function (t) {
    registrarTest(function(err) {
        if (err) fail(t, "registrarTest", err);
        else pass(t, "registrarTest");
    });
});

//
// Run the registrar test
//
test('enroll again', function (t) {
    enrollAgain(function(err) {
        if (err) fail(t, "enrollAgain", err);
        else pass(t, "enrollAgain");
    });
});

// The registrar test
function registrarTest(cb) {
   console.log("testRegistrar");
   //
   // Create and configure the test chain
   //
   var chain = hlc.newChain("testChain");
   chain.setKeyValStore(hlc.newFileKeyValStore(keyValStorePath));
   chain.setMemberServicesUrl("grpc://localhost:50051");
   chain.enroll("admin", "Xurw3yU9zI0l", function (err, admin) {
      if (err) return cb(err);
      chain.setRegistrar(admin);
      // Register and enroll webAdmin
      registerAndEnroll("webAdmin", {roles:['client']}, chain, function(err,webAdmin) {
         if (err) return cb(err);
         chain.setRegistrar(webAdmin);
         registerAndEnroll("webUser", null, chain, function(err, webUser) {
            if (err) return cb(err);
            chain.setRegistrar(webUser);
            registerAndEnroll("webUser2", null, chain, function(err) {
               if (!err) return cb(Error("webUser should not be allowed to register a client"));
               return cb();
            });
         });
      });
   });
}

// Register and enroll user 'name' with registrar info 'registrar' for chain 'chain'
function registerAndEnroll(name, registrar, chain, cb) {
    console.log("registerAndEnroll %s",name);
    // User is not enrolled yet, so perform both registration and enrollment
    var registrationRequest = {
         enrollmentID: name,
         account: "bank_a",
         affiliation: "00001",
         registrar: registrar
    };
    chain.registerAndEnroll(registrationRequest,cb);
}

// Force the client to try to enroll admin again by creating a different chain
// This should fail.
function enrollAgain(cb) {
   console.log("enrollAgain");
   //
   // Remove the file-based keyValStore
   // Create and configure testChain2 so there is no shared state with testChain
   // This is necessary to start without a local cache.
   //
   fs.renameSync(keyValStorePath,keyValStorePath2);
   var chain = hlc.newChain("testChain2");
   chain.setKeyValStore(hlc.newFileKeyValStore('/tmp/keyValStore'));
   chain.setMemberServicesUrl("grpc://localhost:50051");
   chain.enroll("admin", "Xurw3yU9zI0l", function (err, admin) {
      rmdir(keyValStorePath);
      fs.renameSync(keyValStorePath2,keyValStorePath);
      if (!err) return cb(Error("admin should not be allowed to re-enroll"));
      return cb();
   });
}

function rmdir(path) {
  if( fs.existsSync(path) ) {
    fs.readdirSync(path).forEach(function(file,index){
      var curPath = path + "/" + file;
      if(fs.lstatSync(curPath).isDirectory()) { // recurse
        rmdir(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

function pass(t, msg) {
    t.pass("Success: [" + msg + "]");
    t.end();
}

function fail(t, msg, err) {
    t.pass("Failure: [" + msg + "]: [" + err + "]");
    t.end(err);
}
<commit_msg>Add additional UT for registrar.js roles<commit_after>/**
 * Copyright 2016 IBM
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/**
 * Licensed Materials - Property of IBM
 * © Copyright IBM Corp. 2016
 */

var hlc = require('../..');
var test = require('tape');
var util = require('util');
var fs = require('fs');

var keyValStorePath = "/tmp/keyValStore"
var keyValStorePath2 = keyValStorePath + "2";

//
// Run the registrar test
//
test('registrar test', function (t) {
    registrarTest(function(err) {
        if (err) fail(t, "registrarTest", err);
        else pass(t, "registrarTest");
    });
});

//
// Run the registrar test
//
test('enroll again', function (t) {
    enrollAgain(function(err) {
        if (err) fail(t, "enrollAgain", err);
        else pass(t, "enrollAgain");
    });
});

// The registrar test
function registrarTest(cb) {
   console.log("testRegistrar");
   //
   // Create and configure the test chain
   //
   var chain = hlc.newChain("testChain");
   var expect="";
   var found="";

   chain.setKeyValStore(hlc.newFileKeyValStore(keyValStorePath));
   chain.setMemberServicesUrl("grpc://localhost:50051");
   chain.enroll("admin", "Xurw3yU9zI0l", function (err, admin) {
      if (err) return cb(err);
      chain.setRegistrar(admin);
      // Register and enroll webAdmin
      registerAndEnroll("webAdmin", "client", {roles:['client']}, chain, function(err,webAdmin) {
         if (err) return cb(err);
         chain.setRegistrar(webAdmin);
         registerAndEnroll("webUser", "client", null, chain, function(err, webUser) {
            if (err) return cb(err);
            registerAndEnroll("auditor", "auditor", null, chain, function(err, auditor) {
               if (!err) return cb(err);
               expect="webAdmin may not register member of type auditor";
               found = (err.toString()).match(expect);
               if (!(found==expect)) cb(err);
               registerAndEnroll("validator", "validator", null, chain, function(err, validator) {
                  if (!err) return cb(err);
                  expect="webAdmin may not register member of type validator";
                  found = (err.toString()).match(expect);
                  if (!(found==expect)) cb(err);
                  chain.setRegistrar(webUser);
                  registerAndEnroll("webUser2", "client", null, chain, function(err) {
                     if (!err) return cb(Error("webUser should not be allowed to register a client"));
                     expect="webUser may not register member of type client";
                     found = (err.toString()).match(expect);
                     if (!(found==expect)) cb(err);
                     return cb();
                  });
               });
            });
         });
      });
   });
}

// Register and enroll user 'name' with role 'r' with registrar info 'registrar' for chain 'chain'
function registerAndEnroll(name, r, registrar, chain, cb) {
    console.log("registerAndEnroll %s",name);
    // User is not enrolled yet, so perform both registration and enrollment
    var registrationRequest = {
         roles: [ r ],
         enrollmentID: name,
         account: "bank_a",
         affiliation: "00001",
         registrar: registrar
    };
    chain.registerAndEnroll(registrationRequest,cb);
}

// Force the client to try to enroll admin again by creating a different chain
// This should fail.
function enrollAgain(cb) {
   console.log("enrollAgain");
   //
   // Remove the file-based keyValStore
   // Create and configure testChain2 so there is no shared state with testChain
   // This is necessary to start without a local cache.
   //
   fs.renameSync(keyValStorePath,keyValStorePath2);
   var chain = hlc.newChain("testChain2");
   chain.setKeyValStore(hlc.newFileKeyValStore('/tmp/keyValStore'));
   chain.setMemberServicesUrl("grpc://localhost:50051");
   chain.enroll("admin", "Xurw3yU9zI0l", function (err, admin) {
      rmdir(keyValStorePath);
      fs.renameSync(keyValStorePath2,keyValStorePath);
      if (!err) return cb(Error("admin should not be allowed to re-enroll"));
      return cb();
   });
}

function rmdir(path) {
  if( fs.existsSync(path) ) {
    fs.readdirSync(path).forEach(function(file,index){
      var curPath = path + "/" + file;
      if(fs.lstatSync(curPath).isDirectory()) { // recurse
        rmdir(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

function pass(t, msg) {
    t.pass("Success: [" + msg + "]");
    t.end();
}

function fail(t, msg, err) {
    t.pass("Failure: [" + msg + "]: [" + err + "]");
    t.end(err);
}
<|endoftext|>


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

sc_require('components/graph/adornments/plot_adornment_model');

/** @class  The model for a movable line.

  @extends SC.Object
*/
DG.MovableValueModel = DG.PlotAdornmentModel.extend(
/** @scope DG.MovableValueModel.prototype */
{
  /**
    The current value
    @property { Number }
  */
  value: 1,

  /**
    Private cache.
    @property { Boolean }
  */
  _needsComputing: true,

  init: function() {
    sc_super();
    var tPlotModel = this.get('plotModel');
    if( tPlotModel) {
      this.recomputeValue( tPlotModel.get('primaryAxisModel'));
    }
  },

  /**
    True if we need to compute a new value to force within plot bounds
    @return { Boolean }
  */
  isComputingNeeded: function( iAxis) {
    if( this._needsComputing)
      return true;
    this._needsComputing = (this.value < iAxis.get('lowerBound')) ||
                            (this.value > iAxis.get('upperBound'));
    return this._needsComputing;
  },

  /**
    Force a recomputation at next opportunity.
   */
  setComputingNeeded: function() {
    this._needsComputing = true;
  },

  /**
    Use the bounds of the given axes to choose a value, but not one at the exact center.
  */
  recomputeValue: function( iAxis) {
    var tLower = iAxis.get('lowerBound'),
        tUpper = iAxis.get('upperBound');

    this.set('value', tLower + (tUpper - tLower) / 3);
    this._needsComputing = false;
  },

  /**
    Use the bounds of the given axes to recompute slope and intercept.
  */
  recomputeValueIfNeeded: function( iAxis) {
    if( this.isComputingNeeded( iAxis))
      this.recomputeValue( iAxis);
  },

  createStorage: function() {
    var storage = sc_super();
    if( this.get('isVisible'))
      storage.value = this.get('value');
    return storage;
  },

  restoreStorage: function( iStorage) {
    sc_super();
    if( iStorage && iStorage.value) {
      this.set('value', iStorage.value);
      this._needsComputing = false;
    }
    return this;
  }

});
DG.PlotAdornmentModel.registry.movableValue = DG.MovableValueModel;
<commit_msg>[Fixes #137392107] Drag the Moveable Value to its maximum or minimum point on a graph. The moveable line snaps back to its original position when it shouldn't be. We were constantly checking to make sure the movable value was within the axis bounds. But this seems like overkill, especially since the user can always make an additional movable value. So we no longer apply this forcing function.<commit_after>// ==========================================================================
//                      DG.MovableValueModel
//
//  Author:   William Finzer
//
//  Copyright (c) 2014 by The Concord Consortium, Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// ==========================================================================

sc_require('components/graph/adornments/plot_adornment_model');

/** @class  The model for a movable line.

  @extends SC.Object
*/
DG.MovableValueModel = DG.PlotAdornmentModel.extend(
/** @scope DG.MovableValueModel.prototype */
{
  /**
    The current value
    @property { Number }
  */
  value: 1,

  /**
    Private cache.
    @property { Boolean }
  */
  _needsComputing: true,

  init: function() {
    sc_super();
    var tPlotModel = this.get('plotModel');
    if( tPlotModel) {
      this.recomputeValue( tPlotModel.get('primaryAxisModel'));
    }
  },

  /**
    True if we need to compute a new value to force within plot bounds
    @return { Boolean }
  */
  isComputingNeeded: function( iAxis) {
/*
    if( this._needsComputing)
      return true;
    this._needsComputing = (this.value < iAxis.get('lowerBound')) ||
                            (this.value > iAxis.get('upperBound'));
*/
    return this._needsComputing;
  },

  /**
    Force a recomputation at next opportunity.
   */
  setComputingNeeded: function() {
    this._needsComputing = true;
  },

  /**
    Use the bounds of the given axes to choose a value, but not one at the exact center.
  */
  recomputeValue: function( iAxis) {
    var tLower = iAxis.get('lowerBound'),
        tUpper = iAxis.get('upperBound');

    this.set('value', tLower + (tUpper - tLower) / 3);
    this._needsComputing = false;
  },

  /**
    Use the bounds of the given axes to recompute slope and intercept.
  */
  recomputeValueIfNeeded: function( iAxis) {
    if( this.isComputingNeeded( iAxis))
      this.recomputeValue( iAxis);
  },

  createStorage: function() {
    var storage = sc_super();
    if( this.get('isVisible'))
      storage.value = this.get('value');
    return storage;
  },

  restoreStorage: function( iStorage) {
    sc_super();
    if( iStorage && iStorage.value) {
      this.set('value', iStorage.value);
      this._needsComputing = false;
    }
    return this;
  }

});
DG.PlotAdornmentModel.registry.movableValue = DG.MovableValueModel;
<|endoftext|>


<commit_before>/*! Generated by Grunt: http://gitbub.com/kingback/orientation/ 2014-07-25 12:55:22 */
!function(){function a(a){var b,c={};if(a)for(b in a)a.hasOwnProperty(b)&&(c[b]=a[b]);return c}function b(a,b){return a.bind?a.bind(b):function(){a.apply(b,arguments)}}function c(){this.init.apply(this,arguments)}var d="orientationchange",e="resize",f="onorientationchange"in window?d:e,g="function",h="on",i="after";c.prototype={constructor:c,init:function(c){this._cfg=a({delay:400},c),this._subs={on:[],after:[]},this.info=this.getInfo(),window.addEventListener(f,b(this._onWinOrientationChange,this),!1)},destroy:function(){window.removeEventListener(f,this._onWinOrientationChange,!1),delete this._subs},create:function(a){return new c(a)},getInfo:function(){return f===d?{landscape:90==window.orientation||-90==window.orientation,portrait:0==window.orientation||-180==window.orientation,orientation:window.orientation}:{landscape:window.screen.width>window.screen.height,portrait:window.screen.width<=window.screen.height,orientation:window.screen.width>window.screen.height?90:0}},isLandscape:function(){return this.info.landscape},isPortrait:function(){return this.info.portrait},change:function(a,b){return typeof a===g&&this._subs[b?i:h].push(a),this},_fireChange:function(b){var c,d,e=this,f=this.getInfo(),g=this._subs;if(f.landscape!==this.info.landscape){for(this.info=a(f),f.originEvent=b,f.originType=b.type,c=0,d=g.on.length;d>c;c++)g.on[c].call(e,b);setTimeout(function(){for(c=0,d=g.after.length;d>c;c++)g.after[c].call(e,b)},0)}},_checkChange:function(a){var b=this;b._cfg.delay?(clearTimeout(this._changeTimer),b._changeTimer=setTimeout(function(){b._fireChange(a)},b._cfg.delay)):b._fireChange(a)},_onWinOrientationChange:function(a){a.type==e?this._fireChange(a):this._checkChange(a)}},window.Orientation=c.prototype.create()}();<commit_msg>移除事件bugfix<commit_after>/*! Generated by Grunt: http://gitbub.com/kingback/orientation/ 2014-07-25 01:00:31 */
!function(){function a(a){var b,c={};if(a)for(b in a)a.hasOwnProperty(b)&&(c[b]=a[b]);return c}function b(a,b){return a.bind?a.bind(b):function(){a.apply(b,arguments)}}function c(){this.init.apply(this,arguments)}var d="orientationchange",e="resize",f="onorientationchange"in window?d:e,g="function",h="on",i="after";c.prototype={constructor:c,init:function(c){this._cfg=a({delay:400},c),this._subs={on:[],after:[]},this.info=this.getInfo(),window.addEventListener(f,b(this._onWinOrientationChange,this),!1)},destroy:function(){window.removeEventListener(f,this._onWinOrientationChange,!1),delete this._subs},create:function(a){return new c(a)},getInfo:function(){return f===d?{landscape:90==window.orientation||-90==window.orientation,portrait:0==window.orientation||-180==window.orientation,orientation:window.orientation}:{landscape:window.screen.width>window.screen.height,portrait:window.screen.width<=window.screen.height,orientation:window.screen.width>window.screen.height?90:0}},isLandscape:function(){return this.info.landscape},isPortrait:function(){return this.info.portrait},change:function(a,b){return typeof a===g&&this._subs[b?i:h].push(a),this},_fireChange:function(b){var c,d,e=this,f=this.getInfo(),g=this._subs;if(f.landscape!==this.info.landscape){for(this.info=a(f),f.originEvent=b,f.originType=b.type,c=0,d=g.on.length;d>c;c++)g.on[c].call(e,b);setTimeout(function(){for(c=0,d=g.after.length;d>c;c++)g.after[c].call(e,b)},0)}},_checkChange:function(a){var b=this;b._cfg.delay?(clearTimeout(this._changeTimer),b._changeTimer=setTimeout(function(){b._fireChange(a)},b._cfg.delay)):b._fireChange(a)},_onWinOrientationChange:function(a){a.type==e?this._fireChange(a):this._checkChange(a)}},window.Orientation=c.prototype.create()}();<|endoftext|>