function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {

  if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';

  var isInfinity = !isFinite(number);
  var isZero = false;
  var numStr = Math.abs(number) + '',
      formattedText = '',
      parsedNumber;

  if (isInfinity) {
    formattedText = '\u221e';
  } else {
    parsedNumber = parse(numStr);

    roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);

    var digits = parsedNumber.d;
    var integerLen = parsedNumber.i;
    var exponent = parsedNumber.e;
    var decimals = [];
    isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);

    // pad zeros for small numbers
    while (integerLen < 0) {
      digits.unshift(0);
      integerLen++;
    }

    // extract decimals digits
    if (integerLen > 0) {
      decimals = digits.splice(integerLen, digits.length);
    } else {
      decimals = digits;
      digits = [0];
    }

    // format the integer digits with grouping separators
    var groups = [];
    if (digits.length >= pattern.lgSize) {
      groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
    }
    while (digits.length > pattern.gSize) {
      groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
    }
    if (digits.length) {
      groups.unshift(digits.join(''));
    }
    formattedText = groups.join(groupSep);

    // append the decimal digits
    if (decimals.length) {
      formattedText += decimalSep + decimals.join('');
    }

    if (exponent) {
      formattedText += 'e+' + exponent;
    }
  }
  if (number < 0 && !isZero) {
    return pattern.negPre + formattedText + pattern.negSuf;
  } else {
    return pattern.posPre + formattedText + pattern.posSuf;
  }
}

Format a number into a string
@param  {number} number       The number to format
@param  {{
minFrac, // the minimum number of digits required in the fraction part of the number
maxFrac, // the maximum number of digits required in the fraction part of the number
gSize,   // number of digits in each group of separated digits
lgSize,  // number of digits in the last group of digits before the decimal separator
negPre,  // the string to go in front of a negative number (e.g. `-` or `(`))
posPre,  // the string to go in front of a positive number
negSuf,  // the string to go after a negative number (e.g. `)`)
posSuf   // the string to go after a positive number
}} pattern
@param  {string} groupSep     The string to separate groups of number (e.g. `,`)
@param  {string} decimalSep   The string to act as the decimal separator (e.g. `.`)
@param  {[type]} fractionSize The size of the fractional part of the number
@return {string}              The number formatted as a string


function defaults(dst, src) {
  forEach(src, function(value, key) {
    if (!isDefined(dst[key])) {
      dst[key] = value;
    }
  });
}

function defaults ( dst , src ) { forEach ( src , function ( value , key ) { if ( ! isDefined ( dst [ key ] ) ) { dst [ key ] = value ; } } ) ; }

shallow copy over values from `src` that are not already specified on `dst`

shallow copy over values from src that are not already specified on dst


function(playAnimation) {
          if (!animationCompleted) {
            animationPaused = !playAnimation;
            if (timings.animationDuration) {
              var value = blockKeyframeAnimations(node, animationPaused);
              if (animationPaused) {
                temporaryStyles.push(value);
              } else {
                removeFromArray(temporaryStyles, value);
              }
            }
          } else if (animationPaused && playAnimation) {
            animationPaused = false;
            close();
          }
        }

function ( playAnimation ) { if ( ! animationCompleted ) { animationPaused = ! playAnimation ; if ( timings . animationDuration ) { var value = blockKeyframeAnimations ( node , animationPaused ) ; if ( animationPaused ) { temporaryStyles . push ( value ) ; } else { removeFromArray ( temporaryStyles , value ) ; } } } else if ( animationPaused && playAnimation ) { animationPaused = false ; close ( ) ; } }

even though we only pause keyframe animations here the pause flag will still happen when transitions are used. Only the transition will not be paused since that is not possible. If the animation ends when paused then it will not complete until unpaused or cancelled.

even though we only pause keyframe animations here the pause flag will still happen when transitions are used . Only the transition will not be paused since that is not possible . If the animation ends when paused then it will not complete until unpaused or cancelled .


function(scope, $element, attrs, ctrl, $transclude) {
      var previousElement, previousScope;
      scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
        if (previousElement) {
          $animate.leave(previousElement);
        }
        if (previousScope) {
          previousScope.$destroy();
          previousScope = null;
        }
        if (value || value === 0) {
          $transclude(function(clone, childScope) {
            previousElement = clone;
            previousScope = childScope;
            $animate.enter(clone, null, $element);
          });
        }
      });
    }

function ( scope , $element , attrs , ctrl , $transclude ) { var previousElement , previousScope ; scope . $watchCollection ( attrs . ngAnimateSwap || attrs [ 'for' ] , function ( value ) { if ( previousElement ) { $animate . leave ( previousElement ) ; } if ( previousScope ) { previousScope . $destroy ( ) ; previousScope = null ; } if ( value || value === 0 ) { $transclude ( function ( clone , childScope ) { previousElement = clone ; previousScope = childScope ; $animate . enter ( clone , null , $element ) ; } ) ; } } ) ; }

we use 600 here to ensure that the directive is caught before others


function($scope, element, attrs) {
        var src = attrs.ngMessagesInclude || attrs.src;
        $templateRequest(src).then(function(html) {
          if ($scope.$$destroyed) return;

          if (isString(html) && !html.trim()) {
            // Empty template - nothing to compile
            replaceElementWithMarker(element, src);
          } else {
            // Non-empty template - compile and link
            $compile(html)($scope, function(contents) {
              element.after(contents);
              replaceElementWithMarker(element, src);
            });
          }
        });
      }

we only require this for validation sake


function locale_locales__getSetGlobalLocale (key, values) {
        var data;
        if (key) {
            if (typeof values === 'undefined') {
                data = locale_locales__getLocale(key);
            }
            else {
                data = defineLocale(key, values);
            }

            if (data) {
                // moment.duration._locale = moment._locale = data;
                globalLocale = data;
            }
        }

        return globalLocale._abbr;
    }

This function will load locale and then set the global locale.  If no arguments are passed in, it will simply return the current global locale key.

This function will load locale and then set the global locale . If no arguments are passed in it will simply return the current global locale key .


function configFromString(config) {
        var matched = aspNetJsonRegex.exec(config._i);

        if (matched !== null) {
            config._d = new Date(+matched[1]);
            return;
        }

        configFromISO(config);
        if (config._isValid === false) {
            delete config._isValid;
            utils_hooks__hooks.createFromInputFallback(config);
        }
    }

function configFromString ( config ) { var matched = aspNetJsonRegex . exec ( config . _i ) ; if ( matched !== null ) { config . _d = new Date ( + matched [ 1 ] ) ; return ; } configFromISO ( config ) ; if ( config . _isValid === false ) { delete config . _isValid ; utils_hooks__hooks . createFromInputFallback ( config ) ; } }


function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) {
        if (thresholds[threshold] === undefined) {
            return false;
        }
        if (limit === undefined) {
            return thresholds[threshold];
        }
        thresholds[threshold] = limit;
        return true;
    }

This function allows you to set a threshold for relative time strings


function(element, parent, options) {
      options = options || {};

      $mdUtil.disableScrollAround._count = Math.max(0, $mdUtil.disableScrollAround._count || 0);
      $mdUtil.disableScrollAround._count++;

      if ($mdUtil.disableScrollAround._restoreScroll) {
        return $mdUtil.disableScrollAround._restoreScroll;
      }

      var body = $document[0].body;
      var restoreBody = disableBodyScroll();
      var restoreElement = disableElementScroll(parent);

      return $mdUtil.disableScrollAround._restoreScroll = function() {
        if (--$mdUtil.disableScrollAround._count <= 0) {
          restoreBody();
          restoreElement();
          delete $mdUtil.disableScrollAround._restoreScroll;
        }
      };

      /**
       * Creates a virtual scrolling mask to prevent touchmove, keyboard, scrollbar clicking,
       * and wheel events
       */
      function disableElementScroll(element) {
        element = angular.element(element || body);

        var scrollMask;

        if (options.disableScrollMask) {
          scrollMask = element;
        } else {
          scrollMask = angular.element(
            '
' +
            '

' +
            '
');
          element.append(scrollMask);
        }

        scrollMask.on('wheel', preventDefault);
        scrollMask.on('touchmove', preventDefault);

        return function restoreElementScroll() {
          scrollMask.off('wheel');
          scrollMask.off('touchmove');

          if (!options.disableScrollMask && scrollMask[0].parentNode ) {
            scrollMask[0].parentNode.removeChild(scrollMask[0]);
          }
        };

        function preventDefault(e) {
          e.preventDefault();
        }
      }

      // Converts the body to a position fixed block and translate it to the proper scroll position
      function disableBodyScroll() {
        var documentElement = $document[0].documentElement;

        var prevDocumentStyle = documentElement.style.cssText || '';
        var prevBodyStyle = body.style.cssText || '';

        var viewportTop = $mdUtil.getViewportTop();
        var clientWidth = body.clientWidth;
        var hasVerticalScrollbar = body.scrollHeight > body.clientHeight + 1;

        // Scroll may be set on  element (for example by overflow-y: scroll)
        // but Chrome is reporting the scrollTop position always on .
        // scrollElement will allow to restore the scrollTop position to proper target.
        var scrollElement = documentElement.scrollTop > 0 ? documentElement : body;

        if (hasVerticalScrollbar) {
          angular.element(body).css({
            position: 'fixed',
            width: '100%',
            top: -viewportTop + 'px'
          });
        }

        if (body.clientWidth < clientWidth) {
          body.style.overflow = 'hidden';
        }

        // This should be applied after the manipulation to the body, because
        // adding a scrollbar can potentially resize it, causing the measurement
        // to change.
        if (hasVerticalScrollbar) {
          documentElement.style.overflowY = 'scroll';
        }

        return function restoreScroll() {
          // Reset the inline style CSS to the previous.
          body.style.cssText = prevBodyStyle;
          documentElement.style.cssText = prevDocumentStyle;

          // The scroll position while being fixed
          scrollElement.scrollTop = viewportTop;
        };
      }

    }

// Scroll may be set on <html> element (for example by overflow-y: scroll)

// but Chrome is reporting the scrollTop position always on <body>.

Disables scroll around the passed parent element.
@param element Unused
@param {!Element|!angular.JQLite} parent Element to disable scrolling within.
Defaults to body if none supplied.
@param options Object of options to modify functionality
- disableScrollMask Boolean of whether or not to create a scroll mask element or
use the passed parent element.

Disables scroll around the passed parent element .


function sanitizeAndConfigure(scope, options) {
        var selectEl = element.find('md-select-menu');

        if (!options.target) {
          throw new Error($mdUtil.supplant(ERROR_TARGET_EXPECTED, [options.target]));
        }

        angular.extend(options, {
          isRemoved: false,
          target: angular.element(options.target), //make sure it's not a naked dom node
          parent: angular.element(options.parent),
          selectEl: selectEl,
          contentEl: element.find('md-content'),
          optionNodes: selectEl[0].getElementsByTagName('md-option')
        });
      }

function
sanitizeAndConfigure
(
scope
,
options
)
{
var
selectEl
=
element
.
find
(
'md-select-menu'
)
;
if
(
!
options
.
target
)
{
throw
new
Error
(
$mdUtil
.
supplant
(
ERROR_TARGET_EXPECTED
,
[
options
.
target
]
)
)
;
}
angular
.
extend
(
options
,
{
isRemoved
:
false
,
target
:
angular
.
element
(
options
.
target
)
,
//make sure it's not a naked dom node
parent
:
angular
.
element
(
options
.
parent
)
,
selectEl
:
selectEl
,
contentEl
:
element
.
find
(
'md-content'
)
,
optionNodes
:
selectEl
[
0
]
.
getElementsByTagName
(
'md-option'
)
}
)
;
}

Check for valid opts and set some sane defaults


function refreshPosition(item) {
      // Find the top of an item by adding to the offsetHeight until we reach the
      // content element.
      var current = item.element[0];
      item.top = 0;
      item.left = 0;
      item.right = 0;
      while (current && current !== contentEl[0]) {
        item.top += current.offsetTop;
        item.left += current.offsetLeft;
        if ( current.offsetParent ){
          item.right += current.offsetParent.offsetWidth - current.offsetWidth - current.offsetLeft; //Compute offsetRight
        }
        current = current.offsetParent;
      }
      item.height = item.element.prop('offsetHeight');

      var defaultVal = $mdUtil.floatingScrollbars() ? '0' : undefined;
      $mdUtil.bidi(item.clone, 'margin-left', item.left, defaultVal);
      $mdUtil.bidi(item.clone, 'margin-right', defaultVal, item.right);
    }

Find the `top` of an item relative to the content element, and also the height.

Find the top of an item relative to the content element and also the height .


function MdToastController($mdToast, $scope) {
    // For compatibility with AngularJS 1.6+, we should always use the $onInit hook in
    // interimElements. The $mdCompiler simulates the $onInit hook for all versions.
    this.$onInit = function() {
      var self = this;

      if (self.highlightAction) {
        $scope.highlightClasses = [
          'md-highlight',
          self.highlightClass
        ];
      }

      $scope.$watch(function() { return activeToastContent; }, function() {
        self.content = activeToastContent;
      });

      this.resolve = function() {
        $mdToast.hide( ACTION_RESOLVE );
      };
    };
  }

Controller for the Toast interim elements.
@ngInject

Controller for the Toast interim elements .


function positionDropdown () {
    if (!elements) {
      return $mdUtil.nextTick(positionDropdown, false, $scope);
    }

    var dropdownHeight = ($scope.dropdownItems || MAX_ITEMS) * ITEM_HEIGHT;

    var hrect  = elements.wrap.getBoundingClientRect(),
        vrect  = elements.snap.getBoundingClientRect(),
        root   = elements.root.getBoundingClientRect(),
        top    = vrect.bottom - root.top,
        bot    = root.bottom - vrect.top,
        left   = hrect.left - root.left,
        width  = hrect.width,
        offset = getVerticalOffset(),
        position = $scope.dropdownPosition,
        styles;

    // Automatically determine dropdown placement based on available space in viewport.
    if (!position) {
      position = (top > bot && root.height - top - MENU_PADDING < dropdownHeight) ? 'top' : 'bottom';
    }
    // Adjust the width to account for the padding provided by `md-input-container`
    if ($attrs.mdFloatingLabel) {
      left += INPUT_PADDING;
      width -= INPUT_PADDING * 2;
    }
    styles = {
      left:     left + 'px',
      minWidth: width + 'px',
      maxWidth: Math.max(hrect.right - root.left, root.right - hrect.left) - MENU_PADDING + 'px'
    };

    if (position === 'top') {
      styles.top       = 'auto';
      styles.bottom    = bot + 'px';
      styles.maxHeight = Math.min(dropdownHeight, hrect.top - root.top - MENU_PADDING) + 'px';
    } else {
      var bottomSpace = root.bottom - hrect.bottom - MENU_PADDING + $mdUtil.getViewportTop();

      styles.top       = (top - offset) + 'px';
      styles.bottom    = 'auto';
      styles.maxHeight = Math.min(dropdownHeight, bottomSpace) + 'px';
    }

    elements.$.scrollContainer.css(styles);
    $mdUtil.nextTick(correctHorizontalAlignment, false);

    /**
     * Calculates the vertical offset for floating label examples to account for ngMessages
     * @returns {number}
     */
    function getVerticalOffset () {
      var offset = 0;
      var inputContainer = $element.find('md-input-container');
      if (inputContainer.length) {
        var input = inputContainer.find('input');
        offset = inputContainer.prop('offsetHeight');
        offset -= input.prop('offsetTop');
        offset -= input.prop('offsetHeight');
        // add in the height left up top for the floating label text
        offset += inputContainer.prop('offsetTop');
      }
      return offset;
    }

    /**
     * Makes sure that the menu doesn't go off of the screen on either side.
     */
    function correctHorizontalAlignment () {
      var dropdown = elements.scrollContainer.getBoundingClientRect(),
          styles   = {};
      if (dropdown.right > root.right - MENU_PADDING) {
        styles.left = (hrect.right - dropdown.width) + 'px';
      }
      elements.$.scrollContainer.css(styles);
    }
  }

Calculates the dropdown's position and applies the new styles to the menu element
@returns {*}

Calculates the dropdown s position and applies the new styles to the menu element


function correctHorizontalAlignment () {
      var dropdown = elements.scrollContainer.getBoundingClientRect(),
          styles   = {};
      if (dropdown.right > root.right - MENU_PADDING) {
        styles.left = (hrect.right - dropdown.width) + 'px';
      }
      elements.$.scrollContainer.css(styles);
    }

function correctHorizontalAlignment ( ) { var dropdown = elements . scrollContainer . getBoundingClientRect ( ) , styles = { } ; if ( dropdown . right > root . right - MENU_PADDING ) { styles . left = ( hrect . right - dropdown . width ) + 'px' ; } elements . $ . scrollContainer . css ( styles ) ; }

Makes sure that the menu doesn't go off of the screen on either side.

Makes sure that the menu doesn t go off of the screen on either side .


function gatherElements () {

    var snapWrap = gatherSnapWrap();

    elements = {
      main:  $element[0],
      scrollContainer: $element[0].querySelector('.md-virtual-repeat-container'),
      scroller: $element[0].querySelector('.md-virtual-repeat-scroller'),
      ul:    $element.find('ul')[0],
      input: $element.find('input')[0],
      wrap:  snapWrap.wrap,
      snap:  snapWrap.snap,
      root:  document.body
    };

    elements.li   = elements.ul.getElementsByTagName('li');
    elements.$    = getAngularElements(elements);

    inputModelCtrl = elements.$.input.controller('ngModel');
  }

function gatherElements ( ) { var snapWrap = gatherSnapWrap ( ) ; elements = { main : $element [ 0 ] , scrollContainer : $element [ 0 ] . querySelector ( '.md-virtual-repeat-container' ) , scroller : $element [ 0 ] . querySelector ( '.md-virtual-repeat-scroller' ) , ul : $element . find ( 'ul' ) [ 0 ] , input : $element . find ( 'input' ) [ 0 ] , wrap : snapWrap . wrap , snap : snapWrap . snap , root : document . body } ; elements . li = elements . ul . getElementsByTagName ( 'li' ) ; elements . $ = getAngularElements ( elements ) ; inputModelCtrl = elements . $ . input . controller ( 'ngModel' ) ; }

Gathers all of the elements needed for this controller


function selectedItemChange (selectedItem, previousSelectedItem) {

    updateModelValidators();

    if (selectedItem) {
      getDisplayValue(selectedItem).then(function (val) {
        $scope.searchText = val;
        handleSelectedItemChange(selectedItem, previousSelectedItem);
      });
    } else if (previousSelectedItem && $scope.searchText) {
      getDisplayValue(previousSelectedItem).then(function(displayValue) {
        // Clear the searchText, when the selectedItem is set to null.
        // Do not clear the searchText, when the searchText isn't matching with the previous
        // selected item.
        if (angular.isString($scope.searchText)
          && displayValue.toString().toLowerCase() === $scope.searchText.toLowerCase()) {
          $scope.searchText = '';
        }
      });
    }

    if (selectedItem !== previousSelectedItem) announceItemChange();
  }

Handles changes to the selected item.
@param selectedItem
@param previousSelectedItem


function handleSearchText (searchText, previousSearchText) {
    ctrl.index = getDefaultIndex();

    // do nothing on init
    if (searchText === previousSearchText) return;

    updateModelValidators();

    getDisplayValue($scope.selectedItem).then(function (val) {
      // clear selected item if search text no longer matches it
      if (searchText !== val) {
        $scope.selectedItem = null;

        // trigger change event if available
        if (searchText !== previousSearchText) announceTextChange();

        // cancel results if search text is not long enough
        if (!isMinLengthMet()) {
          ctrl.matches = [];

          setLoading(false);
          reportMessages(false, ReportType.Count);

        } else {
          handleQuery();
        }
      }
    });

  }

Handles changes to the searchText property.
@param searchText
@param previousSearchText

Handles changes to the searchText property .


function keydown (event) {
    switch (event.keyCode) {
      case $mdConstant.KEY_CODE.DOWN_ARROW:
        if (ctrl.loading) return;
        event.stopPropagation();
        event.preventDefault();
        ctrl.index   = Math.min(ctrl.index + 1, ctrl.matches.length - 1);
        updateScroll();
        reportMessages(false, ReportType.Selected);
        break;
      case $mdConstant.KEY_CODE.UP_ARROW:
        if (ctrl.loading) return;
        event.stopPropagation();
        event.preventDefault();
        ctrl.index   = ctrl.index < 0 ? ctrl.matches.length - 1 : Math.max(0, ctrl.index - 1);
        updateScroll();
        reportMessages(false, ReportType.Selected);
        break;
      case $mdConstant.KEY_CODE.TAB:
        // If we hit tab, assume that we've left the list so it will close
        onListLeave();

        if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return;
        select(ctrl.index);
        break;
      case $mdConstant.KEY_CODE.ENTER:
        if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return;
        if (hasSelection()) return;
        event.stopPropagation();
        event.preventDefault();
        select(ctrl.index);
        break;
      case $mdConstant.KEY_CODE.ESCAPE:
        event.preventDefault(); // Prevent browser from always clearing input
        if (!shouldProcessEscape()) return;
        event.stopPropagation();

        clearSelectedItem();
        if ($scope.searchText && hasEscapeOption('clear')) {
          clearSearchText();
        }

        // Manually hide (needed for mdNotFound support)
        ctrl.hidden = true;

        if (hasEscapeOption('blur')) {
          // Force the component to blur if they hit escape
          doBlur(true);
        }

        break;
      default:
    }
  }


function getDisplayValue (item) {
    return $q.when(getItemText(item) || item).then(function(itemText) {
      if (itemText && !angular.isString(itemText)) {
        $log.warn('md-autocomplete: Could not resolve display value to a string. ' +
          'Please check the `md-item-text` attribute.');
      }

      return itemText;
    });

    /**
     * Getter function to invoke user-defined expression (in the directive)
     * to convert your object to a single string.
     */
    function getItemText (item) {
      return (item && $scope.itemText) ? $scope.itemText(getItemAsNameVal(item)) : null;
    }
  }

Returns the display value for an item.
@param item
@returns {*}


function updateScroll () {
    if (!elements.li[0]) return;
    var height = elements.li[0].offsetHeight,
        top = height * ctrl.index,
        bot = top + height,
        hgt = elements.scroller.clientHeight,
        scrollTop = elements.scroller.scrollTop;
    if (top < scrollTop) {
      scrollTo(top);
    } else if (bot > scrollTop + hgt) {
      scrollTo(bot - hgt);
    }
  }

function updateScroll ( ) { if ( ! elements . li [ 0 ] ) return ; var height = elements . li [ 0 ] . offsetHeight , top = height * ctrl . index , bot = top + height , hgt = elements . scroller . clientHeight , scrollTop = elements . scroller . scrollTop ; if ( top < scrollTop ) { scrollTo ( top ) ; } else if ( bot > scrollTop + hgt ) { scrollTo ( bot - hgt ) ; } }

Makes sure that the focused element is within view.

Makes sure that the focused element is within view .


function MdChipsCtrl ($scope, $attrs, $mdConstant, $log, $element, $timeout, $mdUtil,
                      $exceptionHandler) {
  /** @type {$timeout} **/
  this.$timeout = $timeout;

  /** @type {Object} */
  this.$mdConstant = $mdConstant;

  /** @type {angular.$scope} */
  this.$scope = $scope;

  /** @type {angular.$scope} */
  this.parent = $scope.$parent;

  /** @type {$mdUtil} */
  this.$mdUtil = $mdUtil;

  /** @type {$log} */
  this.$log = $log;

  /** @type {$exceptionHandler} */
  this.$exceptionHandler = $exceptionHandler;

  /** @type {$element} */
  this.$element = $element;

  /** @type {$attrs} */
  this.$attrs = $attrs;

  /** @type {angular.NgModelController} */
  this.ngModelCtrl = null;

  /** @type {angular.NgModelController} */
  this.userInputNgModelCtrl = null;

  /** @type {MdAutocompleteCtrl} */
  this.autocompleteCtrl = null;

  /** @type {Element} */
  this.userInputElement = null;

  /** @type {Array.<Object>} */
  this.items = [];

  /** @type {number} */
  this.selectedChip = -1;

  /** @type {string} */
  this.enableChipEdit = $mdUtil.parseAttributeBoolean($attrs.mdEnableChipEdit);

  /** @type {string} */
  this.addOnBlur = $mdUtil.parseAttributeBoolean($attrs.mdAddOnBlur);

  /**
   * The text to be used as the aria-label for the input.
   * @type {string}
   */
  this.inputAriaLabel = 'Chips input.';

  /**
   * Hidden hint text to describe the chips container. Used to give context to screen readers when
   * the chips are readonly and the input cannot be selected.
   *
   * @type {string}
   */
  this.containerHint = 'Chips container. Use arrow keys to select chips.';

  /**
   * Hidden hint text for how to delete a chip. Used to give context to screen readers.
   * @type {string}
   */
  this.deleteHint = 'Press delete to remove this chip.';

  /**
   * Hidden label for the delete button. Used to give context to screen readers.
   * @type {string}
   */
  this.deleteButtonLabel = 'Remove';

  /**
   * Model used by the input element.
   * @type {string}
   */
  this.chipBuffer = '';

  /**
   * Whether to use the transformChip expression to transform the chip buffer
   * before appending it to the list.
   * @type {boolean}
   */
  this.useTransformChip = false;

  /**
   * Whether to use the onAdd expression to notify of chip additions.
   * @type {boolean}
   */
  this.useOnAdd = false;

  /**
   * Whether to use the onRemove expression to notify of chip removals.
   * @type {boolean}
   */
  this.useOnRemove = false;

  /**
   * The ID of the chips wrapper which is used to build unique IDs for the chips and the aria-owns
   * attribute.
   *
   * Defaults to '_md-chips-wrapper-' plus a unique number.
   *
   * @type {string}
   */
  this.wrapperId = '';

  /**
   * Array of unique numbers which will be auto-generated any time the items change, and is used to
   * create unique IDs for the aria-owns attribute.
   *
   * @type {Array<number>}
   */
  this.contentIds = [];

  /**
   * The index of the chip that should have it's `tabindex` property set to `0` so it is selectable
   * via the keyboard.
   *
   * @type {number}
   */
  this.ariaTabIndex = null;

  /**
   * After appending a chip, the chip will be focused for this number of milliseconds before the
   * input is refocused.
   *
   * **Note:** This is **required** for compatibility with certain screen readers in order for
   * them to properly allow keyboard access.
   *
   * @type {number}
   */
  this.chipAppendDelay = DEFAULT_CHIP_APPEND_DELAY;

  /**
   * Collection of functions to call to un-register watchers
   *
   * @type {Array}
   */
  this.deRegister = [];

  this.init();
}

Controller for the MdChips component. Responsible for adding to and
removing from the list of chips, marking chips as selected, and binding to
the models of various input components.

@param $scope
@param $attrs
@param $mdConstant
@param $log
@param $element
@param $timeout
@param $mdUtil
@param $exceptionHandler
@constructor

Controller for the MdChips component . Responsible for adding to and removing from the list of chips marking chips as selected and binding to the models of various input components .


function handleStretchTabs (stretchTabs) {
    var elements = getElements();
    angular.element(elements.wrapper).toggleClass('md-stretch-tabs', shouldStretchTabs());
    updateInkBarStyles();
  }

function handleStretchTabs ( stretchTabs ) { var elements = getElements ( ) ; angular . element ( elements . wrapper ) . toggleClass ( 'md-stretch-tabs' , shouldStretchTabs ( ) ) ; updateInkBarStyles ( ) ; }

Change handlers
Toggles stretch tabs class and updates inkbar when tab stretching changes
@param stretchTabs


function handleOffsetChange (left) {
    var elements = getElements();
    var newValue = ((ctrl.shouldCenterTabs || isRtl() ? '' : '-') + left + 'px');

    // Fix double-negative which can happen with RTL support
    newValue = newValue.replace('--', '');

    angular.element(elements.paging).css($mdConstant.CSS.TRANSFORM, 'translate3d(' + newValue + ', 0, 0)');
    $scope.$broadcast('$mdTabsPaginationChanged');
  }

Apply ctrl.offsetLeft to the paging element when it changes
@param left

Apply ctrl . offsetLeft to the paging element when it changes


function scroll (event) {
    if (!ctrl.shouldPaginate) return;
    event.preventDefault();
    ctrl.offsetLeft = fixOffset(ctrl.offsetLeft - event.wheelDelta);
  }

function scroll ( event ) { if ( ! ctrl . shouldPaginate ) return ; event . preventDefault ( ) ; ctrl . offsetLeft = fixOffset ( ctrl . offsetLeft - event . wheelDelta ) ; }

When pagination is on, this makes sure the selected index is in view.
@param event

When pagination is on this makes sure the selected index is in view .


function shouldPaginate () {
    if (ctrl.noPagination || !loaded) return false;
    var canvasWidth = $element.prop('clientWidth');

    angular.forEach(getElements().tabs, function (tab) {
      canvasWidth -= tab.offsetWidth;
    });

    return canvasWidth < 0;
  }

function shouldPaginate ( ) { if ( ctrl . noPagination || ! loaded ) return false ; var canvasWidth = $element . prop ( 'clientWidth' ) ; angular . forEach ( getElements ( ) . tabs , function ( tab ) { canvasWidth -= tab . offsetWidth ; } ) ; return canvasWidth < 0 ; }

Determines if pagination is necessary to display the tabs within the available space.
@returns {boolean}

Determines if pagination is necessary to display the tabs within the available space .


function adjustOffset (index) {
    var elements = getElements();

    if (!angular.isNumber(index)) index = ctrl.focusIndex;
    if (!elements.tabs[ index ]) return;
    if (ctrl.shouldCenterTabs) return;
    var tab         = elements.tabs[ index ],
        left        = tab.offsetLeft,
        right       = tab.offsetWidth + left,
        extraOffset = 32;

    // If we are selecting the first tab (in LTR and RTL), always set the offset to 0
    if (index == 0) {
      ctrl.offsetLeft = 0;
      return;
    }

    if (isRtl()) {
      var tabWidthsBefore = calcTabsWidth(Array.prototype.slice.call(elements.tabs, 0, index));
      var tabWidthsIncluding = calcTabsWidth(Array.prototype.slice.call(elements.tabs, 0, index + 1));

      ctrl.offsetLeft = Math.min(ctrl.offsetLeft, fixOffset(tabWidthsBefore));
      ctrl.offsetLeft = Math.max(ctrl.offsetLeft, fixOffset(tabWidthsIncluding - elements.canvas.clientWidth));
    } else {
      ctrl.offsetLeft = Math.max(ctrl.offsetLeft, fixOffset(right - elements.canvas.clientWidth + extraOffset));
      ctrl.offsetLeft = Math.min(ctrl.offsetLeft, fixOffset(left));
    }
  }

Forces the pagination to move the focused tab into view.

Forces the pagination to move the focused tab into view .


function updateInkBarStyles () {
    var elements = getElements();

    if (!elements.tabs[ ctrl.selectedIndex ]) {
      angular.element(elements.inkBar).css({ left: 'auto', right: 'auto' });
      return;
    }

    if (!ctrl.tabs.length) return queue.push(ctrl.updateInkBarStyles);
    // if the element is not visible, we will not be able to calculate sizes until it is
    // we should treat that as a resize event rather than just updating the ink bar
    if (!$element.prop('offsetParent')) return handleResizeWhenVisible();

    var index      = ctrl.selectedIndex,
        totalWidth = elements.paging.offsetWidth,
        tab        = elements.tabs[ index ],
        left       = tab.offsetLeft,
        right      = totalWidth - left - tab.offsetWidth;

    if (ctrl.shouldCenterTabs) {
      // We need to use the same calculate process as in the pagination wrapper, to avoid rounding deviations.
      var tabWidth = calcTabsWidth(elements.tabs);

      if (totalWidth > tabWidth) {
        $mdUtil.nextTick(updateInkBarStyles, false);
      }
    }
    updateInkBarClassName();
    angular.element(elements.inkBar).css({ left: left + 'px', right: right + 'px' });
  }

Repositions the ink bar to the selected tab.
@returns {*}

Repositions the ink bar to the selected tab .


function Barcode1D() {
  this.mode = MODE_BARWIDTH;
  this.width = 0;
  this.height = 0;
  this.background = '#FFF';
  this.barcolor = '#000';
  this.type = 'PNG';
  this.offset = 0;
  this.modulewidth = 1;
}

function Barcode1D ( ) { this . mode = MODE_BARWIDTH ; this . width = 0 ; this . height = 0 ; this . background = '#FFF' ; this . barcolor = '#000' ; this . type = 'PNG' ; this . offset = 0 ; this . modulewidth = 1 ; }


function update() {
	var stateTree = buildTreeJSON(xebraState.getPatchers());
	var nodes = d3.hierarchy(stateTree, function(d) {
		return d.children;
	});
	d3Tree(nodes);

	var link = g.selectAll(".link")
		.data(nodes.descendants().slice(1))
	.enter().append("path")
		.attr("class", "link")
		.attr("d", diagonal);

	var node = g.selectAll(".node")
		.data(nodes.descendants())
	.enter().append("g")
		.attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
		.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

	node.append("circle")
		.attr("r", 2.5);

	node.append("text")
		.attr("dy", function(d) { return d.children ? -10 : 0 })
		.attr("x", function(d) { return d.children ? -8 : 8; })
		.style("text-anchor", "start" )
		.text(function(d) { return d.data.name; });
}

function
update
(
)
{
var
stateTree
=
buildTreeJSON
(
xebraState
.
getPatchers
(
)
)
;
var
nodes
=
d3
.
hierarchy
(
stateTree
,
function
(
d
)
{
return
d
.
children
;
}
)
;
d3Tree
(
nodes
)
;
var
link
=
g
.
selectAll
(
".link"
)
.
data
(
nodes
.
descendants
(
)
.
slice
(
1
)
)
.
enter
(
)
.
append
(
"path"
)
.
attr
(
"class"
,
"link"
)
.
attr
(
"d"
,
diagonal
)
;
var
node
=
g
.
selectAll
(
".node"
)
.
data
(
nodes
.
descendants
(
)
)
.
enter
(
)
.
append
(
"g"
)
.
attr
(
"class"
,
function
(
d
)
{
return
"node"
+
(
d
.
children
" node--internal"
:
" node--leaf"
)
;
}
)
.
attr
(
"transform"
,
function
(
d
)
{
return
"translate("
+
d
.
y
+
","
+
d
.
x
+
")"
;
}
)
;
node
.
append
(
"circle"
)
.
attr
(
"r"
,
2.5
)
;
node
.
append
(
"text"
)
.
attr
(
"dy"
,
function
(
d
)
{
return
d
.
children
10
:
0
}
)
.
attr
(
"x"
,
function
(
d
)
{
return
d
.
children
8
:
8
;
}
)
.
style
(
"text-anchor"
,
"start"
)
.
text
(
function
(
d
)
{
return
d
.
data
.
name
;
}
)
;
}


function message(msg, thisArg) {
  var sig = colors.red(thisArg.name);
  sig += ' in plugin ';
  sig += '"' + colors.cyan(thisArg.plugin) + '"';
  sig += '\n';
  sig += msg;
  return sig;
}

function
message
(
msg
,
thisArg
)
{
var
sig
=
colors
.
red
(
thisArg
.
name
)
;
sig
+=
' in plugin '
;
sig
+=
'"'
+
colors
.
cyan
(
thisArg
.
plugin
)
+
'"'
;
sig
+=
'\n'
;
sig
+=
msg
;
return
sig
;
}


function setDefaults(plugin, message, opts) {
  if (typeof plugin === 'object') {
    return defaults(plugin);
  }
  opts = opts || {};
  if (message instanceof Error) {
    opts.error = message;
  } else if (typeof message === 'object') {
    opts = message;
  } else {
    opts.message = message;
  }
  opts.plugin = plugin;
  return defaults(opts);
}

function setDefaults ( plugin , message , opts ) { if ( typeof plugin === 'object' ) { return defaults ( plugin ) ; } opts = opts || { } ; if ( message instanceof Error ) { opts . error = message ; } else if ( typeof message === 'object' ) { opts = message ; } else { opts . message = message ; } opts . plugin = plugin ; return defaults ( opts ) ; }

Set default options based on arguments .


function _curry2(fn) {
	  return function f2(a, b) {
	    switch (arguments.length) {
	      case 0:
	        return f2;
	      case 1:
	        return _isPlaceholder(a) ? f2 : _curry1(function (_b) {
	          return fn(a, _b);
	        });
	      default:
	        return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) {
	          return fn(_a, b);
	        }) : _isPlaceholder(b) ? _curry1(function (_b) {
	          return fn(a, _b);
	        }) : fn(a, b);
	    }
	  };
	}

function _curry2 ( fn ) { return function f2 ( a , b ) { switch ( arguments . length ) { case 0 : return f2 ; case 1 : return _isPlaceholder ( a ) ? f2 : _curry1 ( function ( _b ) { return fn ( a , _b ) ; } ) ; default : return _isPlaceholder ( a ) && _isPlaceholder ( b ) ? f2 : _isPlaceholder ( a ) ? _curry1 ( function ( _a ) { return fn ( _a , b ) ; } ) : _isPlaceholder ( b ) ? _curry1 ( function ( _b ) { return fn ( a , _b ) ; } ) : fn ( a , b ) ; } } ; }

Optimized internal two-arity curry function.

@private
@category Function
@param {Function} fn The function to curry.
@return {Function} The curried function.

Optimized internal two - arity curry function .


function _curry1(fn) {
	  return function f1(a) {
	    if (arguments.length === 0 || _isPlaceholder(a)) {
	      return f1;
	    } else {
	      return fn.apply(this, arguments);
	    }
	  };
	}

function _curry1 ( fn ) { return function f1 ( a ) { if ( arguments . length === 0 || _isPlaceholder ( a ) ) { return f1 ; } else { return fn . apply ( this , arguments ) ; } } ; }

Optimized internal one-arity curry function.

@private
@category Function
@param {Function} fn The function to curry.
@return {Function} The curried function.

Optimized internal one - arity curry function .


function _clone(value, refFrom, refTo, deep) {
	  var copy = function copy(copiedValue) {
	    var len = refFrom.length;
	    var idx = 0;
	    while (idx < len) {
	      if (value === refFrom[idx]) {
	        return refTo[idx];
	      }
	      idx += 1;
	    }
	    refFrom[idx + 1] = value;
	    refTo[idx + 1] = copiedValue;
	    for (var key in value) {
	      copiedValue[key] = deep ? _clone(value[key], refFrom, refTo, true) : value[key];
	    }
	    return copiedValue;
	  };
	  switch (type(value)) {
	    case 'Object':
	      return copy({});
	    case 'Array':
	      return copy([]);
	    case 'Date':
	      return new Date(value.valueOf());
	    case 'RegExp':
	      return _cloneRegExp(value);
	    default:
	      return value;
	  }
	}

function _clone ( value , refFrom , refTo , deep ) { var copy = function copy ( copiedValue ) { var len = refFrom . length ; var idx = 0 ; while ( idx < len ) { if ( value === refFrom [ idx ] ) { return refTo [ idx ] ; } idx += 1 ; } refFrom [ idx + 1 ] = value ; refTo [ idx + 1 ] = copiedValue ; for ( var key in value ) { copiedValue [ key ] = deep ? _clone ( value [ key ] , refFrom , refTo , true ) : value [ key ] ; } return copiedValue ; } ; switch ( type ( value ) ) { case 'Object' : return copy ( { } ) ; case 'Array' : return copy ( [ ] ) ; case 'Date' : return new Date ( value . valueOf ( ) ) ; case 'RegExp' : return _cloneRegExp ( value ) ; default : return value ; } }

Copies an object.

@private
@param {*} value The value to be copied
@param {Array} refFrom Array containing the source references
@param {Array} refTo Array containing the copied source references
@param {Boolean} deep Whether or not to perform deep cloning.
@return {*} The copied value.


function pipe() {
	  if (arguments.length === 0) {
	    throw new Error('pipe requires at least one argument');
	  }
	  return _arity(arguments[0].length, reduce(_pipe, arguments[0], tail(arguments)));
	}

function
pipe
(
)
{
if
(
arguments
.
length
===
0
)
{
throw
new
Error
(
'pipe requires at least one argument'
)
;
}
return
_arity
(
arguments
[
0
]
.
length
,
reduce
(
_pipe
,
arguments
[
0
]
,
tail
(
arguments
)
)
)
;
}

Performs left-to-right function composition. The leftmost function may have
any arity; the remaining functions must be unary.

In some libraries this function is named `sequence`.

**Note:** The result of pipe is not automatically curried.

@func
@memberOf R
@since v0.1.0
@category Function
@sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z)
@param {...Function} functions
@return {Function}
@see R.compose
@example

var f = R.pipe(Math.pow, R.negate, R.inc);

f(3, 4); // -(3^4) + 1
@symb R.pipe(f, g, h)(a, b) = h(g(f(a, b)))

Performs left - to - right function composition . The leftmost function may have any arity ; the remaining functions must be unary .


function pipeP() {
	  if (arguments.length === 0) {
	    throw new Error('pipeP requires at least one argument');
	  }
	  return _arity(arguments[0].length, reduce(_pipeP, arguments[0], tail(arguments)));
	}

function
pipeP
(
)
{
if
(
arguments
.
length
===
0
)
{
throw
new
Error
(
'pipeP requires at least one argument'
)
;
}
return
_arity
(
arguments
[
0
]
.
length
,
reduce
(
_pipeP
,
arguments
[
0
]
,
tail
(
arguments
)
)
)
;
}

Performs left-to-right composition of one or more Promise-returning
functions. The leftmost function may have any arity; the remaining functions
must be unary.

@func
@memberOf R
@since v0.10.0
@category Function
@sig ((a -> Promise b), (b -> Promise c), ..., (y -> Promise z)) -> (a -> Promise z)
@param {...Function} functions
@return {Function}
@see R.composeP
@example

//  followersForUser :: String -> Promise [User]
var followersForUser = R.pipeP(db.getUserById, db.getFollowers);

Performs left - to - right composition of one or more Promise - returning functions . The leftmost function may have any arity ; the remaining functions must be unary .


function _uniqContentEquals(aIterator, bIterator, stackA, stackB) {
	  var a = _arrayFromIterator(aIterator);
	  var b = _arrayFromIterator(bIterator);

	  function eq(_a, _b) {
	    return _equals(_a, _b, stackA.slice(), stackB.slice());
	  }

	  // if *a* array contains any element that is not included in *b*
	  return !_containsWith(function (b, aItem) {
	    return !_containsWith(eq, aItem, b);
	  }, b, a);
	}

private _uniqContentEquals function.
That function is checking equality of 2 iterator contents with 2 assumptions
- iterators lengths are the same
- iterators values are unique

false-positive result will be returned for comparision of, e.g.
- [1,2,3] and [1,2,3,4]
- [1,1,1] and [1,2,3]

private _uniqContentEquals function . That function is checking equality of 2 iterator contents with 2 assumptions - iterators lengths are the same - iterators values are unique


function delaunayRefine(points, triangulation) {
  var stack = []

  var numPoints = points.length
  var stars = triangulation.stars
  for(var a=0; a<numPoints; ++a) {
    var star = stars[a]
    for(var j=1; j<star.length; j+=2) {
      var b = star[j]

      //If order is not consistent, then skip edge
      if(b < a) {
        continue
      }

      //Check if edge is constrained
      if(triangulation.isConstraint(a, b)) {
        continue
      }

      //Find opposite edge
      var x = star[j-1], y = -1
      for(var k=1; k<star.length; k+=2) {
        if(star[k-1] === b) {
          y = star[k]
          break
        }
      }

      //If this is a boundary edge, don't flip it
      if(y < 0) {
        continue
      }

      //If edge is in circle, flip it
      if(inCircle(points[a], points[b], points[x], points[y]) < 0) {
        stack.push(a, b)
      }
    }
  }

  while(stack.length > 0) {
    var b = stack.pop()
    var a = stack.pop()

    //Find opposite pairs
    var x = -1, y = -1
    var star = stars[a]
    for(var i=1; i<star.length; i+=2) {
      var s = star[i-1]
      var t = star[i]
      if(s === b) {
        y = t
      } else if(t === b) {
        x = s
      }
    }

    //If x/y are both valid then skip edge
    if(x < 0 || y < 0) {
      continue
    }

    //If edge is now delaunay, then don't flip it
    if(inCircle(points[a], points[b], points[x], points[y]) >= 0) {
      continue
    }

    //Flip the edge
    triangulation.flip(a, b)

    //Test flipping neighboring edges
    testFlip(points, triangulation, stack, x, a, y)
    testFlip(points, triangulation, stack, a, y, x)
    testFlip(points, triangulation, stack, y, b, x)
    testFlip(points, triangulation, stack, b, x, y)
  }
}

Assume edges are sorted lexicographically


function PartialHull(a, b, idx, lowerIds, upperIds) {
  this.a = a
  this.b = b
  this.idx = idx
  this.lowerIds = lowerIds
  this.upperIds = upperIds
}

function PartialHull ( a , b , idx , lowerIds , upperIds ) { this . a = a this . b = b this . idx = idx this . lowerIds = lowerIds this . upperIds = upperIds }

A partial convex hull fragment, made of two unimonotone polygons

A partial convex hull fragment made of two unimonotone polygons


function Event(a, b, type, idx) {
  this.a    = a
  this.b    = b
  this.type = type
  this.idx  = idx
}

function Event ( a , b , type , idx ) { this . a = a this . b = b this . type = type this . idx = idx }


function showValidation(feedback) {
  feedback.errors.forEach(function (error) {
    console.log('ERROR: ' + error);
  });
  feedback.warnings.forEach(function (warning) {
    console.log('WARNING: ' + warning);
  });
  console.log("Validator finished with " + feedback.warnings.length + " warnings and " + feedback.errors.length + " errors.");
  process.exit(feedback.errors.length > 0 ? 2 : 0);
}

function
showValidation
(
feedback
)
{
feedback
.
errors
.
forEach
(
function
(
error
)
{
console
.
log
(
'ERROR: '
+
error
)
;
}
)
;
feedback
.
warnings
.
forEach
(
function
(
warning
)
{
console
.
log
(
'WARNING: '
+
warning
)
;
}
)
;
console
.
log
(
"Validator finished with "
+
feedback
.
warnings
.
length
+
" warnings and "
+
feedback
.
errors
.
length
+
" errors."
)
;
process
.
exit
(
feedback
.
errors
.
length
>
0
2
:
0
)
;
}


function (input, prefix) {
    _.forOwn(input, function (value, key) {
      if ((/[^\w-]/).test(key)) {
        console.warn(key + ': the key format is not valid');
      }
      if (_.isPlainObject(value)) {
        return recursion(value, prefix ? [prefix, key].join('_') : key);
      }
      result[(prefix ? [null, prefix, key] : [null, key]).join('_')] =
        _.isFinite(value) ? value : _.truncate(_.toString(value), {length: 32765}); // 32765 + 1
    });
  }

function
(
input
,
prefix
)
{
_
.
forOwn
(
input
,
function
(
value
,
key
)
{
if
(
(
/
[^\w-]
/
)
.
test
(
key
)
)
{
console
.
warn
(
key
+
': the key format is not valid'
)
;
}
if
(
_
.
isPlainObject
(
value
)
)
{
return
recursion
(
value
,
prefix
[
prefix
,
key
]
.
join
(
'_'
)
:
key
)
;
}
result
[
(
prefix
[
,
prefix
,
key
]
:
[
,
key
]
)
.
join
(
'_'
)
]
=
_
.
isFinite
(
value
)
value
:
_
.
truncate
(
_
.
toString
(
value
)
,
{
length
:
32765
}
)
;
// 32765 + 1
}
)
;
}

recursion function for key-value aggregation 32766 bytes is the maximum length for a field

recursion function for key - value aggregation 32766 bytes is the maximum length for a field


function shallowCopy(src, dst) {
  var i = 0;
  if (isArray(src)) {
    dst = dst || [];

    for (; i < src.length; i++) {
      dst[i] = src[i];
    }
  } else if (isObject(src)) {
    dst = dst || {};

    var keys = Object.keys(src);

    for (var l = keys.length; i < l; i++) {
      var key = keys[i];

      if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
        dst[key] = src[key];
      }
    }
  }

  return dst || src;
}

function shallowCopy ( src , dst ) { var i = 0 ; if ( isArray ( src ) ) { dst = dst || [ ] ; for ( ; i < src . length ; i ++ ) { dst [ i ] = src [ i ] ; } } else if ( isObject ( src ) ) { dst = dst || { } ; var keys = Object . keys ( src ) ; for ( var l = keys . length ; i < l ; i ++ ) { var key = keys [ i ] ; if ( ! ( key . charAt ( 0 ) === '$' && key . charAt ( 1 ) === '$' ) ) { dst [ key ] = src [ key ] ; } } } return dst || src ; }

Creates a shallow copy of an object, an array or a primitive

Creates a shallow copy of an object an array or a primitive


function push() {
        var name,
            value,
            browserCookies,
            updated;

        //delete any cookies deleted in $cookies
        for (name in lastCookies) {
          if (isUndefined(cookies[name])) {
            $browser.cookies(name, undefined);
          }
        }

        //update all cookies updated in $cookies
        for(name in cookies) {
          value = cookies[name];
          if (!angular.isString(value)) {
            value = '' + value;
            cookies[name] = value;
          }
          if (value !== lastCookies[name]) {
            $browser.cookies(name, value);
            updated = true;
          }
        }

        //verify what was actually stored
        if (updated){
          updated = false;
          browserCookies = $browser.cookies();

          for (name in cookies) {
            if (cookies[name] !== browserCookies[name]) {
              //delete or reset all cookies that the browser dropped from $cookies
              if (isUndefined(browserCookies[name])) {
                delete cookies[name];
              } else {
                cookies[name] = browserCookies[name];
              }
              updated = true;
            }
          }
        }
      }

Pushes all the cookies from the service to the browser and verifies if all cookies were
stored.

Pushes all the cookies from the service to the browser and verifies if all cookies were stored .


function $SnifferProvider() {
  this.$get = ['$window', '$document', function($window, $document) {
    var eventSupport = {},
        android =
          int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
        boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
        document = $document[0] || {},
        documentMode = document.documentMode,
        vendorPrefix,
        vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
        bodyStyle = document.body && document.body.style,
        transitions = false,
        animations = false,
        match;

    if (bodyStyle) {
      for(var prop in bodyStyle) {
        if(match = vendorRegex.exec(prop)) {
          vendorPrefix = match[0];
          vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
          break;
        }
      }

      if(!vendorPrefix) {
        vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
      }

      transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
      animations  = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));

      if (android && (!transitions||!animations)) {
        transitions = isString(document.body.style.webkitTransition);
        animations = isString(document.body.style.webkitAnimation);
      }
    }

    return {
      // Android has history.pushState, but it does not update location correctly
      // so let's not use the history API at all.
      // http://code.google.com/p/android/issues/detail?id=17471
      // https://github.com/angular/angular.js/issues/904

      // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
      // so let's not use the history API also
      // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
      // jshint -W018
      history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
      // jshint +W018
      hashchange: 'onhashchange' in $window &&
                  // IE8 compatible mode lies
                  (!documentMode || documentMode > 7),
      hasEvent: function(event) {
        // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
        // it. In particular the event is not fired when backspace or delete key are pressed or
        // when cut operation is performed.
        if (event == 'input' && msie == 9) return false;

        if (isUndefined(eventSupport[event])) {
          var divElm = document.createElement('div');
          eventSupport[event] = 'on' + event in divElm;
        }

        return eventSupport[event];
      },
      csp: csp(),
      vendorPrefix: vendorPrefix,
      transitions : transitions,
      animations : animations,
      android: android,
      msie : msie,
      msieDocumentMode: documentMode
    };
  }];
}

!!! This is an undocumented "private" service !!!

@name $sniffer
@requires $window
@requires $document

@property {boolean} history Does the browser support html5 history api ?
@property {boolean} hashchange Does the browser support hashchange event ?
@property {boolean} transitions Does the browser support CSS transition events ?
@property {boolean} animations Does the browser support CSS animation events ?

@description
This is very simple implementation of testing browser's features.

!!! This is an undocumented private service !!!


function addNativeHtml5Validators(ctrl, validatorName, badFlags, ignoreFlags, validity) {
  if (isObject(validity)) {
    ctrl.$$hasNativeValidators = true;
    var validator = function(value) {
      // Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
      // perform the required validation)
      if (!ctrl.$error[validatorName] &&
          !testFlags(validity, ignoreFlags) &&
          testFlags(validity, badFlags)) {
        ctrl.$setValidity(validatorName, false);
        return;
      }
      return value;
    };
    ctrl.$parsers.push(validator);
  }
}

Pass validity so that behaviour can be mocked easier.

Pass validity so that behaviour can be mocked easier .


function (docular_webapp_target) {
        var ABS_SCRIPTS = __dirname;
        var ABS_LIB = path.resolve(ABS_SCRIPTS + '/..');
        var ABS_DEFAULT_GENERATED_WEBAPP = ABS_LIB + '/generated/';
        return docular_webapp_target ? path.resolve(process.cwd() + '/' + docular_webapp_target) : path.relative(process.cwd(), ABS_DEFAULT_GENERATED_WEBAPP);
    }

function ( docular_webapp_target ) { var ABS_SCRIPTS = __dirname ; var ABS_LIB = path . resolve ( ABS_SCRIPTS + '/..' ) ; var ABS_DEFAULT_GENERATED_WEBAPP = ABS_LIB + '/generated/' ; return docular_webapp_target ? path . resolve ( process . cwd ( ) + '/' + docular_webapp_target ) : path . relative ( process . cwd ( ) , ABS_DEFAULT_GENERATED_WEBAPP ) ; }


function(expr, context, subIntegral) {
      var simplified = simplify.simplifyCore(expr, context);
      if(!simplified.equals(expr)) {
        return subIntegral(simplified, context, "simplified expression");
      }
    }

function
(
expr
,
context
,
subIntegral
)
{
var
simplified
=
simplify
.
simplifyCore
(
expr
,
context
)
;
if
(
!
simplified
.
equals
(
expr
)
)
{
return
subIntegral
(
simplified
,
context
,
"simplified expression"
)
;
}
}


function _integral(expr, context, lastRuleComment) {
    var exprString = expr.toString({
      parenthesis: 'all',
      handler: function(node, options) {
        if(node.type === 'ParenthesisNode') {
          return '(' + node.content.toString(options) + ')';
        }
      }
    });

    var debugComment = lastRuleComment ? lastRuleComment + ": " : "";
    debugComment += "find integral of " + exprString + "  d" + context.variable.name;
    context.printDebug(debugComment);
    context.debugIndent++;

    // Check if we already tried to integrate this expression
    if(context.subIntegral[exprString] !== undefined) {
      // This could be null, indicating that we couldn't find an integral for
      // it (or we are currenly working on it a few levels of recursion up!)
      context.printDebug("Precomputed: " + context.subIntegral[exprString]);
      context.debugIndent--;
      return context.subIntegral[exprString];
    }

    // Remember that we are working on this integral, just haven't found a
    // solution yet!
    context.subIntegral[exprString] = null;

    for(var i = 0; i < context.rules.length; i++) {
      var result = context.rules[i](expr, context, _integral);
      if(result !== undefined && result !== null) {
        // Remember this solution!
        context.subIntegral[exprString] = result;

        context.printDebug("Computed: " + result.toString({parenthesis: 'all'}));
        context.debugIndent--;
        return result;
      }
    }

    // We couldn't find a solution :(
    context.printDebug("No integral found");
    context.debugIndent--;
    return null;
  }

Helper function that runs the main loop for the integrator. It scans over the
rules until one of them produces an integral or until no more rules are left.

@param {Node} expr The expression to be integrated.
@param {IntegrationContext}

Helper function that runs the main loop for the integrator . It scans over the rules until one of them produces an integral or until no more rules are left .


function checkFile( src ) {
			if ( ! grunt.file.exists( src ) ) {
				grunt.log.error( "Source file \"" + src + "\" not fount." );
				return false;
			}

			return true;
		}

function
checkFile
(
src
)
{
if
(
!
grunt
.
file
.
exists
(
src
)
)
{
grunt
.
log
.
error
(
"Source file \""
+
src
+
"\" not fount."
)
;
return
false
;
}
return
true
;
}

Method to check wether file exists and warn if not.

Method to check wether file exists and warn if not .


function parseInlineValues( string ) {
			var match;
			var values = {};

			while( match = attributesRegex.exec( string ) ) {
				values[ match[ 1 ] ] = match[ 2 ];
			}

			return values;
		}

function parseInlineValues ( string ) { var match ; var values = { } ; while ( match = attributesRegex . exec ( string ) ) { values [ match [ 1 ] ] = match [ 2 ] ; } return values ; }


function applyIndent( indent, content ) {
			if ( ! indent || indent.length < 1 ) {
				return content;
			}

			return content
				.split( "\n" )
				.map( function( line ) {
					// do not indent empty lines
					return line.trim() !== "" ? ( indent + line ) : "";
				} )
				.join( "\n" );
		}

function
applyIndent
(
indent
,
content
)
{
if
(
!
indent
||
indent
.
length
<
1
)
{
return
content
;
}
return
content
.
split
(
"\n"
)
.
map
(
function
(
line
)
{
// do not indent empty lines
return
line
.
trim
(
)
!==
""
(
indent
+
line
)
:
""
;
}
)
.
join
(
"\n"
)
;
}


function getArrayValues( string, values ) {

			string = string.split( " " ).join( "" );

			if ( arrayRegex.test( string ) )
				return string.match( arrayRegex )[ 1 ].split( "," );

			else {
				var array = processPlaceholder( string, values );
				if ( ! mout.lang.isArray( array ) ) array = [];

				return array;
			}

		}

function
getArrayValues
(
string
,
values
)
{
string
=
string
.
split
(
" "
)
.
join
(
""
)
;
if
(
arrayRegex
.
test
(
string
)
)
return
string
.
match
(
arrayRegex
)
[
1
]
.
split
(
","
)
;
else
{
var
array
=
processPlaceholder
(
string
,
values
)
;
if
(
!
mout
.
lang
.
isArray
(
array
)
)
array
=
[
]
;
return
array
;
}
}

Helper to either find values from JSON or inline values


function validateIf( inlineValues, values ) {

			if ( "_if" in inlineValues ) {

				var value = inlineValues[ "_if" ];
				delete inlineValues[ "_if" ];

				var params = {};

				var condition = value.replace( ifRegex, function( match, varname ) {
					if( ! varname ) return match;

					var resolved = resolveName( varname, values );

					// check for semantic falsy values
					if ( options.semanticIf === true ) {
						resolved = [ "no", "off" ].indexOf( resolved ) === -1;

					} else if ( mout.lang.isArray( options.semanticIf ) ) {
						resolved = options.semanticIf.indexOf( resolved ) === -1;

					} else if ( mout.lang.isFunction( options.semanticIf ) ) {
						resolved = options.semanticIf( resolved );
					}

					params[ varname ] = resolved;

					return "params['" + varname + "']";
				});

				try {
					/* jshint evil:true */
					/* eslint-disable no-eval */

					return ! eval( condition );

				} catch( e ) {
					grunt.log.error( "Invalid if condition: '" + value + "'" );
				}
			}

			return false;
		}

function
validateIf
(
inlineValues
,
values
)
{
if
(
"_if"
in
inlineValues
)
{
var
value
=
inlineValues
[
"_if"
]
;
delete
inlineValues
[
"_if"
]
;
var
params
=
{
}
;
var
condition
=
value
.
replace
(
ifRegex
,
function
(
match
,
varname
)
{
if
(
!
varname
)
return
match
;
var
resolved
=
resolveName
(
varname
,
values
)
;
// check for semantic falsy values
if
(
options
.
semanticIf
===
true
)
{
resolved
=
[
"no"
,
"off"
]
.
indexOf
(
resolved
)
===
1
;
}
else
if
(
mout
.
lang
.
isArray
(
options
.
semanticIf
)
)
{
resolved
=
options
.
semanticIf
.
indexOf
(
resolved
)
===
1
;
}
else
if
(
mout
.
lang
.
isFunction
(
options
.
semanticIf
)
)
{
resolved
=
options
.
semanticIf
(
resolved
)
;
}
params
[
varname
]
=
resolved
;
return
"params['"
+
varname
+
"']"
;
}
)
;
try
{
/* jshint evil:true */
/* eslint-disable no-eval */
return
!
eval
(
condition
)
;
}
catch
(
e
)
{
grunt
.
log
.
error
(
"Invalid if condition: '"
+
value
+
"'"
)
;
}
}
return
false
;
}

Handle _if attributes in inline arguments


function validateRender( inlineValues ) {
			if ( "_render" in inlineValues ) {

				var skipValue = inlineValues[ "_render" ];

				if ( skipValue in options ) {
					return ! options[ skipValue ];
				}
			}

			return false;
		}

function validateRender ( inlineValues ) { if ( "_render" in inlineValues ) { var skipValue = inlineValues [ "_render" ] ; if ( skipValue in options ) { return ! options [ skipValue ] ; } } return false ; }

Handle _render attributes in inline arguments


function validateForEach( inlineValues, values, array ) {

			if ( "_foreach" in inlineValues ) {

				// test for object syntax `object as key => value`
				var match;

				if ( match = forEachRegex.exec( inlineValues[ "_foreach" ] ) ) {

					var object = {
						keyName: match[ 2 ],
						valueName: match[ 3 ],
						values: values[ match[ 1 ] ]
					};

					return object;
				}

				var set = inlineValues[ "_foreach" ].split( ":" );
				delete inlineValues[ "_foreach" ];

				// as transforms may contain colons, join rest of list to recreate original string
				getArrayValues( set.slice( 1 ).join( ":" ), values ).forEach( function( value ) {
					array.push( value );
				} );

				return set[ 0 ];
			}

			return null;
		}

Handle _foreach attributes in inline arguments


function validateBake( inlineValues ) {
			if ( "_bake" in inlineValues ) {

				var signature = inlineValues[ "_bake" ];
				delete inlineValues[ "_bake" ];

				var set = signature.split( ">", 2 );

				return {
					src: mout.string.trim( set[0] ),
					dest: mout.string.trim( set[1] )
				};
			}

			return null;
		}

function validateBake ( inlineValues ) { if ( "_bake" in inlineValues ) { var signature = inlineValues [ "_bake" ] ; delete inlineValues [ "_bake" ] ; var set = signature . split ( ">" , 2 ) ; return { src : mout . string . trim ( set [ 0 ] ) , dest : mout . string . trim ( set [ 1 ] ) } ; } return null ; }

Handle _bake attributes in inline arguments


function validateProcess( inlineValues ) {
			if ( "_process" in inlineValues ) {

				var value = inlineValues[ "_process" ];
				delete inlineValues[ "_process" ];

				return String(value).toLowerCase() === 'true' ;
			}

			return true;
		}

function validateProcess ( inlineValues ) { if ( "_process" in inlineValues ) { var value = inlineValues [ "_process" ] ; delete inlineValues [ "_process" ] ; return String ( value ) . toLowerCase ( ) === 'true' ; } return true ; }

Handle _process attributes in inline arguments


function extractSection( content ) {
			var depth = 0;			// tracks how difference between found opening and closing tags
			var start = 0;			// character position in `content` where inner-content starts
			var position = 0;		// current character position within _original_ content
			var length = 0;			// length section (= spacing plus bake-tag) we currently evaluate
			var remain = content;	// content left for further extraction
			var section = {};

			do {

				var result = remain.match( regex );

				if( ! result ) break;

				length = result[ 0 ].length;
				position += result.index;

				if( depth === 0 ) {

					start = position + length;

					section = mout.object.merge( section, parseSignature( result[ 4 ] ), {
						before: content.slice( 0, position ),
						linebreak: result[ 1 ],
						indent: result[ 2 ]
					} );
				}

				remain = remain.slice( result.index + length );

				depth += ( result[ 3 ] === "-start" );
				depth -= ( result[ 3 ] === "-end" );

				if( depth === 0 ) {
					return mout.object.merge( section, {
						inner: content.slice( start, position ),
						after: content.slice( position + length )
					} );
				}

				position += length;

			} while( true );

			return null;
		}

extract bake sections. For inline-bake it searches for matching closing tags and returns inline content and other information

extract bake sections . For inline - bake it searches for matching closing tags and returns inline content and other information


function parse( fileContent, filePath, destFile, values ) {

			var section = extractSection( fileContent );

			if( section ) {
				fileContent = processContent( section.before, values );

				if( section.inner ) {
					fileContent += replaceString( section.inner, "", "", filePath, section.attributes, filePath, destFile, values );

				} else if( section.includePath ) {
					fileContent += replaceFile( section.linebreak, section.indent, section.includePath, section.attributes, filePath, destFile, values );
				}

				fileContent += parse( section.after, filePath, destFile, values );

			} else {
				return processContent( fileContent, values );
			}

			return fileContent;
		}

function parse ( fileContent , filePath , destFile , values ) { var section = extractSection ( fileContent ) ; if ( section ) { fileContent = processContent ( section . before , values ) ; if ( section . inner ) { fileContent += replaceString ( section . inner , "" , "" , filePath , section . attributes , filePath , destFile , values ) ; } else if ( section . includePath ) { fileContent += replaceFile ( section . linebreak , section . indent , section . includePath , section . attributes , filePath , destFile , values ) ; } fileContent += parse ( section . after , filePath , destFile , values ) ; } else { return processContent ( fileContent , values ) ; } return fileContent ; }

Recursivly search for bake-tags and create one file.

Recursivly search for bake - tags and create one file .


function processContent( content, values ) {
			return mout.lang.isFunction( options.process ) ? options.process( content, values ) : content;
		}

function processContent ( content , values ) { return mout . lang . isFunction ( options . process ) ? options . process ( content , values ) : content ; }

Run process function if processor-function is defined

Run process function if processor - function is defined


function compare(a, b, index) {
  return (
    (a.charCodeAt(index) || 0) - (b.charCodeAt(index) || 0) ||
    compare(a, b, index + 1)
  )
}

function compare ( a , b , index ) { return ( ( a . charCodeAt ( index ) || 0 ) - ( b . charCodeAt ( index ) || 0 ) || compare ( a , b , index + 1 ) ) }

This would create an infinite loop if `a` and `b` could be equal, but the list we operate on only has unique values.

This would create an infinite loop if a and b could be equal but the list we operate on only has unique values .


function javascript(node) {
  if (!is(node, 'script')) {
    return false
  }

  if (has(node, 'type')) {
    return check(node.properties.type)
  }

  return !has(node, 'language') || check(node.properties.language, 'text/')
}

function javascript ( node ) { if ( ! is ( node , 'script' ) ) { return false } if ( has ( node , 'type' ) ) { return check ( node . properties . type ) } return ! has ( node , 'language' ) || check ( node . properties . language , 'text/' ) }


function check(value, prefix) {
  var val

  if (typeof value !== 'string') {
    return false
  }

  val = trim(value.split(';', 1)[0]).toLowerCase()

  return val === '' || mime.indexOf((prefix || '') + val) !== -1
}

function check ( value , prefix ) { var val if ( typeof value !== 'string' ) { return false } val = trim ( value . split ( ';' , 1 ) [ 0 ] ) . toLowerCase ( ) return val === '' || mime . indexOf ( ( prefix || '' ) + val ) !== - 1 }


function collapsable(node) {
  return (
    is('text', node) ||
    element(node, list) ||
    embedded(node) ||
    bodyOK(node) ||
    (element(node, 'meta') && has(node, 'itemProp'))
  )
}

function collapsable ( node ) { return ( is ( 'text' , node ) || element ( node , list ) || embedded ( node ) || bodyOK ( node ) || ( element ( node , 'meta' ) && has ( node , 'itemProp' ) ) ) }


function render(req, res, next)  {
    if (!req.session[sessionName].length) {
      next();
    } else {
      const resultHTML = [];
      async.each(
        req.session[sessionName],
        function(item, next) {
          beforeSingleRender(item, function(error, item) {
            if (error) return next(error);
            app.render(viewName, item, function(error, html) {
              if (error) return next(error);
              resultHTML.push(html);
              next(null);
            })
          })
        },
        function(error) {
          if (error) return next(error);
          req.session[sessionName].length = 0;
          afterAllRender(resultHTML, function(error, html) {
            if (error) return next(error);
            res.locals[localsName] = html;
            next();
          })
        }
      )
    }
  }

function render ( req , res , next ) { if ( ! req . session [ sessionName ] . length ) { next ( ) ; } else { const resultHTML = [ ] ; async . each ( req . session [ sessionName ] , function ( item , next ) { beforeSingleRender ( item , function ( error , item ) { if ( error ) return next ( error ) ; app . render ( viewName , item , function ( error , html ) { if ( error ) return next ( error ) ; resultHTML . push ( html ) ; next ( null ) ; } ) } ) } , function ( error ) { if ( error ) return next ( error ) ; req . session [ sessionName ] . length = 0 ; afterAllRender ( resultHTML , function ( error , html ) { if ( error ) return next ( error ) ; res . locals [ localsName ] = html ; next ( ) ; } ) } ) } }


function FlashMiddleware(req, res, next) {
    if (!isObject(req.session)) throw new Error('express-session is required. (npm i express-session)');
    if (!req.session[sessionName] || !isArray(req.session[sessionName])) req.session[sessionName] = [];

    /**
    * Utility used to programmatically add flash notifications
    * @method Flash Utility
    */
    req[utilityName] = function() {
      const argc = arguments.length;
      let notification;
      let redirect = REDIRECT;

      // Parse arguments
      if (argc) {
        if (argc === 1) {
          const arg = arguments[0];
          if (isObject(arg)) {
            notification = arg;
            redirect = (arg.redirect === undefined) ? redirect : arg.redirect;
          } else {
            notification = {
              message: '' + arg
            };
          }
        } else {
          notification = {
            type: '' + arguments[0],
            message: '' + arguments[1]
          };
          redirect = (arguments[2] === undefined) ? redirect : arguments[2];
        }
      }

      // Queue Notification
      if (notification && req.session[sessionName]) {
        req.session[sessionName].push(notification);
      }

      // If redirect is set, refresh or redirect, accordingly. Otherwise, render the
      // notifications now since it's on this request where they will be displayed.
      if (redirect) {
        const redirectUrl = (typeof redirect === 'string') ? redirect : req.originalUrl;
        res.redirect(redirectUrl);
      } else {
        /**
        * When there is no redirect, notifications must be rendered now and since
        * rendering is async (and this method is sync), a *promise* like function is returned.
        * The function can be called with a callback that will be called after all notifcations
        * are rendered, otherwise, rendering will be done during the next request.
        */
        return function ManualRender(callback) {
          render(req, res, callback);
        }
      }
    }

    /**
    * Process Queued Notifications
    */
    render(req, res, next);
  }

/**
    * Process Queued Notifications
    */

Adds flash method to req object and renders all notifications found in
req.session
@param {ReadStream} req
@param {WriteStream} res
@param {Function} next

Adds flash method to req object and renders all notifications found in req . session


function getFrameworkPath({ framework, baseDir }) {
  const pkgPath = path.join(baseDir, 'package.json');
  assert(fs.existsSync(pkgPath), `${pkgPath} should exist`);

  const moduleDir = path.join(baseDir, 'node_modules');
  const pkg = utility.readJSONSync(pkgPath);

  // 1. pass framework or customEgg
  if (framework) {
    // 1.1 framework is an absolute path
    // framework: path.join(baseDir, 'node_modules/${frameworkName}')
    if (path.isAbsolute(framework)) {
      assert(fs.existsSync(framework), `${framework} should exist`);
      return framework;
    }
    // 1.2 framework is a npm package that required by application
    // framework: 'frameworkName'
    return assertAndReturn(framework, moduleDir);
  }

  // 2. framework is not specified
  // 2.1 use framework name from pkg.egg.framework
  if (pkg.egg && pkg.egg.framework) {
    return assertAndReturn(pkg.egg.framework, moduleDir);
  }

  // 2.2 use egg by default
  return assertAndReturn('egg', moduleDir);
}

Find the framework directory, lookup order
- specify framework path
- get framework name from
- use egg by default
@param {Object} options - options
@param  {String} options.baseDir - the current directory of application
@param  {String} [options.framework] - the directory of framework
@return {String} frameworkPath

Find the framework directory lookup order - specify framework path - get framework name from - use egg by default


function getFrameworkOrEggPath(cwd, eggNames) {
  eggNames = eggNames || [ 'egg' ];
  const moduleDir = path.join(cwd, 'node_modules');
  if (!fs.existsSync(moduleDir)) {
    return '';
  }

  // try to get framework

  // 1. try to read egg.framework property on package.json
  const pkgFile = path.join(cwd, 'package.json');
  if (fs.existsSync(pkgFile)) {
    const pkg = utility.readJSONSync(pkgFile);
    if (pkg.egg && pkg.egg.framework) {
      return path.join(moduleDir, pkg.egg.framework);
    }
  }

  // 2. try the module dependencies includes eggNames
  const names = fs.readdirSync(moduleDir);
  for (const name of names) {
    const pkgfile = path.join(moduleDir, name, 'package.json');
    if (!fs.existsSync(pkgfile)) {
      continue;
    }
    const pkg = utility.readJSONSync(pkgfile);
    if (pkg.dependencies) {
      for (const eggName of eggNames) {
        if (pkg.dependencies[eggName]) {
          return path.join(moduleDir, name);
        }
      }
    }
  }

  // try to get egg
  for (const eggName of eggNames) {
    const pkgfile = path.join(moduleDir, eggName, 'package.json');
    if (fs.existsSync(pkgfile)) {
      return path.join(moduleDir, eggName);
    }
  }

  return '';
}

Try to get framework dir path
If can't find any framework, try to find egg dir path

@param {String} cwd - current work path
@param {Array} [eggNames] - egg names, default is ['egg']
@return {String} framework or egg dir path
@deprecated

Try to get framework dir path If can t find any framework try to find egg dir path


function autoInjectServices(object, args) {
    if(args.length === 0 ) return;
    let code = object.constructor.toString();
    code = code.match('constructor\\([\\$a-zA-Z0-9\\,\\s]+\\)')[0];
    code = code.substring(code.indexOf('(')+1, code.indexOf(')'));
    code = code.split(', ');
    for (let i = 0; i < code.length; i++) {
        Object.defineProperty(object, code[i], {value: args[i]})
    }
}

used to autoInject Services in the Controller


function SetterObservable(getter, setter) {
	this.setter = setter;
	this.observation = new Observation(getter);
	this.handler = this.handler.bind(this);

	//!steal-remove-start
	if (process.env.NODE_ENV !== 'production') {
		canReflect.assignSymbols(this, {
			"can.getName": function() {
				return (
					canReflect.getName(this.constructor) +
					"<" +
					canReflect.getName(getter) +
					">"
				);
			}
		});
		Object.defineProperty(this.handler, "name", {
			value: canReflect.getName(this) + ".handler"
		});
	}
	//!steal-remove-end
}

function SetterObservable ( getter , setter ) { this . setter = setter ; this . observation = new Observation ( getter ) ; this . handler = this . handler . bind ( this ) ; //!steal-remove-start if ( process . env . NODE_ENV !== 'production' ) { canReflect . assignSymbols ( this , { "can.getName" : function ( ) { return ( canReflect . getName ( this . constructor ) + "<" + canReflect . getName ( getter ) + ">" ) ; } } ) ; Object . defineProperty ( this . handler , "name" , { value : canReflect . getName ( this ) + ".handler" } ) ; } //!steal-remove-end }

SetterObservable's call a function when set. Their getter is backed up by an observation.

SetterObservable s call a function when set . Their getter is backed up by an observation .


function AsyncObservable(fn, context, initialValue) {
	this.resolve = this.resolve.bind(this);
	this.lastSetValue = new SimpleObservable(initialValue);
	this.handler = this.handler.bind(this);

	function observe() {
		this.resolveCalled = false;

		// set inGetter flag to avoid calling `resolve` redundantly if it is called
		// synchronously in the getter
		this.inGetter = true;
		var newVal = fn.call(
			context,
			this.lastSetValue.get(),
			this.bound === true ? this.resolve : undefined
		);
		this.inGetter = false;

		// if the getter returned a value, resolve with the value
		if (newVal !== undefined) {
			this.resolve(newVal);
		}
		// otherwise, if `resolve` was called synchronously in the getter,
		// resolve with the value passed to `resolve`
		else if (this.resolveCalled) {
			this.resolve(this._value);
		}

		// if bound, the handlers will be called by `resolve`
		// returning here would cause a duplicate event
		if (this.bound !== true) {
			return newVal;
		}
	}

	//!steal-remove-start
	if (process.env.NODE_ENV !== 'production') {
		canReflect.assignSymbols(this, {
			"can.getName": function() {
				return (
					canReflect.getName(this.constructor) +
					"<" +
					canReflect.getName(fn) +
					">"
				);
			}
		});
		Object.defineProperty(this.handler, "name", {
			value: canReflect.getName(this) + ".handler"
		});
		Object.defineProperty(observe, "name", {
			value: canReflect.getName(fn) + "::" + canReflect.getName(this.constructor)
		});
	}
	//!steal-remove-end

	this.observation = new Observation(observe, this);
}

This is an observable that is like `settable`, but passed a `resolve` function that can resolve the value of this observable late.

This is an observable that is like settable but passed a resolve function that can resolve the value of this observable late .


function load(dotGraph, appendTo) {
  var dotAST = parseDot(dotGraph);
  if (dotAST.length > 1 && appendTo !== undefined) {
    throw new Error('Dot file contains multiple graphs. Cannot use `saveTo` in this case');
  }

  if (!appendTo) {
    appendTo = require('ngraph.graph')();
  }
  // by default load will only load first graph:

  return loadOne(appendTo, dotAST[0]);
}

Loads graph from 'dot' string.

@param {String} dotGraph a graph in `dot` format
@param {ngraph.graph=} appendTo optional argument if you want to append parsed
graph to an old graph.

@return {ngraph.graph} Parsed graph

@see https://en.wikipedia.org/wiki/DOT_(graph_description_language)
@see https://github.com/anvaka/ngraph.graph


function() {
  var sendTracerInit = function() {
    sendObjectToInspectedPage({ content: { type: "MEIOSIS_TRACER_INIT" } })
  }

  var triggerStreamValue = function(index, value) {
    sendObjectToInspectedPage({ content: {
      type: "MEIOSIS_TRIGGER_STREAM_VALUE",
      index: index,
      value: value
    } })
  }

  tracer = window.meiosisTracer({
    selector: "#meiosis-tracer",
    sendTracerInit: sendTracerInit,
    triggerStreamValue: triggerStreamValue,
    direction: "auto"
  })
}

function ( ) { var sendTracerInit = function ( ) { sendObjectToInspectedPage ( { content : { type : "MEIOSIS_TRACER_INIT" } } ) } var triggerStreamValue = function ( index , value ) { sendObjectToInspectedPage ( { content : { type : "MEIOSIS_TRIGGER_STREAM_VALUE" , index : index , value : value } } ) } tracer = window . meiosisTracer ( { selector : "#meiosis-tracer" , sendTracerInit : sendTracerInit , triggerStreamValue : triggerStreamValue , direction : "auto" } ) }


function recurse (streams) {
    if(streams.length < 2)
      return
    streams[0].pipe(streams[1])
    recurse(streams.slice(1))
  }

function recurse ( streams ) { if ( streams . length < 2 ) return streams [ 0 ] . pipe ( streams [ 1 ] ) recurse ( streams . slice ( 1 ) ) }


function TemporaryCredentials(params) {
    AWS.Credentials.call(this);
    this.loadMasterCredentials();
    this.expired = true;

    this.params = params || {};
    if (this.params.RoleArn) {
      this.params.RoleSessionName =
        this.params.RoleSessionName || 'temporary-credentials';
    }
    this.service = new AWS.STS({params: this.params});
  }

function TemporaryCredentials ( params ) { AWS . Credentials . call ( this ) ; this . loadMasterCredentials ( ) ; this . expired = true ; this . params = params || { } ; if ( this . params . RoleArn ) { this . params . RoleSessionName = this . params . RoleSessionName || 'temporary-credentials' ; } this . service = new AWS . STS ( { params : this . params } ) ; }

Creates a new temporary credentials object.

@note In order to create temporary credentials, you first need to have
"master" credentials configured in {AWS.Config.credentials}. These
master credentials are necessary to retrieve the temporary credentials,
as well as refresh the credentials when they expire.
@param params [map] a map of options that are passed to the
{AWS.STS.assumeRole} or {AWS.STS.getSessionToken} operations.
If a `RoleArn` parameter is passed in, credentials will be based on the
IAM role.
@example Creating a new credenials object for generic temporary credentials
AWS.config.credentials = new AWS.TemporaryCredentials();
@example Creating a new credentials object for an IAM role
AWS.config.credentials = new AWS.TemporaryCredentials({
RoleArn: 'arn:aws:iam::1234567890:role/TemporaryCredentials',
});
@see AWS.STS.assumeRole
@see AWS.STS.getSessionToken

Creates a new temporary credentials object .


function Service(config) {
    if (!this.loadServiceClass) {
      throw AWS.util.error(new Error(),
        'Service must be constructed with `new\' operator');
    }
    var ServiceClass = this.loadServiceClass(config || {});
    if (ServiceClass) return new ServiceClass(config);
    this.initialize(config);
  }

Create a new service object with a configuration object

@param config [map] a map of configuration options


function getSignerClass() {
    var version;
    if (this.config.signatureVersion) {
      version = this.config.signatureVersion;
    } else {
      version = this.api.signatureVersion;
    }
    return AWS.Signers.RequestSigner.getVersion(version);
  }

function getSignerClass ( ) { var version ; if ( this . config . signatureVersion ) { version = this . config . signatureVersion ; } else { version = this . api . signatureVersion ; } return AWS . Signers . RequestSigner . getVersion ( version ) ; }

Gets the signer class for a given request
@api private


function defineMethods(svc) {
    AWS.util.each(svc.prototype.api.operations, function iterator(method) {
      if (svc.prototype[method]) return;
      svc.prototype[method] = function (params, callback) {
        return this.makeRequest(method, params, callback);
      };
    });
  }

function defineMethods ( svc ) { AWS . util . each ( svc . prototype . api . operations , function iterator ( method ) { if ( svc . prototype [ method ] ) return ; svc . prototype [ method ] = function ( params , callback ) { return this . makeRequest ( method , params , callback ) ; } ; } ) ; }

Adds one method for each operation described in the api configuration

@api private


function abort() {
    this.removeAllListeners('validateResponse');
    this.removeAllListeners('extractError');
    this.on('validateResponse', function addAbortedError(resp) {
      resp.error = AWS.util.error(new Error('Request aborted by user'), {
         code: 'RequestAbortedError', retryable: false
      });
    });

    if (this.httpRequest.stream) { // abort HTTP stream
      this.httpRequest.stream.abort();
      if (this.httpRequest._abortCallback) {
         this.httpRequest._abortCallback();
      } else {
        this.removeAllListeners('send'); // haven't sent yet, so let's not
      }
    }

    return this;
  }

function
abort
(
)
{
this
.
removeAllListeners
(
'validateResponse'
)
;
this
.
removeAllListeners
(
'extractError'
)
;
this
.
on
(
'validateResponse'
,
function
addAbortedError
(
resp
)
{
resp
.
error
=
AWS
.
util
.
error
(
new
Error
(
'Request aborted by user'
)
,
{
code
:
'RequestAbortedError'
,
retryable
:
false
}
)
;
}
)
;
if
(
this
.
httpRequest
.
stream
)
{
// abort HTTP stream
this
.
httpRequest
.
stream
.
abort
(
)
;
if
(
this
.
httpRequest
.
_abortCallback
)
{
this
.
httpRequest
.
_abortCallback
(
)
;
}
else
{
this
.
removeAllListeners
(
'send'
)
;
// haven't sent yet, so let's not
}
}
return
this
;
}

Aborts a request, emitting the error and complete events.

@!macro nobrowser
@example Aborting a request after sending
var params = {
Bucket: 'bucket', Key: 'key',
Body: new Buffer(1024 * 1024 * 5) // 5MB payload
};
var request = s3.putObject(params);
request.send(function (err, data) {
if (err) console.log("Error:", err.code, err.message);
else console.log(data);
});

// abort request in 1 second
setTimeout(request.abort.bind(request), 1000);

// prints "Error: RequestAbortedError Request aborted by user"
@return [AWS.Request] the same request object, for chaining.
@since v1.4.0

Aborts a request emitting the error and complete events .


function eachItem(callback) {
    function wrappedCallback(err, data) {
      if (err) return callback(err, null);
      if (data === null) return callback(null, null);

      var config = this.request.service.paginationConfig(this.request.operation);
      var resultKey = config.resultKey;
      if (Array.isArray(resultKey)) resultKey = resultKey[0];
      var results = AWS.util.jamespath.query(resultKey, data);
      AWS.util.arrayEach(results, function(result) {
        AWS.util.arrayEach(result, function(item) { callback(null, item); });
      });
    }

    this.eachPage(wrappedCallback);
  }

function eachItem ( callback ) { function wrappedCallback ( err , data ) { if ( err ) return callback ( err , null ) ; if ( data === null ) return callback ( null , null ) ; var config = this . request . service . paginationConfig ( this . request . operation ) ; var resultKey = config . resultKey ; if ( Array . isArray ( resultKey ) ) resultKey = resultKey [ 0 ] ; var results = AWS . util . jamespath . query ( resultKey , data ) ; AWS . util . arrayEach ( results , function ( result ) { AWS . util . arrayEach ( result , function ( item ) { callback ( null , item ) ; } ) ; } ) ; } this . eachPage ( wrappedCallback ) ; }

Enumerates over individual items of a request, paging the responses if
necessary.

@api experimental
@since v1.4.0

Enumerates over individual items of a request paging the responses if necessary .


function createReadStream() {
    var streams = AWS.util.nodeRequire('stream');
    var req = this;
    var stream = null;
    var legacyStreams = false;

    if (AWS.HttpClient.streamsApiVersion === 2) {
      stream = new streams.Readable();
      stream._read = function() {};
    } else {
      stream = new streams.Stream();
      stream.readable = true;
    }

    stream.sent = false;
    stream.on('newListener', function(event) {
      if (!stream.sent && (event === 'data' || event === 'readable')) {
        if (event === 'data') legacyStreams = true;
        stream.sent = true;
        process.nextTick(function() { req.send(function() { }); });
      }
    });

    this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) {
      if (statusCode < 300) {
        this.httpRequest._streaming = true;

        req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA);
        req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR);
        req.on('httpError', function streamHttpError(error, resp) {
          resp.error = error;
          resp.error.retryable = false;
        });

        var httpStream = resp.httpResponse.stream;
        if (legacyStreams) {
          httpStream.on('data', function(arg) {
            stream.emit('data', arg);
          });
          httpStream.on('end', function() {
            stream.emit('end');
          });
        } else {
          httpStream.on('readable', function() {
            var chunk;
            do {
              chunk = httpStream.read();
              if (chunk !== null) stream.push(chunk);
            } while (chunk !== null);
            stream.read(0);
          });
          httpStream.on('end', function() {
            stream.push(null);
          });
        }

        httpStream.on('error', function(err) {
          stream.emit('error', err);
        });
      }
    });

    this.on('error', function(err) {
      stream.emit('error', err);
    });

    return stream;
  }

function createReadStream ( ) { var streams = AWS . util . nodeRequire ( 'stream' ) ; var req = this ; var stream = null ; var legacyStreams = false ; if ( AWS . HttpClient . streamsApiVersion === 2 ) { stream = new streams . Readable ( ) ; stream . _read = function ( ) { } ; } else { stream = new streams . Stream ( ) ; stream . readable = true ; } stream . sent = false ; stream . on ( 'newListener' , function ( event ) { if ( ! stream . sent && ( event === 'data' || event === 'readable' ) ) { if ( event === 'data' ) legacyStreams = true ; stream . sent = true ; process . nextTick ( function ( ) { req . send ( function ( ) { } ) ; } ) ; } } ) ; this . on ( 'httpHeaders' , function streamHeaders ( statusCode , headers , resp ) { if ( statusCode < 300 ) { this . httpRequest . _streaming = true ; req . removeListener ( 'httpData' , AWS . EventListeners . Core . HTTP_DATA ) ; req . removeListener ( 'httpError' , AWS . EventListeners . Core . HTTP_ERROR ) ; req . on ( 'httpError' , function streamHttpError ( error , resp ) { resp . error = error ; resp . error . retryable = false ; } ) ; var httpStream = resp . httpResponse . stream ; if ( legacyStreams ) { httpStream . on ( 'data' , function ( arg ) { stream . emit ( 'data' , arg ) ; } ) ; httpStream . on ( 'end' , function ( ) { stream . emit ( 'end' ) ; } ) ; } else { httpStream . on ( 'readable' , function ( ) { var chunk ; do { chunk = httpStream . read ( ) ; if ( chunk !== null ) stream . push ( chunk ) ; } while ( chunk !== null ) ; stream . read ( 0 ) ; } ) ; httpStream . on ( 'end' , function ( ) { stream . push ( null ) ; } ) ; } httpStream . on ( 'error' , function ( err ) { stream . emit ( 'error' , err ) ; } ) ; } } ) ; this . on ( 'error' , function ( err ) { stream . emit ( 'error' , err ) ; } ) ; return stream ; }

Converts the request object into a readable stream that
can be read from or piped into a writable stream.

@note The data read from a readable stream contains only
the raw HTTP body contents.
@example Manually reading from a stream
request.createReadStream().on('data', function(data) {
console.log("Got data:", data.toString());
});
@example Piping a request body into a file
var out = fs.createWriteStream('/path/to/outfile.jpg');
s3.service.getObject(params).createReadStream().pipe(out);
@return [Stream] the readable stream object that can be piped
or read from (by registering 'data' event listeners).
@!macro nobrowser

Converts the request object into a readable stream that can be read from or piped into a writable stream .


function constructor(service, state) {
    this.service = service;
    this.state = state;

    if (typeof this.state === 'object') {
      AWS.util.each.call(this, this.state, function (key, value) {
        this.state = key;
        this.expectedValue = value;
      });
    }

    this.loadWaiterConfig(this.state);
    if (!this.expectedValue) {
      this.expectedValue = this.config.successValue;
    }
  }

function constructor ( service , state ) { this . service = service ; this . state = state ; if ( typeof this . state === 'object' ) { AWS . util . each . call ( this , this . state , function ( key , value ) { this . state = key ; this . expectedValue = value ; } ) ; } this . loadWaiterConfig ( this . state ) ; if ( ! this . expectedValue ) { this . expectedValue = this . config . successValue ; } }

Waits for a given state on a service object
@param service [Service] the service object to wait on
@param state [String] the state (defined in waiter configuration) to wait
for.
@example Create a waiter for running EC2 instances
var ec2 = new AWS.EC2;
var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');


function checkSuccess(resp) {
    if (!this.config.successPath) {
      return resp.httpResponse.statusCode < 300;
    }

    var r = AWS.util.jamespath.find(this.config.successPath, resp.data);

    if (this.config.failureValue &&
        this.config.failureValue.indexOf(r) >= 0) {
      return null; // fast fail
    }

    if (this.expectedValue) {
      return r === this.expectedValue;
    } else {
      return r ? true : false;
    }
  }

function
checkSuccess
(
resp
)
{
if
(
!
this
.
config
.
successPath
)
{
return
resp
.
httpResponse
.
statusCode
<
300
;
}
var
r
=
AWS
.
util
.
jamespath
.
find
(
this
.
config
.
successPath
,
resp
.
data
)
;
if
(
this
.
config
.
failureValue
&&
this
.
config
.
failureValue
.
indexOf
(
r
)
>=
0
)
{
return
;
// fast fail
}
if
(
this
.
expectedValue
)
{
return
r
===
this
.
expectedValue
;
}
else
{
return
r
true
:
false
;
}
}

Checks if the terminal expected success state has been met
@return [Boolean]


function checkError(resp) {
    var value = this.config.successValue;
    if (typeof value === 'number') {
      return resp.httpResponse.statusCode === value;
    } else {
      return resp.error && resp.error.code === value;
    }
  }

function checkError ( resp ) { var value = this . config . successValue ; if ( typeof value === 'number' ) { return resp . httpResponse . statusCode === value ; } else { return resp . error && resp . error . code === value ; } }

Checks if the terminal expected error state has been met
@return [Boolean]


function SharedIniFileCredentials(options) {
    AWS.Credentials.call(this);

    options = options || {};

    this.filename = options.filename;
    this.profile = options.profile || process.env.AWS_PROFILE || 'default';
    this.get(function() {});
  }

function SharedIniFileCredentials ( options ) { AWS . Credentials . call ( this ) ; options = options || { } ; this . filename = options . filename ; this . profile = options . profile || process . env . AWS_PROFILE || 'default' ; this . get ( function ( ) { } ) ; }

Creates a new SharedIniFileCredentials object.

@param options [map] a set of options
@option options profile [String] (AWS_PROFILE env var or 'default')
the name of the profile to load.
@option options filename [String] ('~/.aws/credentials') the filename
to use when loading credentials.

Creates a new SharedIniFileCredentials object .


function getId(callback) {
    var self = this;
    if (typeof self.params.IdentityId === 'string') return callback();

    self.cognito.getId(function(err, data) {
      if (!err && data.IdentityId) {
        self.params.IdentityId = data.IdentityId;
      }
      callback(err, data);
    });
  }

function getId ( callback ) { var self = this ; if ( typeof self . params . IdentityId === 'string' ) return callback ( ) ; self . cognito . getId ( function ( err , data ) { if ( ! err && data . IdentityId ) { self . params . IdentityId = data . IdentityId ; } callback ( err , data ) ; } ) ; }

Retrieves a Cognito ID, loading from cache if it was already retrieved
on this device.

@note If not loaded explicitly, the Cognito ID is loaded and stored in
localStorage in the browser environment of a device.

Retrieves a Cognito ID loading from cache if it was already retrieved on this device .


function(collection, key, ip) {
    if (!collection) {
        collection = {};
    }

    if (!collection[key]) {
        collection[key] = [];
    }

    collection[key].push(ip);
}

function ( collection , key , ip ) { if ( ! collection ) { collection = { } ; } if ( ! collection [ key ] ) { collection [ key ] = [ ] ; } collection [ key ] . push ( ip ) ; }

Finds the appropriate block or
bucket for the given IP to be
inserted in. Another way
@param key
@param ip

Finds the appropriate block or bucket for the given IP to be inserted in . Another way