Esempio n. 1
0
        /**
        * Checks the indentation of a function's parameters
        * @param {ASTNode} node The node
        * @param {number} paramsIndent The indentation level option for the parameters
        * @returns {void}
        */
        function addFunctionParamsIndent(node, paramsIndent) {
            const openingParen = node.params.length ? sourceCode.getTokenBefore(node.params[0]) : sourceCode.getTokenBefore(node.body, 1);
            const closingParen = sourceCode.getTokenBefore(node.body);
            const nodeTokens = getTokensAndComments(node);
            const openingParenIndex = lodash.sortedIndexBy(nodeTokens, openingParen, token => token.range[0]);
            const closingParenIndex = lodash.sortedIndexBy(nodeTokens, closingParen, token => token.range[0]);
            const paramTokens = nodeTokens.slice(openingParenIndex, closingParenIndex + 1);

            parameterParens.add(paramTokens[0]);
            parameterParens.add(paramTokens[paramTokens.length - 1]);

            addElementListIndent(paramTokens, node.params, paramsIndent);
        }
Esempio n. 2
0
exports.search = function search(tokens, location) {
    return lodash.sortedIndexBy(
        tokens,
        { range: [location] },
        getStartLocation
    );
};
Esempio n. 3
0
  progressScrollHandler = _.debounce(function update_progress_on_scroll() {
    let viewportStart = $window.scrollTop() + navbar_height;

    // If we scroll below top border of the first topic,
    // show the secondary navbar
    //
    if ($('.dialog-list').offset().top < viewportStart) {
      $('.navbar').addClass('navbar__m-secondary');
    } else {
      $('.navbar').removeClass('navbar__m-secondary');
    }

    // Update progress bar
    //
    let dialogs         = document.getElementsByClassName('dialog-list-item');
    let dialogThreshold = $window.scrollTop() + navbar_height + TOP_OFFSET;
    let offset;
    let currentIdx;

    // Get offset of the first topic in the viewport
    //
    currentIdx = _.sortedIndexBy(dialogs, null, dlg => {
      if (!dlg) { return dialogThreshold; }
      return dlg.offsetTop;
    });

    currentIdx--;

    offset = currentIdx + dlgListState.first_offset;

    N.wire.emit(module.apiPath + '.blocks.page_progress:update', {
      current:  offset + 1, // `+1` because offset is zero based
      max:      dlgListState.dialog_count
    }).catch(err => N.wire.emit('error', err));
  }, 100, { maxWait: 100 });
Esempio n. 4
0
  locationScrollHandler = _.debounce(function update_location_on_scroll() {
    let media          = document.getElementById('users-media-list').getElementsByClassName('thumb-grid__item'),
        mediaThreshold = navbarHeight + TOP_OFFSET,
        currentIdx;

    // Get offset of the first media in the viewport
    //
    currentIdx = _.sortedIndexBy(media, null, medium => {
      if (!medium) { return mediaThreshold; }
      return medium.getBoundingClientRect().bottom;
    });

    if (currentIdx === 0) {
      if (!media.length || media[currentIdx].getBoundingClientRect().top > mediaThreshold) {
        currentIdx--;
      }
    }

    if (currentIdx >= media.length) { currentIdx = media.length - 1; }

    let href = null;
    let state = null;

    if (currentIdx >= 0 && media.length) {
      state = {
        media:  $(media[currentIdx]).data('media-id'),
        offset: mediaThreshold - media[currentIdx].getBoundingClientRect().top
      };
    }

    /* eslint-disable no-undefined */
    href = N.router.linkTo('users.album', {
      user_hid: mediaState.user_hid,
      album_id: mediaState.album_id,
      media_id: currentIdx >= 0 ? $(media[currentIdx]).data('media-id') : undefined
    });

    // all photos, 1st page    - noindex, nofollow
    // all photos, other pages - noindex, nofollow
    // album, 1st page         - index,   follow
    // album, other pages      - noindex, follow
    //
    let index  = mediaState.album_id && currentIdx < 0;
    let follow = mediaState.album_id;
    let tag    = $('meta[name="robots"]');

    if (index && follow) {
      tag.remove();
    } else {
      if (!tag.length) $('head').append(tag = $('<meta name="robots">'));

      tag.attr('content', (index  ? 'index'  : 'noindex') + ',' +
                          (follow ? 'follow' : 'nofollow'));
    }

    N.wire.emit('navigate.replace', { href, state })
          .catch(err => N.wire.emit('error', err));

  }, 500);
Esempio n. 5
0
function getDailyUsageHistogramInRange(statObj, startDateTime, endDateTime) {
    //statobj.timestamps must be sorted
    //start index is inclusive
    var startIdx = _.sortedIndexBy(statObj.timestamps, startDateTime),
        endIdx = _.sortedIndexBy(statObj.timestamps, endDateTime);
    return _
        .chain(statObj.timestamps)
        .map(function (time) {
            //to hours of day:
            var dateObj = new Date(time);
            //note: this is local time
            return dateObj.getHours();
        })
        .slice(startIdx, endIdx)
        .countBy()
        .value();
}
Esempio n. 6
0
 addEvent: function (event) {
 // splice the event and event name into the sorted collections
     var index = _.sortedIndexBy(this.events, event, function (o) {
         return o.name;
     });
     this.events.splice(index, 0, event);
     this.eventNames.splice(index, 0, event.name);
     return this;
 },
Esempio n. 7
0
export function getBoundsForInstantaeousData(timestampedData, timeRange, timestampPath = 'timestamp') {
  const lowerBound = _.set({}, timestampPath, timeRange.min);
  const upperBound = _.set({}, timestampPath, timeRange.max);

  const firstIndex = _.sortedIndexBy(timestampedData, lowerBound, timestampPath);
  const lastIndex = _.sortedLastIndexBy(timestampedData, upperBound, timestampPath);

  return adjustBounds(firstIndex, lastIndex, timestampedData.length);
}
Esempio n. 8
0
function nextTokenFromToken(tokenList, curToken) {
  const tokenIndex = _.sortedIndexBy(tokenList, curToken, _.property('start'))

  let nextTokenIndex = tokenIndex + 1
  while (nextTokenIndex < tokenList.length && tokenList[nextTokenIndex].channel !== 0) {
    nextTokenIndex += 1
  }

  return tokenList[nextTokenIndex]
}
Esempio n. 9
0
function prevTokenFromToken(tokenList, curToken) {
  const tokenIndex = _.sortedIndexBy(tokenList, curToken, _.property('start'))

  let prevTokenIndex = tokenIndex - 1
  while (prevTokenIndex >= 0 && tokenList[prevTokenIndex].channel !== 0) {
    prevTokenIndex -= 1
  }

  return tokenList[prevTokenIndex]
}
Esempio n. 10
0
    /**
     * Adds a new node to this collection. If a sort
     * method is configured, the node will be added
     * in the appropriate order.
     *
     * @category TreeNodes
     * @param {object} object Node
     * @return {TreeNode} Node object.
     */
    addNode(object) {
        // Base insertion index
        var index = this.length;

        // If tree is sorted, insert in correct position
        if (this._tree.config.sort) {
            index = _.sortedIndexBy(this, object, this._tree.config.sort);
        }

        return this.insertAt(index, object);
    }
Esempio n. 11
0
        /**
        * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
        * @param {ASTNode} node A CallExpression or NewExpression node
        * @returns {void}
        */
        function addFunctionCallIndent(node) {
            let openingParen;

            if (node.arguments.length) {
                openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken);
            } else {
                openingParen = sourceCode.getLastToken(node, 1);
            }
            const callExpressionTokens = getTokensAndComments(node);
            const tokens = callExpressionTokens.slice(lodash.sortedIndexBy(callExpressionTokens, openingParen, token => token.range[0]));

            parameterParens.add(tokens[0]);
            parameterParens.add(tokens[tokens.length - 1]);
            offsets.matchIndentOf(sourceCode.getLastToken(node.callee), openingParen);

            addElementListIndent(tokens, node.arguments, options.CallExpression.arguments);
        }
Esempio n. 12
0
        /**
        * Adds indentation for the right-hand side of binary/logical expressions.
        * @param {ASTNode} node A BinaryExpression or LogicalExpression node
        * @returns {void}
        */
        function addBinaryOrLogicalExpressionIndent(node) {
            const tokens = getTokensAndComments(node);
            const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
            const firstTokenAfterOperator = sourceCode.getTokenAfter(operator);
            const tokensAfterOperator = tokens.slice(lodash.sortedIndexBy(tokens, firstTokenAfterOperator, token => token.range[0]));

            /*
             * For backwards compatibility, don't check BinaryExpression indents, e.g.
             * var foo = bar &&
             *                   baz;
             */

            offsets.ignoreToken(operator);
            offsets.ignoreToken(tokensAfterOperator[0]);
            offsets.setDesiredOffset(tokensAfterOperator[0], sourceCode.getFirstToken(node), 1);
            offsets.setDesiredOffsets(tokensAfterOperator, tokensAfterOperator[0], 1);
        }
Esempio n. 13
0
/**
 *
 * @param {Number} A
 * @param {Number} B
 * @param {Number} sim
 * @returns {Array}
 */
function scoreUpdate(A, B, sim) {
  const update = [];
  if (!sim) return update;

  for (let [a, b] of [[A, B], [B, A]]) {
    let index = _.findIndex(items[a].r, {0: b});
    index > -1 && _.pullAt(items[a].r, index);

    if (sim >= MIN_SIMILARITY) {
      index = _.sortedIndexBy(items[a].r, [b, sim], 1);
      items[a].r.splice(index, 0, [b, sim]);
      update.push(['ZADD', `r:${a}`, sim, b]);
    } else {
      update.push(['ZREM', `r:${a}`, b]);
    }
  }
  return update;
}
Esempio n. 14
0
  locationScrollHandler = _.debounce(function update_location_on_scroll() {
    let dialogs         = document.getElementsByClassName('dialog-list-item');
    let dialogThreshold = $window.scrollTop() + navbar_height + TOP_OFFSET;
    let offset;
    let currentIdx;

    // Get offset of the first topic in the viewport
    //
    currentIdx = _.sortedIndexBy(dialogs, null, dlg => {
      if (!dlg) { return dialogThreshold; }
      return dlg.offsetTop;
    });

    if (currentIdx >= dialogs.length) {
      currentIdx = dialogs.length - 1;
    }

    let href = null;
    let state = null;

    offset = currentIdx + dlgListState.first_offset;

    if (currentIdx >= 0 && dialogs.length) {
      state = {
        dialog_id: $(dialogs[currentIdx]).data('dialog-id'),
        offset: dialogThreshold - dialogs[currentIdx].offsetTop
      };
    }

    // save current offset, and only update url if offset is different,
    // it protects url like /messages/4ecabbd0821e2864cda37762 from being overwritten instantly
    if (dlgListState.current_offset !== offset) {
      /* eslint-disable no-undefined */
      href = N.router.linkTo('users.dialogs_root', {
        dialog_id: state ? state.dialog_id : undefined
      });

      dlgListState.current_offset = offset;
    }

    N.wire.emit('navigate.replace', { href, state });
  }, 500);
Esempio n. 15
0
  _processIndex = (pointProfile) => {
    const timeOverSort = (point) => {
      const timestamp = new Date(point.timeOver);
      return timestamp;
    };

    let highlightIndex = _.sortedIndexBy(pointProfile, {timeOver: Date.now()}, timeOverSort) - 1;

    // Highlight the last row
    if(highlightIndex < 0) {
      highlightIndex = 0;
    }

    let scrollIndex = highlightIndex - 2;
    if(scrollIndex < 0) {
      scrollIndex = 0;
    }

    return {
      highlightIndex,
      scrollIndex,
    };
  };
        _.forEach(requestRepositoryPayload.newRequests, function(request) {
            if (!_data.index[request.id]) {
                var sortedIndex = 0;

                if (request._requestStartTime) {
                    sortedIndex = _.sortedIndexBy(_data.values, request, function(value) {
                        // TODO: This check wont really work because of the decending order logic
                        return value._requestStartTime ? moment(value._requestStartTime).valueOf() * -1 : 0;   // decending order
                    });
                }
                else {
                    // TODO: store in a list which marks it as being reconciled later
                }

                _data.values.splice(sortedIndex, 0, request);
            }
            else {
                // TODO: Perf wise this isn't great in terms of perf, fix later
                var currentIndex = _.findIndex(_data.values, [ 'id', request.id ]);
                _data.values[currentIndex] = request;
            }

            _data.index[request.id] = request;
        });
Esempio n. 17
0
        return {
            ArrayExpression: addArrayOrObjectIndent,
            ArrayPattern: addArrayOrObjectIndent,

            ArrowFunctionExpression(node) {
                addFunctionParamsIndent(node, options.FunctionExpression.parameters);
                if (node.body.type !== "BlockStatement") {
                    offsets.setDesiredOffsets(getTokensAndComments(node.body), sourceCode.getFirstToken(node), 1);
                }
            },

            AssignmentExpression(node) {
                const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
                const nodeTokens = getTokensAndComments(node);
                const tokensFromOperator = nodeTokens.slice(lodash.sortedIndexBy(nodeTokens, operator, token => token.range[0]));

                offsets.setDesiredOffsets(tokensFromOperator, sourceCode.getFirstToken(node.left), 1);
                offsets.ignoreToken(tokensFromOperator[0]);
                offsets.ignoreToken(tokensFromOperator[1]);
            },

            BinaryExpression: addBinaryOrLogicalExpressionIndent,

            BlockStatement: addBlockIndent,

            CallExpression: addFunctionCallIndent,

            ClassDeclaration: addClassIndent,

            ClassExpression: addClassIndent,
Esempio n. 18
0
    logs = Object.keys(logs).map(getPropertyValue, logs)

    if (!isEmpty(filter)) {
      logs = logs.filter(iteratee(filter))
    }

    logs.sort((a, b) => a.start - b.start)

    // only extract the range we are interested in
    const i =
      after === undefined
        ? 0
        : sortedIndexBy(
            logs,
            {
              start: typeof after === 'number' ? after : Date.now() - ms(after),
            },
            'start'
          )
    let j =
      before === undefined
        ? logs.length
        : sortedIndexBy(
            logs,
            {
              start:
                typeof before === 'number' ? before : Date.now() - ms(before),
            },
            'start'
          )
/**
 * Experimetns to test various ordering methods
 */

var _ = require('lodash');

var list = [
  {name: 'Home', position: 0},
  {name: 'About', position: 2},
  {name: 'Bananas', position: 1},
  {name: 'Contact', position: 5}
];

console.log('before', list);

list = _.orderBy(list, ['position', 'name']);


console.log('after', list);


var newItem = {name: 'newItem', position: 3};

var newIndex = _.sortedIndexBy(list, newItem, 'position');

console.log('newIndex', newIndex);

list.splice(newIndex, 0, newItem);

console.log('final', list);
Esempio n. 20
0

/**
 * _.range
 */
_.range(0, 10)[4] == 4
// $ExpectError string. This type is incompatible with number
_.range(0, 'a');
// $ExpectError string cannot be compared to number
_.range(0, 10)[4] == 'a';


/**
 * _.sortedIndexBy
 */
_.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, function(o) { return o.x; });
_.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');


/**
 * _.sortedLastIndexBy
 */
_.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, function(o) { return o.x; });
_.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');

/**
 * _.extend
 */
_.extend({a: 1}, {b: 2}).a
_.extend({a: 1}, {b: 2}).b
// $ExpectError property `c`. Property not found in object literal