python/mozbuild/mozbuild/chunkify.py
author Shane Hughes <shughes@mozilla.com>
Sat, 24 Sep 2022 00:00:46 +0000
changeset 636388 50f72898d7b8b88985dc5d7595007b426a46c93e
parent 554551 994ae8e4833c90447d91f0e26a718573cff5a514
permissions -rw-r--r--
Bug 1789644 - Add a pref toggle for QuickActions, separate from the pref for suggestions. r=mak,daleharvey Change the behavior of the QuickActions provider, so that setting the pref `quickactions.enabled` to false will prevent showing quick action results in all contexts, while setting `suggest.quickactions` to false will only prevent showing quick action results in the default search mode (i.e., quick action results will still appear in the Quick Actions search mode enabled by typing `> ` in the urlbar). Differential Revision: https://phabricator.services.mozilla.com/D157702

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

# This file is a direct clone of
# https://github.com/bhearsum/chunkify/blob/master/chunkify/__init__.py
# of version 1.2. Its license (MPL2) is contained in repo root LICENSE file.
# Please make modifications there where possible.

from __future__ import absolute_import, print_function

from itertools import islice


class ChunkingError(Exception):
    pass


def split_evenly(n, chunks):
    """Split an integer into evenly distributed list

    >>> split_evenly(7, 3)
    [3, 2, 2]

    >>> split_evenly(12, 3)
    [4, 4, 4]

    >>> split_evenly(35, 10)
    [4, 4, 4, 4, 4, 3, 3, 3, 3, 3]

    >>> split_evenly(1, 2)
    Traceback (most recent call last):
        ...
    ChunkingError: Number of chunks is greater than number

    """
    if n < chunks:
        raise ChunkingError("Number of chunks is greater than number")
    if n % chunks == 0:
        # Either we can evenly split or only 1 chunk left
        return [n // chunks] * chunks
    # otherwise the current chunk should be a bit larger
    max_size = n // chunks + 1
    return [max_size] + split_evenly(n - max_size, chunks - 1)


def chunkify(things, this_chunk, chunks):
    if this_chunk > chunks:
        raise ChunkingError("this_chunk is greater than total chunks")

    dist = split_evenly(len(things), chunks)
    start = sum(dist[: this_chunk - 1])
    end = start + dist[this_chunk - 1]

    try:
        return things[start:end]
    except TypeError:
        return islice(things, start, end)