<commit_before>const mongoose = require('mongoose')
const FriendRequest = mongoose.model('FriendRequest')
const User = mongoose.model('User')
const categories = require('../config/constants').categories

module.exports = {
  showRequests: (req, res) => {
    // remove the requests that are sent by the user
    let receivedFriendRequests = req.user.pendingFriendRequests.filter(frReq => {
      return !frReq.sender.equals(req.user.id)
    })
    FriendRequest.populate(receivedFriendRequests, { path: 'sender' }).then(reqs => {
      FriendRequest.populate(receivedFriendRequests, [{ path: 'sender.profilePic', model: 'Photo' }, { path: 'sender.category', model: 'Category' }]).then(reqs => {
        res.render('user/friendRequests', { friendRequests: receivedFriendRequests, categories: categories })
      })
    })
  },

  sendRequest: (req, res) => {
    // sends a friend request to the given user
    // Validate given ID
    let receiverId = req.params.receiverId
    if (req.user.id === receiverId) {
      req.session.errorMsg = 'You cannot friend yourself!'
      res.redirect('/')
      return
    } else if (req.user.hasFriend(receiverId)) {
      res.render('home/index', { categories: categories })
      return
    }

    User.findById(receiverId).populate('pendingFriendRequests').then(user => {
      if (!user) {
        // ERROR - User does not exist
        // Something is wrong with the logic or the user is malicious
        // TODO!
        res.render('home/index', { categories: categories })
        return
      } else if (user.hasFriend(req.user.id)) {
        // ERROR - User already has the logged in user as a friend
        throw Error(`ERROR: Inconsistency with friends, user ${req.user.email} does not have user ${user.email} as a friend, but ${user.email} does`)
      }
      // validate that such a request does not exist
      let potentialRequestIdx = user.pendingFriendRequests.findIndex(frReq => {
        return frReq.sender === req.user.id
      })
      if (potentialRequestIdx !== -1) {
        // ERROR, Such a request already exists!
        res.render('home/index', { categories: categories })
        return
      }

      FriendRequest.create({ sender: req.user.id, receiver: receiverId }).then(() => {
        let returnUrl = res.locals.returnUrl || `/user/${user.userId}`
        res.redirect(returnUrl)
      })
    })
  },

  acceptRequest: (req, res) => {
    let frReqId = req.params.id
    FriendRequest.findById(frReqId).populate('sender receiver').then(friendRequest => {
      if (!friendRequest) {
        req.session.errorMsg = 'No such friend request exists!'
        res.redirect('/')
        return
      } else if (!friendRequest.receiver.equals(req.user._id)) {
        req.session.errorMsg = 'You do not have permission to accept that request!'
        res.redirect('/')
        return
      }
      let sender = friendRequest.sender
      let receiver = friendRequest.receiver
      let promises = [
        // make them friends
        sender.addFriend(frReqId, receiver.id),
        receiver.addFriend(frReqId, sender.id)
      ]
      Promise.all(promises).then(() => {
        // Success - users are now friends, delete the FriendRequest
        friendRequest.remove()
        // TODO: Attach success message
        let returnUrl = res.locals.returnUrl || '/friendRequests'
        res.redirect(returnUrl)
      })
    })
  },

  declineRequest: (req, res) => {
    let frReqId = req.params.id
    FriendRequest.findById(frReqId).populate('sender receiver').then(friendRequest => {
      if (!friendRequest) {
        req.session.errorMsg = 'Invalid friend request!'
        res.redirect('/')
        return
      } else if (!(friendRequest.receiver.equals(req.user._id) || friendRequest.sender.equals(req.user._id))) {
        req.session.errorMsg = 'You do not have permission to decline that request!'
        res.redirect('/')
        return
      }
      let sender = friendRequest.sender
      let receiver = friendRequest.receiver
      let promises = [
        // remove the user's friend requests
        sender.removeFriendRequest(frReqId),
        receiver.removeFriendRequest(frReqId)
      ]

      Promise.all(promises).then(() => {
        friendRequest.remove()
        let returnUrl = res.locals.returnUrl || '/friendRequests'
        res.redirect(returnUrl)
      })
    })
  }
}
<commit_msg>Replaced some renders with redirects<commit_after>const mongoose = require('mongoose')
const FriendRequest = mongoose.model('FriendRequest')
const User = mongoose.model('User')
const categories = require('../config/constants').categories

module.exports = {
  showRequests: (req, res) => {
    // remove the requests that are sent by the user
    let receivedFriendRequests = req.user.pendingFriendRequests.filter(frReq => {
      return !frReq.sender.equals(req.user.id)
    })
    FriendRequest.populate(receivedFriendRequests, { path: 'sender' }).then(reqs => {
      FriendRequest.populate(receivedFriendRequests, [{ path: 'sender.profilePic', model: 'Photo' }, { path: 'sender.category', model: 'Category' }]).then(reqs => {
        res.render('user/friendRequests', { friendRequests: receivedFriendRequests, categories: categories })
      })
    })
  },

  sendRequest: (req, res) => {
    // sends a friend request to the given user
    // Validate given ID
    let receiverId = req.params.receiverId
    if (req.user.id === receiverId) {
      req.session.errorMsg = 'You cannot friend yourself!'
      res.redirect('/')
      return
    } else if (req.user.hasFriend(receiverId)) {
      res.render('home/index', { categories: categories })
      return
    }

    User.findById(receiverId).populate('pendingFriendRequests').then(user => {
      if (!user) {
        // ERROR - User does not exist
        // Something is wrong with the logic or the user is malicious
        req.session.errorMsg = 'User does not exist!'
        res.redirect('/')
        return
      } else if (user.hasFriend(req.user.id)) {
        // ERROR - User already has the logged in user as a friend
        console.log(`ERROR: Inconsistency with friends, user ${req.user.email} does not have user ${user.email} as a friend, but ${user.email} does`)
        req.session.errorMsg = 'You are already friends.'
        res.redirect('/')
      }
      // validate that such a request does not exist
      let potentialRequestIdx = user.pendingFriendRequests.findIndex(frReq => {
        return frReq.sender === req.user.id
      })
      if (potentialRequestIdx !== -1) {
        // ERROR, Such a request already exists!
        req.session.errorMsg = 'You already have a pending request to that user.'
        res.redirect('/')
        return
      }

      FriendRequest.create({ sender: req.user.id, receiver: receiverId }).then(() => {
        let returnUrl = res.locals.returnUrl || `/user/${user.userId}`
        res.redirect(returnUrl)
      })
    })
  },

  acceptRequest: (req, res) => {
    let frReqId = req.params.id
    FriendRequest.findById(frReqId).populate('sender receiver').then(friendRequest => {
      if (!friendRequest) {
        req.session.errorMsg = 'No such friend request exists!'
        res.redirect('/')
        return
      } else if (!friendRequest.receiver.equals(req.user._id)) {
        req.session.errorMsg = 'You do not have permission to accept that request!'
        res.redirect('/')
        return
      }
      let sender = friendRequest.sender
      let receiver = friendRequest.receiver
      let promises = [
        // make them friends
        sender.addFriend(frReqId, receiver.id),
        receiver.addFriend(frReqId, sender.id)
      ]
      Promise.all(promises).then(() => {
        // Success - users are now friends, delete the FriendRequest
        friendRequest.remove()
        // TODO: Attach success message
        let returnUrl = res.locals.returnUrl || '/friendRequests'
        res.redirect(returnUrl)
      })
    })
  },

  declineRequest: (req, res) => {
    let frReqId = req.params.id
    FriendRequest.findById(frReqId).populate('sender receiver').then(friendRequest => {
      if (!friendRequest) {
        req.session.errorMsg = 'Invalid friend request!'
        res.redirect('/')
        return
      } else if (!(friendRequest.receiver.equals(req.user._id) || friendRequest.sender.equals(req.user._id))) {
        req.session.errorMsg = 'You do not have permission to decline that request!'
        res.redirect('/')
        return
      }
      let sender = friendRequest.sender
      let receiver = friendRequest.receiver
      let promises = [
        // remove the user's friend requests
        sender.removeFriendRequest(frReqId),
        receiver.removeFriendRequest(frReqId)
      ]

      Promise.all(promises).then(() => {
        friendRequest.remove()
        let returnUrl = res.locals.returnUrl || '/friendRequests'
        res.redirect(returnUrl)
      })
    })
  }
}
<|endoftext|>


<commit_before>import EmberObject, { computed } from '@ember/object';

/**
 * @class Column
 * @extends Ember.Object
 * @namespace SemanticUI
 */
export default EmberObject.extend({
  /**
   * Label for the column header.
   *
   * @property label
   * @type String
   * @required
   * @public
   */
  label: '',

  /**
   * Path to the value displayed in this column.
   *
   * @property label
   * @type String
   * @public
   */
  valuePath: null,

  /**
   * Type of the header for this column. The type is mapped to a component
   * name prefixed with `table-header/`. To create custom header types, you
   * can create a new component named `table-header/my-custom-header` and
   * specify it here as `headerType: 'my-custom-header'`.
   *
   * @property headerType
   * @type String
   * @default 'default'
   * @public
   */
  headerType: 'default',

  /**
   * Type of the cells for this column. The type is mapped to a component name
   * prefixed with `table-cell/`. To create custom cell types, you can create
   * a new component named `table-cell/my-custom-cell` specify it here as
   * `cellType: 'my-custom-cell'`.
   *
   * @property cellType
   * @type String
   * @default 'default'
   * @public
   */
  cellType: 'default',

  /**
   * Whether the column can be hidden.
   *
   * @property hideable
   * @type Boolean
   * @default true
   * @public
   */
  hideable: true,

  /**
   * Whether the column is hidden.
   *
   * @property hidden
   * @type Boolean
   * @default false
   * @public
   */
  hidden: false,

  /**
   * Whether the column is visible.
   *
   * @property visible
   * @type Boolean
   * @default true
   * @public
   */
  visible: computed('hidden', {
    get() {
      return !this.get('hidden');
    },
    set(name, value) {
      this.set('hidden', !value);
    }
  }),

  /**
   * Whether the column can be sorted.
   *
   * @property sortable
   * @type Boolean
   * @default false
   * @public
   */
  sortable: false,

  /**
   * Whether the column is sorted.
   *
   * @property sorted
   * @type Boolean
   * @default false
   * @public
   */
  sorted: false,

  /**
   * The sort direction when `sorted` is `true`. Either 'ascending' or 'descending'.
   *
   * @property direction
   * @type String
   * @public
   */
  direction: '',

  /**
   * Text alignment for the column header and respective cells. Possible
   * values are `'left'`, `'center'` and `'right'`.
   *
   * @property align
   * @type String
   * @default 'left'
   * @public
   */
  align: 'left',

  /**
   * Vertical alignment for the column header and respective cells. Possible
   * values are `'top'`, `'middle'` and `'bottom'`.
   *
   * @property verticalAlign
   * @type String
   * @default 'top'
   * @public
   */
  verticalAlign: 'top',

  /**
   * Column width specified as in Semantic UI grid size (e.g. 'ten wide').
   *
   * @property width
   * @type String
   * @default null
   * @public
   */
  width: null,

  /**
   * Whether the column is collapsing so that it only uses as much space
   * as required.
   *
   * @property collapsing
   * @type Boolean
   * @default false
   * @public
   */
  collapsing: false,

  /**
   * Whether the cells in this column can be edited. Must be used together
   * with a `cellType` that supports editing.
   *
   * @property editable
   * @type Boolean
   * @default false
   * @public
   */
  editable: false
});
<commit_msg>Fix wrong property name in docs<commit_after>import EmberObject, { computed } from '@ember/object';

/**
 * @class Column
 * @extends Ember.Object
 * @namespace SemanticUI
 */
export default EmberObject.extend({
  /**
   * Label for the column header.
   *
   * @property label
   * @type String
   * @required
   * @public
   */
  label: '',

  /**
   * Path to the value displayed in this column.
   *
   * @property valuePath
   * @type String
   * @public
   */
  valuePath: null,

  /**
   * Type of the header for this column. The type is mapped to a component
   * name prefixed with `table-header/`. To create custom header types, you
   * can create a new component named `table-header/my-custom-header` and
   * specify it here as `headerType: 'my-custom-header'`.
   *
   * @property headerType
   * @type String
   * @default 'default'
   * @public
   */
  headerType: 'default',

  /**
   * Type of the cells for this column. The type is mapped to a component name
   * prefixed with `table-cell/`. To create custom cell types, you can create
   * a new component named `table-cell/my-custom-cell` specify it here as
   * `cellType: 'my-custom-cell'`.
   *
   * @property cellType
   * @type String
   * @default 'default'
   * @public
   */
  cellType: 'default',

  /**
   * Whether the column can be hidden.
   *
   * @property hideable
   * @type Boolean
   * @default true
   * @public
   */
  hideable: true,

  /**
   * Whether the column is hidden.
   *
   * @property hidden
   * @type Boolean
   * @default false
   * @public
   */
  hidden: false,

  /**
   * Whether the column is visible.
   *
   * @property visible
   * @type Boolean
   * @default true
   * @public
   */
  visible: computed('hidden', {
    get() {
      return !this.get('hidden');
    },
    set(name, value) {
      this.set('hidden', !value);
    }
  }),

  /**
   * Whether the column can be sorted.
   *
   * @property sortable
   * @type Boolean
   * @default false
   * @public
   */
  sortable: false,

  /**
   * Whether the column is sorted.
   *
   * @property sorted
   * @type Boolean
   * @default false
   * @public
   */
  sorted: false,

  /**
   * The sort direction when `sorted` is `true`. Either 'ascending' or 'descending'.
   *
   * @property direction
   * @type String
   * @public
   */
  direction: '',

  /**
   * Text alignment for the column header and respective cells. Possible
   * values are `'left'`, `'center'` and `'right'`.
   *
   * @property align
   * @type String
   * @default 'left'
   * @public
   */
  align: 'left',

  /**
   * Vertical alignment for the column header and respective cells. Possible
   * values are `'top'`, `'middle'` and `'bottom'`.
   *
   * @property verticalAlign
   * @type String
   * @default 'top'
   * @public
   */
  verticalAlign: 'top',

  /**
   * Column width specified as in Semantic UI grid size (e.g. 'ten wide').
   *
   * @property width
   * @type String
   * @default null
   * @public
   */
  width: null,

  /**
   * Whether the column is collapsing so that it only uses as much space
   * as required.
   *
   * @property collapsing
   * @type Boolean
   * @default false
   * @public
   */
  collapsing: false,

  /**
   * Whether the cells in this column can be edited. Must be used together
   * with a `cellType` that supports editing.
   *
   * @property editable
   * @type Boolean
   * @default false
   * @public
   */
  editable: false
});
<|endoftext|>


<commit_before>module.exports = {

	'SL_Chrome_Win7': {
		base: 'SauceLabs',
		browserName: 'chrome',
		platform: 'Windows 7'
	},

	'SL_Chrome_Win8': {
		base: 'SauceLabs',
		browserName: 'chrome',
		platform: 'Windows 8.1'
	},

	'SL_Chrome_OSX': {
		base: 'SauceLabs',
		browserName: 'chrome',
		platform: 'OS X 10.10'
	},

	'SL_FF_Win7': {
		base: 'SauceLabs',
		browserName: 'firefox',
		platform: 'Windows 7'
	},

	'SL_FF_OSX': {
		base: 'SauceLabs',
		browserName: 'firefox',
		platform: 'OS X 10.10'
	},

	'SL_IE_9': {
		base: 'SauceLabs',
		browserName: 'internet explorer',
		platform: 'Windows 7',
		version: '9'
	},

	'SL_Safari': {
		base: 'SauceLabs',
		browserName: 'safari',
		platform: 'OS X 10.10'
	}

}
<commit_msg>Just use chrome<commit_after>module.exports = {

	'SL_Chrome_Win7': {
		base: 'SauceLabs',
		browserName: 'chrome',
		platform: 'Windows 7'
	}
	/*,

		'SL_Chrome_Win8': {
			base: 'SauceLabs',
			browserName: 'chrome',
			platform: 'Windows 8.1'
		},

		'SL_Chrome_OSX': {
			base: 'SauceLabs',
			browserName: 'chrome',
			platform: 'OS X 10.10'
		},

		'SL_FF_Win7': {
			base: 'SauceLabs',
			browserName: 'firefox',
			platform: 'Windows 7'
		},

		'SL_FF_OSX': {
			base: 'SauceLabs',
			browserName: 'firefox',
			platform: 'OS X 10.10'
		},

		'SL_IE_9': {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '9'
		},

		'SL_Safari': {
			base: 'SauceLabs',
			browserName: 'safari',
			platform: 'OS X 10.10'
		}*/

}
<|endoftext|>


<commit_before>(function (angular) {
    'use strict';

    // Use existing module otherwise create a new one
    var module;
    try {
        module = angular.module('coUtils');
    } catch (e) {
        module = angular.module('coUtils', []);
    }

    // Reference code:
    // https://github.com/nostalgiaz/bootstrap-switch
    // https://github.com/cgarvis/angular-toggle-switch

    var toggle = ['$scope', '$timeout', function ($scope, $timeout) {
            $scope.toggle = function toggle() {
                if (!$scope.disabled) {
                    if ($scope.model === $scope.trueValue) {
                        $scope.model = $scope.falseValue;
                    } else {
                        $scope.model = $scope.trueValue;
                    }
                }
                $timeout($scope.onChange);
            };
        }];

    module
    .directive('toggleSwitch', function () {
        return {
            restrict: 'EA',
            scope: {
                model: '=?',
                disabled: '=?',
                onLabel: '=?',
                offLabel: '=?',
                trueValue: '=?',
                falseValue: '=?',
                knobLabel: '=?',
                onChange: '&'
            },
            template:
                '
' +
                    '
' +
                        '{{onLabel}}' +
                        '{{knobLabel}}' +
                        '{{offLabel}}' +
                    '
' +
                    '{{largeText}}' +
                '
',
            controller: toggle,
            link: function(scope, $element) {
                scope.onLabel = scope.onLabel || "On";
                scope.offLabel = scope.offLabel || "Off";
                scope.knobLabel = scope.knobLabel || "\u00a0";
                scope.trueValue = scope.trueValue || true;
                scope.falseValue = scope.falseValue || false;

                // Add class to outer element (no replace)
                $element.addClass('co-toggle');

                var longest = [
                        scope.onLabel, scope.knobLabel, scope.offLabel
                    ].sort(function (a, b) { return b.length - a.length; })[0];

                scope.largeText = longest + longest + 'buffer';
            }
        };
    })

    .directive('iosToggle', function () {
        return {
            template: '

',
            restrict: 'EA',
            controller: toggle,
            scope: {
                model: '=?',
                disabled: '=?',
                trueValue: '=?',
                falseValue: '=?',
                onChange: '&'
            },
            link: function (scope, $element) {
                scope.trueValue = scope.trueValue || true;
                scope.falseValue = scope.falseValue || false;

                // Add class to outer element (no replace)
                $element.addClass('ios-toggle');
            }
        };
    })

    // Requires the images to be defined in CSS
    .directive('imageToggle', function () {
        return {
            template:
                '

',
            restrict: 'EA',
            controller: toggle,
            scope: {
                model: '=?',
                disabled: '=?',
                trueValue: '=?',
                falseValue: '=?',
                onChange: '&'
            },
            link: function (scope, $element) {
                scope.trueValue = scope.trueValue || true;
                scope.falseValue = scope.falseValue || false;

                // Add class to outer element (no replace)
                $element.addClass('image-toggle');
            }
        };
    });

}(this.angular));
<commit_msg>allow true value to be falsy<commit_after>(function (angular) {
    'use strict';

    // Use existing module otherwise create a new one
    var module;
    try {
        module = angular.module('coUtils');
    } catch (e) {
        module = angular.module('coUtils', []);
    }

    // Reference code:
    // https://github.com/nostalgiaz/bootstrap-switch
    // https://github.com/cgarvis/angular-toggle-switch

    var toggle = ['$scope', '$timeout', function ($scope, $timeout) {
            $scope.toggle = function toggle() {
                if (!$scope.disabled) {
                    if ($scope.model === $scope.trueValue) {
                        $scope.model = $scope.falseValue;
                    } else {
                        $scope.model = $scope.trueValue;
                    }
                }
                $timeout($scope.onChange);
            };
        }];

    module
    .directive('toggleSwitch', function () {
        return {
            restrict: 'EA',
            scope: {
                model: '=?',
                disabled: '=?',
                onLabel: '=?',
                offLabel: '=?',
                trueValue: '=?',
                falseValue: '=?',
                knobLabel: '=?',
                onChange: '&'
            },
            template:
                '
' +
                    '
' +
                        '{{onLabel}}' +
                        '{{knobLabel}}' +
                        '{{offLabel}}' +
                    '
' +
                    '{{largeText}}' +
                '
',
            controller: toggle,
            link: function(scope, $element) {
                scope.onLabel = scope.onLabel || "On";
                scope.offLabel = scope.offLabel || "Off";
                scope.knobLabel = scope.knobLabel || "\u00a0";
                scope.trueValue = scope.trueValue === undefined ? true : scope.trueValue;
                scope.falseValue = scope.falseValue === undefined ? false : scope.falseValue;

                // Add class to outer element (no replace)
                $element.addClass('co-toggle');

                var longest = [
                        scope.onLabel, scope.knobLabel, scope.offLabel
                    ].sort(function (a, b) { return b.length - a.length; })[0];

                scope.largeText = longest + longest + 'buffer';
            }
        };
    })

    .directive('iosToggle', function () {
        return {
            template: '

',
            restrict: 'EA',
            controller: toggle,
            scope: {
                model: '=?',
                disabled: '=?',
                trueValue: '=?',
                falseValue: '=?',
                onChange: '&'
            },
            link: function (scope, $element) {
                scope.trueValue = scope.trueValue === undefined ? true : scope.trueValue;
                scope.falseValue = scope.falseValue === undefined ? false : scope.falseValue;

                // Add class to outer element (no replace)
                $element.addClass('ios-toggle');
            }
        };
    })

    // Requires the images to be defined in CSS
    .directive('imageToggle', function () {
        return {
            template:
                '

',
            restrict: 'EA',
            controller: toggle,
            scope: {
                model: '=?',
                disabled: '=?',
                trueValue: '=?',
                falseValue: '=?',
                onChange: '&'
            },
            link: function (scope, $element) {
                scope.trueValue = scope.trueValue === undefined ? true : scope.trueValue;
                scope.falseValue = scope.falseValue === undefined ? false : scope.falseValue;

                // Add class to outer element (no replace)
                $element.addClass('image-toggle');
            }
        };
    });

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


<commit_before>angular.module('bind.polymer', []).
directive('bindPolymer', function($q, $timeout) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var attrMap = {};
      for (var prop in attrs.$attr) {
        if (prop != 'bindPolymer') {
          var _attr = attrs.$attr[prop];
          var _match = element.attr(_attr).match(/\{\{\s*(\w+)\s*\}\}/);
          if (_match) {
            attrMap[_attr] = _match[1];
          }
        }
      }

      // Always get updated Polymer element
      function polymer() {
        return element.parent().find(element[0].nodeName)[0];
      }

      // Helper to wait for Polymer to expose the observe property
      function onPolymerReady() {
        var deferred = $q.defer();

        function _checkForObserve() {
          polymer().observe ?
            deferred.resolve() :
            $timeout(_checkForObserve, 10);
        }
        _checkForObserve();

        return deferred.promise;
      }

      // When Polymer is ready, establish the bound variable watch
      onPolymerReady().
        then(function(){
          // When Polymer sees a change to the bound variable,
          // $apply / $digest the changes here in Angular
          var observer = new MutationObserver(function() {
            scope.$apply();
          });

          observer.observe(polymer(), {attributes: true});

          for (var _attr in attrMap) {
            scope.$watch(
              function() {return element.attr(_attr);},
              function(value) {
                scope[attrMap[_attr]] = value;
              }
            );
          }
        });
    }
  };
});
<commit_msg>Keep module name same as directive name to cut down on confusion.<commit_after>angular.module('bindPolymer', []).
directive('bindPolymer', function($q, $timeout) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var attrMap = {};
      for (var prop in attrs.$attr) {
        if (prop != 'bindPolymer') {
          var _attr = attrs.$attr[prop];
          var _match = element.attr(_attr).match(/\{\{\s*(\w+)\s*\}\}/);
          if (_match) {
            attrMap[_attr] = _match[1];
          }
        }
      }

      // Always get updated Polymer element
      function polymer() {
        return element.parent().find(element[0].nodeName)[0];
      }

      // Helper to wait for Polymer to expose the observe property
      function onPolymerReady() {
        var deferred = $q.defer();

        function _checkForObserve() {
          polymer().observe ?
            deferred.resolve() :
            $timeout(_checkForObserve, 10);
        }
        _checkForObserve();

        return deferred.promise;
      }

      // When Polymer is ready, establish the bound variable watch
      onPolymerReady().
        then(function(){
          // When Polymer sees a change to the bound variable,
          // $apply / $digest the changes here in Angular
          var observer = new MutationObserver(function() {
            scope.$apply();
          });

          observer.observe(polymer(), {attributes: true});

          for (var _attr in attrMap) {
            scope.$watch(
              function() {return element.attr(_attr);},
              function(value) {
                scope[attrMap[_attr]] = value;
              }
            );
          }
        });
    }
  };
});
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'

import 'sanitize.css/sanitize.css'

import Nav from '../components/Nav'
import Logo from '../components/Logo'
import Footer from '../components/Footer'

import { m } from '../utils/breakpoints'

const Layout = ({
  location,
  children,
}) => (

        <Logo />

        {children()}

)

Layout.propTypes = {
  children: PropTypes.func.isRequired,
  location: PropTypes.shape({
    pathname: PropTypes.string.isRequired,
  }).isRequired,
}

export default Layout
<commit_msg>use rem instead of em<commit_after>import React from 'react'
import PropTypes from 'prop-types'

import 'sanitize.css/sanitize.css'

import Nav from '../components/Nav'
import Logo from '../components/Logo'
import Footer from '../components/Footer'

import { m } from '../utils/breakpoints'

const Layout = ({
  location,
  children,
}) => (

        <Logo />

        {children()}

)

Layout.propTypes = {
  children: PropTypes.func.isRequired,
  location: PropTypes.shape({
    pathname: PropTypes.string.isRequired,
  }).isRequired,
}

export default Layout
<|endoftext|>


<commit_before>import DS from 'ember-data';
import Ember from 'ember';

import {
  _normalizeSerializerPayload
} from './../serializer-response';

const {
  get,
  String: { pluralize },
  assert,
  Evented
} = Ember;

// copied from ember-data store core
function isThenable(object) {
  return object && typeof object.then === 'function';
}
// copied from ember-data store core
function serializerFor(container, type, defaultSerializer) {
  return container.lookup('serializer:' + type) ||
         container.lookup('serializer:application') ||
         container.lookup('serializer:' + defaultSerializer) ||
         container.lookup('serializer:-default');
}
// copied from ember-data store core
function serializerForAdapter(adapter, type) {
  let serializer = adapter.serializer;
  const defaultSerializer = adapter.defaultSerializer;
  const container = adapter.container;

  if (container && serializer === undefined) {
    serializer = serializerFor(container, type.modelName, defaultSerializer);
  }

  if (serializer === null || serializer === undefined) {
    serializer = {
      extract: function(store, type, payload) {
        return payload;
      }
    };
  }

  return serializer;
}
// copied from ember-data store core
function _commit(adapter, store, operation, snapshot) {
  const internalModel = snapshot._internalModel;
  const modelName = snapshot.modelName;
  const typeClass = store.modelFor(modelName);
  const promise = adapter[operation](store, typeClass, snapshot);
  const serializer = serializerForAdapter(store, adapter, modelName);
  const label = 'DS: Extract and notify about ' + operation + ' completion of ' + modelName;

  assert("Your adapter's '" + operation + "' method must return a value, but it returned `undefined", promise !== undefined);

  return promise.then((adapterPayload) => {
    let payload;

    store._adapterRun(() => {
      if (adapterPayload) {
        payload = serializer.extract(store, typeClass, adapterPayload, snapshot.id, operation);
      } else {
        payload = adapterPayload;
      }
      store.didSaveRecord(internalModel, _normalizeSerializerPayload(typeClass, payload));
    });
    return internalModel;
  }, (reason) => {
    if (reason instanceof DS.InvalidError) {
      store.recordWasInvalid(internalModel, reason.errors);
    } else {
      store.recordWasError(internalModel, reason);
    }
    throw reason;
  }, label);
}

function _bulkCommit(adapter, store, operation, modelName, snapshots) {
  const typeClass = store.modelFor(modelName);
  const promise = adapter[operation](store, typeClass, snapshots);
  const serializer = serializerForAdapter(store, adapter, modelName);
  const label = 'DS: Extract and notify about ' + operation + ' completion of ' + snapshots.length + ' of type ' + modelName;
  const internalModels = snapshots.map((snapshot) => snapshot._internalModel);
  assert('Your adapter\'s ' + operation + ' method must return a promise, but it returned ' + promise, isThenable(promise));

  return promise.then((adapterPayload) => {
    let payload;

    store._adapterRun(function() {
      if (adapterPayload) {
        payload = serializer.extract(store, typeClass, adapterPayload, null, operation);
      } else {
        payload = adapterPayload;
      }
      internalModels.forEach((internalModel, index) => {
        store.didSaveRecord(internalModel, _normalizeSerializerPayload(typeClass, payload && payload[index]));
      });
    });
    return internalModels;
  }, function(reason) {
    forEach(internalModels, (internalModel) => {
      if (reason instanceof DS.InvalidError) {
        store.recordWasInvalid(internalModel, reason.errors);
      } else {
        store.recordWasError(internalModel, reason);
      }
    });
    throw reason;
  }, label);
}

export default DS.Store.extend(Evented, {
  flushPendingSave: function() {
    const pending = this._pendingSave.slice();
    this._pendingSave = [];
    const bulkRecords = [];
    const bulkDataTypeMap = [];
    const bulkDataResolvers = [];
    const bulkDataAdapters = [];
    const bulkDataOperationMap = [
        'createRecord',
        'deleteRecord',
        'updateRecord'
      ];

    pending.forEach((pendingItem) => {
      const snapshot = pendingItem.snapshot;
      const internalModel = snapshot._internalModel;
      const resolver = pendingItem.resolver;
      const type = internalModel.type.modelName;
      const adapter = this.adapterFor(type);
      let bulkSupport;
      let operation;
      let typeIndex;
      let operationIndex;

      if (internalModel.isNew()) {
        operation = 'createRecord';
      } else if (internalModel.isDeleted()) {
        operation = 'deleteRecord';
      } else {
        operation = 'updateRecord';
      }
      bulkSupport = get(adapter, 'bulkOperationsSupport')[operation];

      if (bulkSupport) {
        operationIndex = bulkDataOperationMap.indexOf(operation);
        typeIndex = bulkDataTypeMap.indexOf(type);
        if (typeIndex < 0) {
          bulkDataTypeMap.push(type);
          typeIndex = bulkDataTypeMap.length - 1;
          bulkRecords[typeIndex] = [];
          bulkDataResolvers[typeIndex] = [];
          bulkDataAdapters[typeIndex] = adapter;
        }
        if (!(bulkRecords[typeIndex][operationIndex] instanceof Array)) {
          bulkRecords[typeIndex][operationIndex] = [];
        }
        if (!(bulkDataResolvers[typeIndex][operationIndex] instanceof Array)) {
          bulkDataResolvers[typeIndex][operationIndex] = [];
        }
        bulkDataResolvers[typeIndex][operationIndex].push(resolver);
        bulkRecords[typeIndex][operationIndex].push(snapshot);
      } else {
        resolver.resolve(_commit(adapter, this, operation, snapshot));
      }
    });

    /*jshint -W083 */
    if (bulkRecords.length) {
      for (let i = 0; i < bulkRecords.length; i++) {
        for (let j = 0; j < bulkDataOperationMap.length; j++) {
          if (bulkRecords[i][j] && bulkRecords[i][j].length) {
            if (bulkRecords[i][j].length === 1) {
              bulkDataResolvers[i][j][0].resolve(_commit(bulkDataAdapters[i], this, bulkDataOperationMap[j], bulkRecords[i][j][0]));
            } else {
              _bulkCommit(bulkDataAdapters[i], this, pluralize(bulkDataOperationMap[j]), bulkDataTypeMap[i], bulkRecords[i][j])
                .then(
                  (snapshots) => {
                    snapshots.forEach((snapshot, index) => {
                      bulkDataResolvers[i][j][index].resolve(snapshot);
                    });
                  },
                  (response) => {
                    bulkDataResolvers[i][j].forEach((promise) => promise.reject(response));
                  }
                );
            }
          }
        }
      }
    }
  }
});
<commit_msg>fix broken test<commit_after>import DS from 'ember-data';
import Ember from 'ember';

import {
  _normalizeSerializerPayload
} from './../serializer-response';

const {
  get,
  String: { pluralize },
  assert,
  Evented
} = Ember;

// copied from ember-data store core
function isThenable(object) {
  return object && typeof object.then === 'function';
}
// copied from ember-data store core
function serializerFor(container, type, defaultSerializer) {
  return container.lookup('serializer:' + type) ||
         container.lookup('serializer:application') ||
         container.lookup('serializer:' + defaultSerializer) ||
         container.lookup('serializer:-default');
}
// copied from ember-data store core
function serializerForAdapter(adapter, type) {
  let serializer = adapter.serializer;
  const defaultSerializer = adapter.defaultSerializer;
  const container = adapter.container;

  if (container && serializer === undefined) {
    serializer = serializerFor(container, type.modelName, defaultSerializer);
  }

  if (serializer === null || serializer === undefined) {
    serializer = {
      extract: function(store, type, payload) {
        return payload;
      }
    };
  }

  return serializer;
}
// copied from ember-data store core
function _commit(adapter, store, operation, snapshot) {
  const internalModel = snapshot._internalModel;
  const modelName = snapshot.modelName;
  const typeClass = store.modelFor(modelName);
  const promise = adapter[operation](store, typeClass, snapshot);
  const serializer = serializerForAdapter(store, adapter, modelName);
  const label = 'DS: Extract and notify about ' + operation + ' completion of ' + modelName;

  assert("Your adapter's '" + operation + "' method must return a value, but it returned `undefined", promise !== undefined);

  return promise.then((adapterPayload) => {
    let payload;

    store._adapterRun(() => {
      if (adapterPayload) {
        payload = serializer.extract(store, typeClass, adapterPayload, snapshot.id, operation);
      } else {
        payload = adapterPayload;
      }
      store.didSaveRecord(internalModel, _normalizeSerializerPayload(typeClass, payload));
    });
    return internalModel;
  }, (reason) => {
    if (reason instanceof DS.InvalidError) {
      store.recordWasInvalid(internalModel, reason.errors);
    } else {
      store.recordWasError(internalModel, reason);
    }
    throw reason;
  }, label);
}

function _bulkCommit(adapter, store, operation, modelName, snapshots) {
  const typeClass = store.modelFor(modelName);
  const promise = adapter[operation](store, typeClass, snapshots);
  const serializer = serializerForAdapter(store, adapter, modelName);
  const label = 'DS: Extract and notify about ' + operation + ' completion of ' + snapshots.length + ' of type ' + modelName;
  const internalModels = snapshots.map((snapshot) => snapshot._internalModel);
  assert('Your adapter\'s ' + operation + ' method must return a promise, but it returned ' + promise, isThenable(promise));

  return promise.then((adapterPayload) => {
    let payload;

    store._adapterRun(function() {
      if (adapterPayload) {
        payload = serializer.extract(store, typeClass, adapterPayload, null, operation);
      } else {
        payload = adapterPayload;
      }
      internalModels.forEach((internalModel, index) => {
        store.didSaveRecord(internalModel, _normalizeSerializerPayload(typeClass, payload && payload[index]));
      });
    });
    return internalModels;
  }, function(reason) {
    internalModels.forEach((internalModel) => {
      if (reason instanceof DS.InvalidError) {
        store.recordWasInvalid(internalModel, reason.errors);
      } else {
        store.recordWasError(internalModel, reason);
      }
    });
    throw reason;
  }, label);
}

export default DS.Store.extend(Evented, {
  flushPendingSave: function() {
    const pending = this._pendingSave.slice();
    this._pendingSave = [];
    const bulkRecords = [];
    const bulkDataTypeMap = [];
    const bulkDataResolvers = [];
    const bulkDataAdapters = [];
    const bulkDataOperationMap = [
        'createRecord',
        'deleteRecord',
        'updateRecord'
      ];

    pending.forEach((pendingItem) => {
      const snapshot = pendingItem.snapshot;
      const internalModel = snapshot._internalModel;
      const resolver = pendingItem.resolver;
      const type = internalModel.type.modelName;
      const adapter = this.adapterFor(type);
      let bulkSupport;
      let operation;
      let typeIndex;
      let operationIndex;

      if (internalModel.isNew()) {
        operation = 'createRecord';
      } else if (internalModel.isDeleted()) {
        operation = 'deleteRecord';
      } else {
        operation = 'updateRecord';
      }
      bulkSupport = get(adapter, 'bulkOperationsSupport')[operation];

      if (bulkSupport) {
        operationIndex = bulkDataOperationMap.indexOf(operation);
        typeIndex = bulkDataTypeMap.indexOf(type);
        if (typeIndex < 0) {
          bulkDataTypeMap.push(type);
          typeIndex = bulkDataTypeMap.length - 1;
          bulkRecords[typeIndex] = [];
          bulkDataResolvers[typeIndex] = [];
          bulkDataAdapters[typeIndex] = adapter;
        }
        if (!(bulkRecords[typeIndex][operationIndex] instanceof Array)) {
          bulkRecords[typeIndex][operationIndex] = [];
        }
        if (!(bulkDataResolvers[typeIndex][operationIndex] instanceof Array)) {
          bulkDataResolvers[typeIndex][operationIndex] = [];
        }
        bulkDataResolvers[typeIndex][operationIndex].push(resolver);
        bulkRecords[typeIndex][operationIndex].push(snapshot);
      } else {
        resolver.resolve(_commit(adapter, this, operation, snapshot));
      }
    });

    /*jshint -W083 */
    if (bulkRecords.length) {
      for (let i = 0; i < bulkRecords.length; i++) {
        for (let j = 0; j < bulkDataOperationMap.length; j++) {
          if (bulkRecords[i][j] && bulkRecords[i][j].length) {
            if (bulkRecords[i][j].length === 1) {
              bulkDataResolvers[i][j][0].resolve(_commit(bulkDataAdapters[i], this, bulkDataOperationMap[j], bulkRecords[i][j][0]));
            } else {
              _bulkCommit(bulkDataAdapters[i], this, pluralize(bulkDataOperationMap[j]), bulkDataTypeMap[i], bulkRecords[i][j])
                .then(
                  (snapshots) => {
                    snapshots.forEach((snapshot, index) => {
                      bulkDataResolvers[i][j][index].resolve(snapshot);
                    });
                  },
                  (response) => {
                    bulkDataResolvers[i][j].forEach((promise) => promise.reject(response));
                  }
                );
            }
          }
        }
      }
    }
  }
});
<|endoftext|>


<commit_before>import { setSources } from "./lazyload.setSources";
import { setStatus } from "./lazyload.data";
import { addOneShotEventListeners, checkFinish } from "./lazyload.event";
import { addClass } from "./lazyload.class";
import { safeCallback } from "./lazyload.callback";
import { statusLoading, statusNative } from "./lazyload.elementStatus";

const manageableTags = ["IMG", "IFRAME", "VIDEO"];

export const decreaseToLoadCount = (settings, instance) => {
    if (instance) instance.toLoadCount -= 1;
    checkFinish(settings, instance);
};

export const unobserve = (element, instance) => {
    const observer = instance._observer;
    if (observer && instance._settings.auto_unobserve) {
        observer.unobserve(element);
    }
};

export const isManageableTag = element => manageableTags.indexOf(element.tagName) > -1;

export const enableLoading = (element, settings, instance) => {
    if (isManageableTag(element)) {
        addOneShotEventListeners(element, settings, instance);
        addClass(element, settings.class_loading);
    }
    setSources(element, settings, instance);
    decreaseToLoadCount(settings, instance);
};

export const load = (element, settings, instance) => {
    enableLoading(element, settings, instance);
    setStatus(element, statusLoading);
    safeCallback(settings.callback_loading, element, instance);
    /* DEPRECATED, REMOVE IN V.15 => */ safeCallback(settings.callback_reveal, element, instance);
    if (instance) unobserve(element, instance);
};

export const loadNative = (element, settings, instance) => {
    enableLoading(element, settings, instance);
    setStatus(element, statusNative);
};
<commit_msg>Fixed an error when using static load<commit_after>import { setSources } from "./lazyload.setSources";
import { setStatus } from "./lazyload.data";
import { addOneShotEventListeners, checkFinish } from "./lazyload.event";
import { addClass } from "./lazyload.class";
import { safeCallback } from "./lazyload.callback";
import { statusLoading, statusNative } from "./lazyload.elementStatus";

const manageableTags = ["IMG", "IFRAME", "VIDEO"];

export const decreaseToLoadCount = (settings, instance) => {
    if (instance) instance.toLoadCount -= 1;
    checkFinish(settings, instance);
};

export const unobserve = (element, instance) => {
    const observer = instance._observer;
    if (observer && instance._settings.auto_unobserve) {
        observer.unobserve(element);
    }
};

export const isManageableTag = element => manageableTags.indexOf(element.tagName) > -1;

export const enableLoading = (element, settings, instance) => {
    if (isManageableTag(element)) {
        addOneShotEventListeners(element, settings, instance);
        addClass(element, settings.class_loading);
    }
    setSources(element, settings, instance);
    if (instance) decreaseToLoadCount(settings, instance);
};

export const load = (element, settings, instance) => {
    enableLoading(element, settings, instance);
    setStatus(element, statusLoading);
    safeCallback(settings.callback_loading, element, instance);
    /* DEPRECATED, REMOVE IN V.15 => */ safeCallback(settings.callback_reveal, element, instance);
    if (instance) unobserve(element, instance);
};

export const loadNative = (element, settings, instance) => {
    enableLoading(element, settings, instance);
    setStatus(element, statusNative);
};
<|endoftext|>


<commit_before>// require('../lib/transform.js')
var exports;
if (typeof module === "object" && exports) {
	exports = module.exports;
} else if (typeof window !== "undefined") {
	exports = window["eviltransform"] = {};
}

var earthR = 6378137.0;

function outOfChina(lat, lng) {
	if ((lng < 72.004) || (lng > 137.8347)) {
		return true;
	}
	if ((lat < 0.8293) || (lat > 55.8271)) {
		return true;
	}
	return false;
}

function transform(x, y) {
	var xy = x * y;
	var absX = Math.sqrt(Math.abs(x));
	var xPi = x * Math.PI;
	var yPi = y * Math.PI;
	var d = 20.0*Math.sin(6.0*xPi) + 20.0*Math.sin(2.0*xPi);

	var lat = d;
	var lng = d;

	lat += 20.0*Math.sin(yPi) + 40.0*Math.sin(yPi/3.0);
	lng += 20.0*Math.sin(xPi) + 40.0*Math.sin(xPi/3.0);

	lat += 160.0*Math.sin(yPi/12.0) + 320*Math.sin(yPi/30.0);
	lng += 150.0*Math.sin(xPi/12.0) + 300.0*Math.sin(xPi/30.0);

	lat *= 2.0 / 3.0;
	lng *= 2.0 / 3.0;

	lat += -100.0 + 2.0*x + 3.0*y + 0.2*y*y + 0.1*xy + 0.2*absX;
	lng += 300.0 + x + 2.0*y + 0.1*x*x + 0.1*xy + 0.1*absX;

	return {lat: lat, lng: lng}
}

function delta(lat, lng) {
	var ee = 0.00669342162296594323;
	var d = transform(lng-105.0, lat-35.0);
	var radLat = lat / 180.0 * Math.PI;
	var magic = Math.sin(radLat);
	magic = 1 - ee*magic*magic;
	var sqrtMagic = Math.sqrt(magic);
	d.lat = (d.lat * 180.0) / ((earthR * (1 - ee)) / (magic * sqrtMagic) * Math.PI);
	d.lng = (d.lng * 180.0) / (earthR / sqrtMagic * Math.cos(radLat) * Math.PI);
	return d;
}

function wgs2gcj(wgsLat, wgsLng) {
	if (outOfChina(wgsLat, wgsLng)) {
		return {lat: wgsLat, lng: wgsLng};
	}
	var d = delta(wgsLat, wgsLng);
	return {lat: wgsLat + d.lat, lng: wgsLng + d.lng};
}
exports.wgs2gcj = wgs2gcj;

function gcj2wgs(gcjLat, gcjLng) {
	if (outOfChina(gcjLat, gcjLng)) {
		return {lat: gcjLat, lng: gcjLng};
	}
	var d = delta(gcjLat, gcjLng);
	return {lat: gcjLat - d.lat, lng: gcjLng - d.lng};
}
exports.gcj2wgs = gcj2wgs;

function gcj2wgs_exact(gcjLat, gcjLng) {
	var initDelta = 0.01;
	var threshold = 0.000001;
	var dLat = initDelta, dLng = initDelta;
	var mLat = gcjLat-dLat, mLng = gcjLng-dLng;
	var pLat = gcjLat+dLat, pLng = gcjLng+dLng;
	var wgsLat, wgsLng;
	for (var i = 0; i < 30; i++) {
		wgsLat = (mLat+pLat)/2;
		wgsLng = (mLng+pLng)/2;
		var tmp = wgs2gcj(wgsLat, wgsLng)
		dLat = tmp.lat-gcjLat;
		dLng = tmp.lng-gcjLng;
		if ((Math.abs(dLat) < threshold) && (Math.abs(dLng) < threshold)) {
			return {lat: wgsLat, lng: wgsLng};
		}
		if (dLat > 0) {
			pLat = wgsLat;
		} else {
			mLat = wgsLat;
		}
		if (dLng > 0) {
			pLng = wgsLng;
		} else {
			mLng = wgsLng;
		}
	}
	return {lat: wgsLat, lng: wgsLng};
}
exports.gcj2wgs_exact = gcj2wgs_exact;

function distance(latA, lngA, latB, lngB) {
	var pi180 = Math.PI / 180;
	var arcLatA = latA * pi180;
 	var arcLatB = latB * pi180;
	var x = Math.cos(arcLatA) * Math.cos(arcLatB) * Math.cos((lngA-lngB)*pi180);
	var y = Math.sin(arcLatA) * Math.sin(arcLatB);
	var s = x + y;
	if (s > 1) {
		s = 1;
	}
	if (s < -1) {
		s = -1;
	}
	var alpha = Math.acos(s);
	var distance = alpha * earthR;
	return distance;
}
exports.distance = distance;

function gcj2bd(gcjLat, gcjLng) {
	if (outOfChina(gcjLat, gcjLng)) {
		return {lat: gcjLat, lng: gcjLng};
	}

	var x = gcjLng, y = gcjLat;
	var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
	var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);
	var bdLng = z * Math.cos(theta) + 0.0065;
	var bdLat = z * Math.sin(theta) + 0.006;
	return {lat: bdLat, lng: bdLng};
}
exports.gcj2bd = gcj2bd;

function bd2gcj(bdLat, bdLng) {
	if (outOfChina(bdLat, bdLng)) {
		return {lat: bdLat, lng: bdLng};
	}

	var x = bdLng - 0.0065, y = bdLat - 0.006;
	var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
	var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);
	var gcjLng = z * Math.cos(theta);
	var gcjLat = z * Math.sin(theta);
	return {lat: gcjLat, lng: gcjLng};
}
exports.bd2gcj = bd2gcj;

function wgs2bd(wgsLat, wgsLng) {
	var gcj = wgs2gcj(wgsLat, wgsLng);
	return gcj2bd(gcj.lat, gcj.lng);
}
exports.wgs2bd = wgs2bd;

function bd2wgs(bdLat, bdLng) {
	var gcj = bd2gcj(bdLat, bdLng);
	return gcj2wgs(gcj.lat, gcj.lng);
}
exports.bd2wgs = bd2wgs;
/**
 * Projection class for Baidu Spherical Mercator
 *
 * @class BaiduSphericalMercator
 */
L.Projection.GCJ02SphericalMercator = {
    /**
     * Project latLng to point coordinate
     *
     * @method project
     * @param {Object} latLng coordinate for a point on earth
     * @return {Object} leafletPoint point coordinate of L.Point
     */
    project: function(latLng) {
        //1.gcj02 to wgs84 lat lon
        //2.wgs84 lat lon to point
        var wgs84_latlon = gcj2wgs(latLng.lat, latLng.lng)
        // var MAX_LATITUDE = 85.0511287798;
        // var R = 6378137;
        // var d = Math.PI/ 180;
        // var max = MAX_LATITUDE;
        // var lat = Math.max(Math.min(max, wgs84_latlon.lat), -max);
        // var sin = Math.sin(lat * d);

        // var x = R *  wgs84_latlon.lng * d;
        // var y = R * Math.log((1 + sin) / (1 - sin)) / 2;

        var x = wgs84_latlon.lng * 20037508.34 / 180;
        var y = Math.log(Math.tan((90 + wgs84_latlon.lat) * Math.PI / 360)) / (Math.PI / 180);
        y = y * 20037508.34 / 180;

        var leafletPoint = new L.Point(x, y);
        return leafletPoint;

    },

    /**
     * unproject point coordinate to latLng
     *
     * @method unproject
     * @param {Object} bpoint baidu point coordinate
     * @return {Object} latitude and longitude
     */
    unproject: function (bpoint) {
        //1. x,y to wgs84 lat lon
        //2. wgs84 to gcj02 lat lon
        // var R = 6378137;
        // var d = 180 / Math.PI;
        // var lng = bpoint.x * d / R;
        // var lat = (2 * Math.atan(Math.exp(bpoint.y / R)) - (Math.PI / 2)) * d;

        var lng = (bpoint.x / 20037508.34) * 180;
        var lat = (bpoint.y / 20037508.34) * 180;

        lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

        gcj02_latlon = wgs2gcj(lat, lng);
        var latLng = new L.LatLng(gcj02_latlon.lat, gcj02_latlon.lng);
        return latLng;
    },

    /**
     * Don't know how it used currently.
     *
     * However, I guess this is the range of coordinate.
     * Range of pixel coordinate is gotten from
     * BMap.MercatorProjection.lngLatToPoint(180, -90) and (180, 90)
     * After getting max min value of pixel coordinate, use
     * pointToLngLat() get the max lat and Lng.
     */
    // bounds: (function () {
    //     var MAX_X= 20037726.37;
    //     var MIN_Y= -11708041.66;
    //     var MAX_Y= 12474104.17;
    //     var bounds = L.bounds(
    //         [-MAX_X, MIN_Y], //180, -71.988531
    //         [MAX_X, MAX_Y]  //-180, 74.000022
    //     );
    //     return bounds;
    // })()
};

L.GCJ02Transformation = L.extend({}, L.Transformation, {
  MAXZOOM: 30,
  /**
   * Don't know how it used currently.
   */
  transform: function (point, zoom) {
      return this._transform(point.clone(), zoom);
  },

  /**
   * transform point coordinate to pixel coordinate
   *
   * @method _transform
   * @param {Object} point point coordinate
   * @param {Number} zoom zoom level of the map
   * @return {Object} point, pixel coordinate
   */
  _transform: function (point, zoom) {
      point.x = point.x >> (this.MAXZOOM - zoom);
      point.y = point.y >> (this.MAXZOOM - zoom);
      return point;
  },

  /**
   * transform pixel coordinate to point coordinate
   *
   * @method untransform
   * @param {Object} point pixel coordinate
   * @param {Number} zoom zoom level of the map
   * @return {Object} point, point coordinate
   */
  untransform: function (point, zoom) {
      point.x = point.x << (this.MAXZOOM - zoom);
      point.y = point.y << (this.MAXZOOM - zoom);
      return point;
  }
});

/**
 * Coordinate system for Baidu EPSG3857
 *
 * @class BEPSG3857
 */
L.CRS.GCJ02 = L.extend({}, L.CRS, {
    /**
     * transform latLng to pixel coordinate
     *
     * @method untransform
     * @param {Object} latlng latitude and longitude
     * @param {Number} zoom zoom level of the map
     * @return {Object} pixel coordinate calculated for latLng
     */
    latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
        var projectedPoint = this.projection.project(latlng);
        return this.transformation._transform(projectedPoint, zoom);
    },

    /**
     * transform pixel coordinate to latLng
     *
     * @method untransform
     * @param {Object} point pixel coordinate
     * @param {Number} zoom zoom level of the map
     * @return {Object} latitude and longitude
     */
    pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
        var untransformedPoint = this.transformation.untransform(point, zoom);
        return this.projection.unproject(untransformedPoint);
    },

    code: 'EPSG:3857',
    projection: L.Projection.GCJ02SphericalMercator,

    transformation: L.GCJ02Transformation
});
<commit_msg>fix bug<commit_after>// require('../lib/transform.js')
var exports;
if (typeof module === "object" && exports) {
	exports = module.exports;
} else if (typeof window !== "undefined") {
	exports = window["eviltransform"] = {};
}

var earthR = 6378137.0;

function outOfChina(lat, lng) {
	if ((lng < 72.004) || (lng > 137.8347)) {
		return true;
	}
	if ((lat < 0.8293) || (lat > 55.8271)) {
		return true;
	}
	return false;
}

function transform(x, y) {
	var xy = x * y;
	var absX = Math.sqrt(Math.abs(x));
	var xPi = x * Math.PI;
	var yPi = y * Math.PI;
	var d = 20.0*Math.sin(6.0*xPi) + 20.0*Math.sin(2.0*xPi);

	var lat = d;
	var lng = d;

	lat += 20.0*Math.sin(yPi) + 40.0*Math.sin(yPi/3.0);
	lng += 20.0*Math.sin(xPi) + 40.0*Math.sin(xPi/3.0);

	lat += 160.0*Math.sin(yPi/12.0) + 320*Math.sin(yPi/30.0);
	lng += 150.0*Math.sin(xPi/12.0) + 300.0*Math.sin(xPi/30.0);

	lat *= 2.0 / 3.0;
	lng *= 2.0 / 3.0;

	lat += -100.0 + 2.0*x + 3.0*y + 0.2*y*y + 0.1*xy + 0.2*absX;
	lng += 300.0 + x + 2.0*y + 0.1*x*x + 0.1*xy + 0.1*absX;

	return {lat: lat, lng: lng}
}

function delta(lat, lng) {
	var ee = 0.00669342162296594323;
	var d = transform(lng-105.0, lat-35.0);
	var radLat = lat / 180.0 * Math.PI;
	var magic = Math.sin(radLat);
	magic = 1 - ee*magic*magic;
	var sqrtMagic = Math.sqrt(magic);
	d.lat = (d.lat * 180.0) / ((earthR * (1 - ee)) / (magic * sqrtMagic) * Math.PI);
	d.lng = (d.lng * 180.0) / (earthR / sqrtMagic * Math.cos(radLat) * Math.PI);
	return d;
}

function wgs2gcj(wgsLat, wgsLng) {
	if (outOfChina(wgsLat, wgsLng)) {
		return {lat: wgsLat, lng: wgsLng};
	}
	var d = delta(wgsLat, wgsLng);
	return {lat: wgsLat + d.lat, lng: wgsLng + d.lng};
}
exports.wgs2gcj = wgs2gcj;

function gcj2wgs(gcjLat, gcjLng) {
	if (outOfChina(gcjLat, gcjLng)) {
		return {lat: gcjLat, lng: gcjLng};
	}
	var d = delta(gcjLat, gcjLng);
	return {lat: gcjLat - d.lat, lng: gcjLng - d.lng};
}
exports.gcj2wgs = gcj2wgs;

function gcj2wgs_exact(gcjLat, gcjLng) {
	var initDelta = 0.01;
	var threshold = 0.000001;
	var dLat = initDelta, dLng = initDelta;
	var mLat = gcjLat-dLat, mLng = gcjLng-dLng;
	var pLat = gcjLat+dLat, pLng = gcjLng+dLng;
	var wgsLat, wgsLng;
	for (var i = 0; i < 30; i++) {
		wgsLat = (mLat+pLat)/2;
		wgsLng = (mLng+pLng)/2;
		var tmp = wgs2gcj(wgsLat, wgsLng)
		dLat = tmp.lat-gcjLat;
		dLng = tmp.lng-gcjLng;
		if ((Math.abs(dLat) < threshold) && (Math.abs(dLng) < threshold)) {
			return {lat: wgsLat, lng: wgsLng};
		}
		if (dLat > 0) {
			pLat = wgsLat;
		} else {
			mLat = wgsLat;
		}
		if (dLng > 0) {
			pLng = wgsLng;
		} else {
			mLng = wgsLng;
		}
	}
	return {lat: wgsLat, lng: wgsLng};
}
exports.gcj2wgs_exact = gcj2wgs_exact;

function distance(latA, lngA, latB, lngB) {
	var pi180 = Math.PI / 180;
	var arcLatA = latA * pi180;
 	var arcLatB = latB * pi180;
	var x = Math.cos(arcLatA) * Math.cos(arcLatB) * Math.cos((lngA-lngB)*pi180);
	var y = Math.sin(arcLatA) * Math.sin(arcLatB);
	var s = x + y;
	if (s > 1) {
		s = 1;
	}
	if (s < -1) {
		s = -1;
	}
	var alpha = Math.acos(s);
	var distance = alpha * earthR;
	return distance;
}
exports.distance = distance;

function gcj2bd(gcjLat, gcjLng) {
	if (outOfChina(gcjLat, gcjLng)) {
		return {lat: gcjLat, lng: gcjLng};
	}

	var x = gcjLng, y = gcjLat;
	var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
	var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);
	var bdLng = z * Math.cos(theta) + 0.0065;
	var bdLat = z * Math.sin(theta) + 0.006;
	return {lat: bdLat, lng: bdLng};
}
exports.gcj2bd = gcj2bd;

function bd2gcj(bdLat, bdLng) {
	if (outOfChina(bdLat, bdLng)) {
		return {lat: bdLat, lng: bdLng};
	}

	var x = bdLng - 0.0065, y = bdLat - 0.006;
	var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
	var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);
	var gcjLng = z * Math.cos(theta);
	var gcjLat = z * Math.sin(theta);
	return {lat: gcjLat, lng: gcjLng};
}
exports.bd2gcj = bd2gcj;

function wgs2bd(wgsLat, wgsLng) {
	var gcj = wgs2gcj(wgsLat, wgsLng);
	return gcj2bd(gcj.lat, gcj.lng);
}
exports.wgs2bd = wgs2bd;

function bd2wgs(bdLat, bdLng) {
	var gcj = bd2gcj(bdLat, bdLng);
	return gcj2wgs(gcj.lat, gcj.lng);
}
exports.bd2wgs = bd2wgs;
/**
 * Projection class for Baidu Spherical Mercator
 *
 * @class BaiduSphericalMercator
 */
L.Projection.GCJ02SphericalMercator = {
    /**
     * Project latLng to point coordinate
     *
     * @method project
     * @param {Object} latLng coordinate for a point on earth
     * @return {Object} leafletPoint point coordinate of L.Point
     */
    project: function(latLng) {
        //1.gcj02 to wgs84 lat lon
        //2.wgs84 lat lon to point
        var wgs84_latlon = gcj2wgs(latLng.lat, latLng.lng)
        // var MAX_LATITUDE = 85.0511287798;
        // var R = 6378137;
        // var d = Math.PI/ 180;
        // var max = MAX_LATITUDE;
        // var lat = Math.max(Math.min(max, wgs84_latlon.lat), -max);
        // var sin = Math.sin(lat * d);

        // var x = R *  wgs84_latlon.lng * d;
        // var y = R * Math.log((1 + sin) / (1 - sin)) / 2;

        var x = wgs84_latlon.lng * 20037508.34 / 180;
        var y = Math.log(Math.tan((90 + wgs84_latlon.lat) * Math.PI / 360)) / (Math.PI / 180);
        y = y * 20037508.34 / 180;

        var leafletPoint = new L.Point(x, y);
        return leafletPoint;

    },

    /**
     * unproject point coordinate to latLng
     *
     * @method unproject
     * @param {Object} bpoint baidu point coordinate
     * @return {Object} latitude and longitude
     */
    unproject: function (bpoint) {
        //1. x,y to wgs84 lat lon
        //2. wgs84 to gcj02 lat lon
        // var R = 6378137;
        // var d = 180 / Math.PI;
        // var lng = bpoint.x * d / R;
        // var lat = (2 * Math.atan(Math.exp(bpoint.y / R)) - (Math.PI / 2)) * d;

        var lng = (bpoint.x / 20037508.34) * 180;
        var lat = (bpoint.y / 20037508.34) * 180;

        lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

        gcj02_latlon = wgs2gcj(lat, lng);
        var latLng = new L.LatLng(gcj02_latlon.lat, gcj02_latlon.lng);
        return latLng;
    },

    /**
     * Don't know how it used currently.
     *
     * However, I guess this is the range of coordinate.
     * Range of pixel coordinate is gotten from
     * BMap.MercatorProjection.lngLatToPoint(180, -90) and (180, 90)
     * After getting max min value of pixel coordinate, use
     * pointToLngLat() get the max lat and Lng.
     */
    // bounds: (function () {
    //     var MAX_X= 20037726.37;
    //     var MIN_Y= -11708041.66;
    //     var MAX_Y= 12474104.17;
    //     var bounds = L.bounds(
    //         [-MAX_X, MIN_Y], //180, -71.988531
    //         [MAX_X, MAX_Y]  //-180, 74.000022
    //     );
    //     return bounds;
    // })()
};

L.GCJ02Transformation = L.extend({}, L.Transformation, {
  MAXZOOM: 30,
  /**
   * Don't know how it used currently.
   */
  transform: function (point, zoom) {
      return this._transform(point.clone(), zoom);
  },

  /**
   * transform point coordinate to pixel coordinate
   *
   * @method _transform
   * @param {Object} point point coordinate
   * @param {Number} zoom zoom level of the map
   * @return {Object} point, pixel coordinate
   */
  _transform: function (point, zoom) {
      point.x = point.x >> (this.MAXZOOM - zoom);
      point.y = point.y >> (this.MAXZOOM - zoom);
      return point;
  },

  /**
   * transform pixel coordinate to point coordinate
   *
   * @method untransform
   * @param {Object} point pixel coordinate
   * @param {Number} zoom zoom level of the map
   * @return {Object} point, point coordinate
   */
  untransform: function (point, zoom) {
      point.x = point.x << (this.MAXZOOM - zoom);
      point.y = point.y << (this.MAXZOOM - zoom);
      return point;
  }
});

/**
 * Coordinate system for Baidu EPSG3857
 *
 * @class BEPSG3857
 */
L.CRS.GCJ02 = L.extend({}, L.CRS, {
    /**
     * transform latLng to pixel coordinate
     *
     * @method untransform
     * @param {Object} latlng latitude and longitude
     * @param {Number} zoom zoom level of the map
     * @return {Object} pixel coordinate calculated for latLng
     */
    latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
        var projectedPoint = this.projection.project(latlng);
        return this.transformation._transform(projectedPoint, zoom);
    },

    /**
     * transform pixel coordinate to latLng
     *
     * @method untransform
     * @param {Object} point pixel coordinate
     * @param {Number} zoom zoom level of the map
     * @return {Object} latitude and longitude
     */
    pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
        var untransformedPoint = this.transformation.untransform(point, zoom);
        return this.projection.unproject(untransformedPoint);
    },

    code: 'EPSG:3857',
    projection: new L.Projection.GCJ02SphericalMercator(),

    transformation: new L.GCJ02Transformation()
});
<|endoftext|>


<commit_before>const BinaryRingBuffer = require('./BinaryRingBuffer');

describe('Binary ring buffer reading and writing', function () {
    it('simple byte write and read', function () {
        let buf = new BinaryRingBuffer();
        let expected = [3, 95, 0, 255, 9, 64];

        expected.forEach(v => {
            buf.writeBits(v, 8);
            expect(buf.readBits(8)).toEqual(v);
        });
    });

    it('simple bits write and read', function () {
        let buf = new BinaryRingBuffer();
        let expected = [[3, 3], [1, 3], [250, 8], [1, 1], [63, 6], [7, 5], [3, 3]];

        expected.forEach(v => {
            buf.writeBits(v[0], v[1]);
            expect(buf.readBits(v[1])).toEqual(v[0]);
        });
    });

    it('larger than one byte write and read', function () {
        let buf = new BinaryRingBuffer();
        let expected = [[38, 6], [0, 2], [1023, 10], [255, 8], [0, 17], [10, 4], [256, 9]];

        expected.forEach(v => {
            buf.writeBits(v[0], v[1]);
            expect(buf.readBits(v[1])).toEqual(v[0]);
        });
    });

    it('read multiple writes', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(1, 1);
        buf.writeBits(0, 1);
        buf.writeBits(1, 1);
        buf.writeBits(0, 1);
        expect(buf.readBits(4)).toEqual(10);

        buf.writeBits(15, 4);
        buf.writeBits(15, 4);
        expect(buf.readBits(8)).toEqual(255);

        buf.writeBits(0, 4);
        buf.writeBits(15, 4);
        buf.writeBits(15, 4);
        expect(buf.readBits(12)).toEqual(255);
    });

    it('read over multiple full bytes', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(6, 3);
        buf.readBits(3);
        buf.writeBits((1 << 16) - 1, 16);
        buf.writeBits((1 << 16) - 1, 16);
        expect(buf.readBits(30)).toEqual((1 << 30) - 1);
    });

    it('capacity is the same after many reads and writes', function () {
        let buf = new BinaryRingBuffer();
        let cap0 = buf.cap;
        let bitsPerOp = 3;
        let bits = 1000;
        while (bits > 0) {
            buf.writeBits(5, bitsPerOp);
            let readValue = buf.readBits(bitsPerOp);
            expect(readValue).toEqual(5);
            bits -= bitsPerOp;
        }
        expect(buf.size()).toEqual(0);
        expect(buf.cap).toEqual(cap0);
    });

    it('wrap around does not alter written values', function () {
        let buf = new BinaryRingBuffer(1);
        buf.writeBits(0, 2);
        buf.readBits(2);
        buf.writeBits(127, 7);
        expect(buf.readBits(7)).toEqual(127);
        buf.writeBits(255, 8);
        expect(buf.readBits(8)).toEqual(255);
        buf.writeBits(5, 3);
        buf.writeBits(5, 3);
        expect(buf.readBits(6)).toEqual(45);
    });

    it('can dynamically increase size', function () {
        let buf = new BinaryRingBuffer(1);
        buf.writeBits(0, 8 * 1024);

        buf = new BinaryRingBuffer(1);
        buf.writeBits(1, 3);
        buf.writeBits(1, 3);
        expect(buf.readBits(3)).toEqual(1);
        buf.writeBits(1, 3);
        buf.writeBits(1, 3);
        expect(buf.readBits(3)).toEqual(1);
        buf.writeBits(1, 3);
        expect(buf.readBits(3)).toEqual(1);
        expect(buf.readBits(3)).toEqual(1);

        buf = new BinaryRingBuffer(1);
        let array = [];
        for (let i = 0; i < 1000; i++) {
            let d = Math.random() * 8 | 0;
            array.push(d);
            array.push(d);
            buf.writeBits(d, 3);
            buf.writeBits(d, 3);
            let v = buf.readBits(3);
            expect(v).toEqual(array.shift());
        }
    });

    it('read 16 bit int', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(0, 3);
        buf.readBits(3);

        buf.writeBits(Math.pow(2, 16) - 1, 16);
        expect(buf.readBits(16)).toEqual(Math.pow(2, 16) - 1);
    });

    it('read 32 bit int', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(0, 3);
        buf.readBits(3);

        buf.writeBits(Math.pow(2, 32) - 1, 32);
        expect(buf.readBits(32)).toEqual(Math.pow(2, 32) - 1);
    });

    it('read 64 bit int', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(0, 5);
        buf.readBits(5);

        // TODO: support accurate writing past 53 bits
        // buf.writeBits(Math.pow(2, 64) - 1, 64);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(15, 4);

        // Note we lose precision here but not accuracy
        expect(buf.readBits(64)).toEqual(Math.pow(2, 64));
    });
});

describe('Peak read', function () {
    it('peak does not move', function () {
        // write 0xFF00
        let buf = new BinaryRingBuffer(2);
        buf.writeBits(255, 8);
        buf.writeBits(0, 8);

        // Peak first 6 bits
        expect(buf.peakBits(6)).toEqual(63);
        let view = buf.viewArray();
        expect(view.cursors).toEqual('R0000000,00000000');

        // Read should have same result
        expect(buf.readBits(6)).toEqual(63);
        view = buf.viewArray();
        expect(view.cursors).toEqual('W00000R0,00000000');

        // now moved
        expect(buf.peakBits(3)).toEqual(6);
        view = buf.viewArray();
        expect(view.cursors).toEqual('W00000R0,00000000');
    });
});

describe('View array helper', function () {
    it('all ones in a single byte', function () {
        let buf = new BinaryRingBuffer(1);
        buf.writeBits(255, 8);
        let view = buf.viewArray();
        expect(view.array).toEqual('11111111');
        expect(view.cursors).toEqual('R0000000');
    });
    it('multiple bytes and different R/W cursors', function () {
        let buf = new BinaryRingBuffer(3);
        buf.writeBits(1, 8);
        buf.writeBits(1, 8);
        let view = buf.viewArray();
        expect(view.array).toEqual('00000001,00000001,00000000');
        expect(view.cursors).toEqual('R0000000,00000000,W0000000');
    });
});<commit_msg>Simple test of clearing buffer<commit_after>const BinaryRingBuffer = require('./BinaryRingBuffer');

describe('Binary ring buffer reading and writing', function () {
    it('simple byte write and read', function () {
        let buf = new BinaryRingBuffer();
        let expected = [3, 95, 0, 255, 9, 64];

        expected.forEach(v => {
            buf.writeBits(v, 8);
            expect(buf.readBits(8)).toEqual(v);
        });
    });

    it('simple bits write and read', function () {
        let buf = new BinaryRingBuffer();
        let expected = [[3, 3], [1, 3], [250, 8], [1, 1], [63, 6], [7, 5], [3, 3]];

        expected.forEach(v => {
            buf.writeBits(v[0], v[1]);
            expect(buf.readBits(v[1])).toEqual(v[0]);
        });
    });

    it('larger than one byte write and read', function () {
        let buf = new BinaryRingBuffer();
        let expected = [[38, 6], [0, 2], [1023, 10], [255, 8], [0, 17], [10, 4], [256, 9]];

        expected.forEach(v => {
            buf.writeBits(v[0], v[1]);
            expect(buf.readBits(v[1])).toEqual(v[0]);
        });
    });

    it('read multiple writes', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(1, 1);
        buf.writeBits(0, 1);
        buf.writeBits(1, 1);
        buf.writeBits(0, 1);
        expect(buf.readBits(4)).toEqual(10);

        buf.writeBits(15, 4);
        buf.writeBits(15, 4);
        expect(buf.readBits(8)).toEqual(255);

        buf.writeBits(0, 4);
        buf.writeBits(15, 4);
        buf.writeBits(15, 4);
        expect(buf.readBits(12)).toEqual(255);
    });

    it('read over multiple full bytes', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(6, 3);
        buf.readBits(3);
        buf.writeBits((1 << 16) - 1, 16);
        buf.writeBits((1 << 16) - 1, 16);
        expect(buf.readBits(30)).toEqual((1 << 30) - 1);
    });

    it('capacity is the same after many reads and writes', function () {
        let buf = new BinaryRingBuffer();
        let cap0 = buf.cap;
        let bitsPerOp = 3;
        let bits = 1000;
        while (bits > 0) {
            buf.writeBits(5, bitsPerOp);
            let readValue = buf.readBits(bitsPerOp);
            expect(readValue).toEqual(5);
            bits -= bitsPerOp;
        }
        expect(buf.size()).toEqual(0);
        expect(buf.cap).toEqual(cap0);
    });

    it('wrap around does not alter written values', function () {
        let buf = new BinaryRingBuffer(1);
        buf.writeBits(0, 2);
        buf.readBits(2);
        buf.writeBits(127, 7);
        expect(buf.readBits(7)).toEqual(127);
        buf.writeBits(255, 8);
        expect(buf.readBits(8)).toEqual(255);
        buf.writeBits(5, 3);
        buf.writeBits(5, 3);
        expect(buf.readBits(6)).toEqual(45);
    });

    it('can dynamically increase size', function () {
        let buf = new BinaryRingBuffer(1);
        buf.writeBits(0, 8 * 1024);

        buf = new BinaryRingBuffer(1);
        buf.writeBits(1, 3);
        buf.writeBits(1, 3);
        expect(buf.readBits(3)).toEqual(1);
        buf.writeBits(1, 3);
        buf.writeBits(1, 3);
        expect(buf.readBits(3)).toEqual(1);
        buf.writeBits(1, 3);
        expect(buf.readBits(3)).toEqual(1);
        expect(buf.readBits(3)).toEqual(1);

        buf = new BinaryRingBuffer(1);
        let array = [];
        for (let i = 0; i < 1000; i++) {
            let d = Math.random() * 8 | 0;
            array.push(d);
            array.push(d);
            buf.writeBits(d, 3);
            buf.writeBits(d, 3);
            let v = buf.readBits(3);
            expect(v).toEqual(array.shift());
        }
    });

    it('read 16 bit int', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(0, 3);
        buf.readBits(3);

        buf.writeBits(Math.pow(2, 16) - 1, 16);
        expect(buf.readBits(16)).toEqual(Math.pow(2, 16) - 1);
    });

    it('read 32 bit int', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(0, 3);
        buf.readBits(3);

        buf.writeBits(Math.pow(2, 32) - 1, 32);
        expect(buf.readBits(32)).toEqual(Math.pow(2, 32) - 1);
    });

    it('read 64 bit int', function () {
        let buf = new BinaryRingBuffer();
        buf.writeBits(0, 5);
        buf.readBits(5);

        // TODO: support accurate writing past 53 bits
        // buf.writeBits(Math.pow(2, 64) - 1, 64);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(1023, 10);
        buf.writeBits(15, 4);

        // Note we lose precision here but not accuracy
        expect(buf.readBits(64)).toEqual(Math.pow(2, 64));
    });
});

describe('Buffer clear', function () {
    it('does do not grow at all when clearing', function () {
        buf = new BinaryRingBuffer(1);
        let array = [];
        for (let i = 0; i < 1000; i++) {
            let d = Math.floor(Math.random() * 32);
            buf.writeBits(d, 5);
            expect(buf.size()).toEqual(5);
            buf.clear();
            expect(buf.size()).toEqual(0);
            expect(buf.cap).toEqual(8);
        }
    });
});

describe('Peak read', function () {
    it('peak does not move', function () {
        // write 0xFF00
        let buf = new BinaryRingBuffer(2);
        buf.writeBits(255, 8);
        buf.writeBits(0, 8);

        // Peak first 6 bits
        expect(buf.peakBits(6)).toEqual(63);
        let view = buf.viewArray();
        expect(view.cursors).toEqual('R0000000,00000000');

        // Read should have same result
        expect(buf.readBits(6)).toEqual(63);
        view = buf.viewArray();
        expect(view.cursors).toEqual('W00000R0,00000000');

        // now moved
        expect(buf.peakBits(3)).toEqual(6);
        view = buf.viewArray();
        expect(view.cursors).toEqual('W00000R0,00000000');
    });
});

describe('View array helper', function () {
    it('all ones in a single byte', function () {
        let buf = new BinaryRingBuffer(1);
        buf.writeBits(255, 8);
        let view = buf.viewArray();
        expect(view.array).toEqual('11111111');
        expect(view.cursors).toEqual('R0000000');
    });
    it('multiple bytes and different R/W cursors', function () {
        let buf = new BinaryRingBuffer(3);
        buf.writeBits(1, 8);
        buf.writeBits(1, 8);
        let view = buf.viewArray();
        expect(view.array).toEqual('00000001,00000001,00000000');
        expect(view.cursors).toEqual('R0000000,00000000,W0000000');
    });
});<|endoftext|>


<commit_before>var os = require('os');

var sysInfoBtn = document.getElementById('sys-info');
var homeDir = os.homedir();

sysInfoBtn.addEventListener('click', function () {
  var message = 'Your system home directory is: ' + homeDir;
  document.getElementById('got-sys-info').innerHTML = message;
});
<commit_msg>nodey stuff first, then selectors<commit_after>var os = require('os');
var homeDir = os.homedir();
var sysInfoBtn = document.getElementById('sys-info');

sysInfoBtn.addEventListener('click', function () {
  var message = 'Your system home directory is: ' + homeDir;
  document.getElementById('got-sys-info').innerHTML = message;
});
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('unregistered-contributor-form', 'Integration | Component | unregistered contributor form', {
    integration: true
});

let noop = () => {};

test('form renders 11111111', function(assert) {
    // Tests that the unregistered-contirbutor form renders

    this.set('resetfindContributorsView', noop);
    this.set('addUnregisteredContributor', noop);
    this.render(hbs`{{unregistered-contributor-form
                       resetfindContributorsView=resetfindContributorsView
                       addUnregisteredContributor=addUnregisteredContributor}}`);

    assert.equal(this.$('label')[0].textContent.trim(), 'Full Name');
    assert.equal(this.$('label')[1].textContent.trim(), 'Email');
    assert.equal(this.$('p').text(), 'We will notify the user that they have been added to your preprint.');
    assert.equal(this.$('button')[0].textContent.trim(), 'Cancel');
    assert.equal(this.$('button')[1].textContent.trim(), 'Add');
});

test('cancel unregistered contributor form 11111111', function(assert) {
    // Tests that the cancel button properly works to reset the contributor form

    this.set('resetfindContributorsView', function() {
        this.$('input[name=fullName]').val("");
        this.$('input[name=username]').val("");
    });
    this.set('addUnregisteredContributor', noop);
    this.set('model', this);
    this.set('valuePath', 'username');
    this.set('placeholder', 'Email');
    this.set('value', '');

    // Renders the handlebars template with variables for inline 'validated-input' component
    this.render(hbs `{{unregistered-contributor-form
                        resetfindContributorsView=resetfindContributorsView
                        addUnregisteredContributor=addUnregisteredContributor
                        model=model
                        valuePath=valuePath
                        placeholder=placeholder
                        value=value}}`);

    // Changes the value of the input boxes
    this.$('input[name=fullName]').val('Tester Test');
    this.$('input[name=username]').val('test@test.com');

    // Checks the before value of the input boxes
    assert.equal(this.$('input[name=fullName]').val(), "Tester Test", 'value of input has name before button click');
    assert.equal(this.$('input[name=username]').val(), "test@test.com", 'value of input has email before button click');

    // Clicks the 'cancel' button
    this.$('button')[0].click();

    // Checks the final value of the input boxes
    assert.equal(this.$('input[name=fullName]').val(), "", 'value of input is blank after button click');
    assert.equal(this.$('input[name=username]').val(), "", 'value of input is blank after button click');

});

test('add unregistered contributor 11111111', function(assert) {
    // Tests that the unregistered contributor is added on submit

    function addUnregisteredContributor(component) {
        component.$('input[name=fullName]').val("");
        component.$('input[name=username]').val("");
    }
    this.set('resetfindContributorsView', noop);
    this.set('addUnregisteredContributor', noop);
    this.set('model', this);
    this.set('valuePath', 'username');
    this.set('placeholder', 'Email');
    this.set('value', '');
    this.render(hbs `{{unregistered-contributor-form
                        resetfindContributorsView=resetfindContributorsView
                        addUnregisteredContributor=addUnregisteredContributor
                        model=model
                        valuePath=valuePath
                        placeholder=placeholder
                        value=value
                        addUnregistered='assertUnregistered'}}`);

    // Changes the value of the input boxes
    this.$('input[name=fullName]').val("Tester Test");
    this.$('input[name=username]').val("test@test.com");

    // Checks the before value of the input boxes
    assert.equal(this.$('input[name=fullName]').val(), "Tester Test", 'value of name input box before submit button click');
    assert.equal(this.$('input[name=username]').val(), "test@test.com", 'value of email input box before submit button click');

    this.on('assertUnregistered', addUnregisteredContributor(this));

    // Clicks the submit button
    this.$('button')[1].click();

    // Chekcs the after value of the input boxes
    assert.equal(this.$('input[name=fullName]').val(), "", 'value of name input box after submit button is clicked');
    assert.equal(this.$('input[name=username]').val(), "", 'value of email input box after submit button is clicked');

});
<commit_msg>Updated unregistered-contributor-form-test<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('unregistered-contributor-form', 'Integration | Component | unregistered contributor form', {
    integration: true
});

let noop = () => {};

test('form renders', function(assert) {
    // Tests that the unregistered-contirbutor form renders

    this.set('resetfindContributorsView', noop);
    this.set('addUnregisteredContributor', noop);
    this.render(hbs`{{unregistered-contributor-form
                       resetfindContributorsView=resetfindContributorsView
                       addUnregisteredContributor=addUnregisteredContributor}}`);

    assert.equal(this.$('label')[0].textContent.trim(), 'Full Name');
    assert.equal(this.$('label')[1].textContent.trim(), 'Email');
    assert.equal(this.$('p').text(), 'We will notify the user that they have been added to your preprint.');
    assert.equal(this.$('button')[0].textContent.trim(), 'Cancel');
    assert.equal(this.$('button')[1].textContent.trim(), 'Add');
});

test('cancel unregistered contributor form', function(assert) {
    // Tests that the cancel button properly works to reset the contributor form

    this.set('resetfindContributorsView', function() {
        this.$('input[name=fullName]').val("");
        this.$('input[name=username]').val("");
    });
    this.set('addUnregisteredContributor', noop);
    this.set('model', this);
    this.set('valuePath', 'username');
    this.set('placeholder', 'Email');
    this.set('value', '');

    // Renders the handlebars template with variables for inline 'validated-input' component
    this.render(hbs `{{unregistered-contributor-form
                        resetfindContributorsView=resetfindContributorsView
                        addUnregisteredContributor=addUnregisteredContributor
                        model=model
                        valuePath=valuePath
                        placeholder=placeholder
                        value=value}}`);

    // Changes the value of the input boxes
    this.$('input[name=fullName]').val('Tester Test');
    this.$('input[name=username]').val('test@test.com');

    // Checks the before value of the input boxes
    assert.equal(this.$('input[name=fullName]').val(), "Tester Test", 'value of input has name before button click');
    assert.equal(this.$('input[name=username]').val(), "test@test.com", 'value of input has email before button click');

    // Clicks the 'cancel' button
    this.$('button')[0].click();

    // Checks the final value of the input boxes
    assert.equal(this.$('input[name=fullName]').val(), "", 'value of input is blank after button click');
    assert.equal(this.$('input[name=username]').val(), "", 'value of input is blank after button click');

});

test('add unregistered contributor', function(assert) {
    // Tests that the unregistered contributor is added on submit

    function addUnregisteredContributor(component) {
        component.$('input[name=fullName]').val("");
        component.$('input[name=username]').val("");
    }
    this.set('resetfindContributorsView', noop);
    this.set('addUnregisteredContributor', noop);
    this.set('model', this);
    this.set('valuePath', 'username');
    this.set('placeholder', 'Email');
    this.set('value', '');
    this.render(hbs `{{unregistered-contributor-form
                        resetfindContributorsView=resetfindContributorsView
                        addUnregisteredContributor=addUnregisteredContributor
                        model=model
                        valuePath=valuePath
                        placeholder=placeholder
                        value=value
                        addUnregistered='assertUnregistered'}}`);

    // Changes the value of the input boxes
    this.$('input[name=fullName]').val("Tester Test");
    this.$('input[name=username]').val("test@test.com");

    // Checks the before value of the input boxes
    assert.equal(this.$('input[name=fullName]').val(), "Tester Test", 'value of name input box before submit button click');
    assert.equal(this.$('input[name=username]').val(), "test@test.com", 'value of email input box before submit button click');

    this.on('assertUnregistered', addUnregisteredContributor(this));

    // Clicks the submit button
    this.$('button')[1].click();

    // Chekcs the after value of the input boxes
    assert.equal(this.$('input[name=fullName]').val(), "", 'value of name input box after submit button is clicked');
    assert.equal(this.$('input[name=username]').val(), "", 'value of email input box after submit button is clicked');

});
<|endoftext|>


<commit_before>module.exports = function ( grunt ) {

	// load NPM tasks
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-cssmin');

	var packages = [];
	var admin = grunt.file.readJSON( 'admin.json' );
	var cp = require( 'child_process' );
	var pathInfo = {
		source: '../src/',
		lib: '../lib/',
		dist: '../grunt-dist/',
		repo: 'http://j4f.jnw.io/repository'
	};

	grunt.initConfig( {
		path: pathInfo,
		pkg: grunt.file.readJSON( 'package.json' ),
		clean: {
			options: {
				force: true
			},
			build: [ '<%= path.dist %>' ]
		},
		copy: {
			lib: {
				files: [ {
					expand: true,
					src: [ '<%= path.lib %>**' ],
					dest: '<%= path.dist %>lib'
				} ]
			},
			src: {
				files: [
					{
						expand: true,
						src: [
							'<%= path.source %>**',
							'!<%= path.source %>style/**',
							'<%= path.source %>style/**/package.json',
							'!<%= path.source %>style/bootstrap3/package.json'
						],
						dest: '<%= path.dist %>src'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-dark/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-white/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-wireframe/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-cerulean/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-flatly/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-united/images'
					}
				]
			}
		},
		uglify: {
			options: {
				banner: grunt.file.read( './copyright.txt', { encoding: 'UTF-8' } )
			},
			minify: {
				files: [ {
					expand: true,
					src: [ '<%= path.dist %>src/**/*.js', '!<%= path.dist %>src/style/**/*.js' ]
				} ]
			}
		},
		less: {
			compile: {
				files: [
					{
						'<%= path.dist %>src/style/theme-dark/cornerstone.css': '<%= path.source %>style/theme-dark/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/theme-white/cornerstone.css': '<%= path.source %>style/theme-white/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/theme-wireframe/cornerstone.css': '<%= path.source %>style/theme-wireframe/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/skin-cerulean/cerulean.css': '<%= path.source %>style/skin-cerulean/cerulean.less'
					},
					{
						'<%= path.dist %>src/style/skin-flatly/flatly.css': '<%= path.source %>style/skin-flatly/flatly.less'
					},
					{
						'<%= path.dist %>src/style/skin-united/united.css': '<%= path.source %>style/skin-united/united.less'
					}
				]
			}
		},
		cssmin: {
			options: {
				banner: grunt.file.read( './copyright.txt', { encoding: 'UTF-8' } )
			},
			minify: {
				files: [
					{
						'<%= path.dist %>src/style/theme-dark/cornerstone.css': '<%= path.dist %>src/style/theme-dark/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/theme-white/cornerstone.css': '<%= path.dist %>src/style/theme-white/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/theme-wireframe/cornerstone.css': '<%= path.dist %>src/style/theme-wireframe/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/skin-cerulean/cerulean.css': '<%= path.dist %>src/style/skin-cerulean/cerulean.css'
					},
					{
						'<%= path.dist %>src/style/skin-flatly/flatly.css': '<%= path.dist %>src/style/skin-flatly/flatly.css'
					},
					{
						'<%= path.dist %>src/style/skin-united/united.css': '<%= path.dist %>src/style/skin-united/united.css'
					}
				]
			}
		}
	} );

	grunt.registerTask( 'findPackages', function () {
		grunt.file.recurse( pathInfo.dist, function callback( abspath, rootdir, subdir, filename ) {
			if ( filename == 'package.json' ) packages.push( rootdir + subdir );
		} );
	} );

	grunt.registerTask( 'upload', function () {
		this.async();
		packages.forEach( function ( packageDir ) {
			var child = cp.exec( 'jam publish ' + packageDir + ' --force --repository ' + pathInfo.repo, function( err, stdout, stderr ) {
				process.exit( 0 );
			} );

			child.stdin.setEncoding( 'utf-8' );
			child.stdout.pipe( process.stdout );

			child.stdout.on( 'data', function( chunk ) {
				if ( chunk.substr( -10 ) == 'Username: ' )
					child.stdin.write( admin.id + '\n' );
				else if ( chunk.substr( -10 ) == 'Password: ' )
					child.stdin.write( admin.pass + '\n' );
			} );
		} );
	} );

	grunt.registerTask( 'test', [ 'findPackages', 'upload' ] );
	grunt.registerTask( 'publish', [ 'clean', 'copy', 'uglify', 'less', 'cssmin' ] );
	grunt.registerTask( 'default', [ 'publish' ] );
}<commit_msg>child_process.exec callback 제거<commit_after>module.exports = function ( grunt ) {

	// load NPM tasks
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-cssmin');

	var packages = [];
	var admin = grunt.file.readJSON( 'admin.json' );
	var cp = require( 'child_process' );
	var pathInfo = {
		source: '../src/',
		lib: '../lib/',
		dist: '../grunt-dist/',
		repo: 'http://j4f.jnw.io/repository'
	};

	grunt.initConfig( {
		path: pathInfo,
		pkg: grunt.file.readJSON( 'package.json' ),
		clean: {
			options: {
				force: true
			},
			build: [ '<%= path.dist %>' ]
		},
		copy: {
			lib: {
				files: [ {
					expand: true,
					src: [ '<%= path.lib %>**' ],
					dest: '<%= path.dist %>lib'
				} ]
			},
			src: {
				files: [
					{
						expand: true,
						src: [
							'<%= path.source %>**',
							'!<%= path.source %>style/**',
							'<%= path.source %>style/**/package.json',
							'!<%= path.source %>style/bootstrap3/package.json'
						],
						dest: '<%= path.dist %>src'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-dark/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-white/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-wireframe/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-cerulean/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-flatly/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-united/images'
					}
				]
			}
		},
		uglify: {
			options: {
				banner: grunt.file.read( './copyright.txt', { encoding: 'UTF-8' } )
			},
			minify: {
				files: [ {
					expand: true,
					src: [ '<%= path.dist %>src/**/*.js', '!<%= path.dist %>src/style/**/*.js' ]
				} ]
			}
		},
		less: {
			compile: {
				files: [
					{
						'<%= path.dist %>src/style/theme-dark/cornerstone.css': '<%= path.source %>style/theme-dark/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/theme-white/cornerstone.css': '<%= path.source %>style/theme-white/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/theme-wireframe/cornerstone.css': '<%= path.source %>style/theme-wireframe/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/skin-cerulean/cerulean.css': '<%= path.source %>style/skin-cerulean/cerulean.less'
					},
					{
						'<%= path.dist %>src/style/skin-flatly/flatly.css': '<%= path.source %>style/skin-flatly/flatly.less'
					},
					{
						'<%= path.dist %>src/style/skin-united/united.css': '<%= path.source %>style/skin-united/united.less'
					}
				]
			}
		},
		cssmin: {
			options: {
				banner: grunt.file.read( './copyright.txt', { encoding: 'UTF-8' } )
			},
			minify: {
				files: [
					{
						'<%= path.dist %>src/style/theme-dark/cornerstone.css': '<%= path.dist %>src/style/theme-dark/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/theme-white/cornerstone.css': '<%= path.dist %>src/style/theme-white/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/theme-wireframe/cornerstone.css': '<%= path.dist %>src/style/theme-wireframe/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/skin-cerulean/cerulean.css': '<%= path.dist %>src/style/skin-cerulean/cerulean.css'
					},
					{
						'<%= path.dist %>src/style/skin-flatly/flatly.css': '<%= path.dist %>src/style/skin-flatly/flatly.css'
					},
					{
						'<%= path.dist %>src/style/skin-united/united.css': '<%= path.dist %>src/style/skin-united/united.css'
					}
				]
			}
		}
	} );

	grunt.registerTask( 'findPackages', function () {
		grunt.file.recurse( pathInfo.dist, function callback( abspath, rootdir, subdir, filename ) {
			if ( filename == 'package.json' ) packages.push( rootdir + subdir );
		} );
	} );

	grunt.registerTask( 'upload', function () {
		this.async();
		packages.forEach( function ( packageDir ) {
			var child = cp.exec( 'jam publish ' + packageDir + ' --force --repository ' + pathInfo.repo );

			child.stdin.setEncoding( 'utf-8' );
			child.stdout.pipe( process.stdout );

			child.stdout.on( 'data', function( chunk ) {
				if ( chunk.substr( -10 ) == 'Username: ' )
					child.stdin.write( admin.id + '\n' );
				else if ( chunk.substr( -10 ) == 'Password: ' )
					child.stdin.write( admin.pass + '\n' );
			} );
		} );
	} );

	grunt.registerTask( 'test', [ 'findPackages', 'upload' ] );
	grunt.registerTask( 'publish', [ 'clean', 'copy', 'uglify', 'less', 'cssmin' ] );
	grunt.registerTask( 'default', [ 'publish' ] );
}<|endoftext|>