Пример #1
0
def reduce(source: ObservableBase,
           accumulator: Callable[[Any, Any], Any],
           seed: Any = None) -> ObservableBase:
    """Applies an accumulator function over an observable sequence,
    returning the result of the aggregation as a single element in the
    result sequence. The specified seed value is used as the initial
    accumulator value.

    For aggregation behavior with incremental intermediate results, see
    Observable.scan.

    Example:
    1 - res = source.reduce(lambda acc, x: acc + x)
    2 - res = source.reduce(lambda acc, x: acc + x, 0)

    Keyword arguments:
    :param types.FunctionType accumulator: An accumulator function to be
        invoked on each element.
    :param T seed: Optional initial accumulator value.

    :returns: An observable sequence containing a single element with the
        final accumulator value.
    :rtype: Observable
    """

    if seed is not None:
        return source.scan(accumulator, seed=seed).start_with(seed).last()
    else:
        return source.scan(accumulator).last()
Пример #2
0
    def partial(source: ObservableBase) -> ObservableBase:
        if key_mapper:
            return source.map(key_mapper).average()

        def accumulator(prev, cur):
            return AverageValue(sum=prev.sum + cur, count=prev.count + 1)

        def mapper(s):
            if s.count == 0:
                raise Exception('The input sequence was empty')

            return s.sum / float(s.count)

        seed = AverageValue(sum=0, count=0)
        return source.scan(accumulator, seed).last().map(mapper)
Пример #3
0
def first_or_default(source: ObservableBase,
                     predicate: Predicate = None,
                     default_value: Any = None) -> ObservableBase:
    """Returns the first element of an observable sequence that
    satisfies the condition in the predicate, or a default value if no
    such element exists.

    Example:
    res = source.first_or_default()
    res = source.first_or_default(lambda x: x > 3)
    res = source.first_or_default(lambda x: x > 3, 0)
    res = source.first_or_default(null, 0)

    Keyword arguments:
    source -- Observable sequence.
    predicate -- [optional] A predicate function to evaluate for
        elements in the source sequence.
    default_value -- [Optional] The default value if no such element
        exists.  If not specified, defaults to None.

    Returns {Observable} Sequence containing the first element in the
    observable sequence that satisfies the condition in the predicate,
    or a default value if no such element exists.
    """

    return source.filter(predicate).first_or_default(
        None, default_value) if predicate else first_or_default_async(
            source, True, default_value)
Пример #4
0
 def partial(source: ObservableBase) -> List[ObservableBase]:
     published = source.publish().ref_count()
     return [
         published.filteri(predicate_indexed),
         published.filteri(
             predicate_indexed=lambda x, i: not predicate_indexed(x, i))
     ]
Пример #5
0
def group_by(source: ObservableBase,
             key_mapper,
             element_mapper=None) -> ObservableBase:
    """Groups the elements of an observable sequence according to a
    specified key mapper function and comparer and selects the resulting
    elements by using a specified function.

    1 - observable.group_by(lambda x: x.id)
    2 - observable.group_by(lambda x: x.id, lambda x: x.name)
    3 - observable.group_by(
        lambda x: x.id,
        lambda x: x.name,
        lambda x: str(x))

    Keyword arguments:
    key_mapper -- A function to extract the key for each element.
    element_mapper -- [Optional] A function to map each source element to
        an element in an observable group.

    Returns a sequence of observable groups, each of which corresponds to a
    unique key value, containing all elements that share that same key
    value.
    """
    def duration_mapper(_):
        return Observable.never()

    return source.group_by_until(key_mapper, element_mapper, duration_mapper)
Пример #6
0
def single_or_default(source: ObservableBase,
                      predicate: Predicate = None,
                      default_value: Any = None) -> ObservableBase:
    """Returns the only element of an observable sequence that matches
    the predicate, or a default value if no such element exists this
    method reports an exception if there is more than one element in the
    observable sequence.

    Example:
    res = source.single_or_default()
    res = source.single_or_default(lambda x: x == 42)
    res = source.single_or_default(lambda x: x == 42, 0)
    res = source.single_or_default(None, 0)

    Keyword arguments:
    predicate -- [Optional] A predicate function to evaluate for
        elements in the source sequence.
    default_value -- [Optional] The default value if the index is
        outside the bounds of the source sequence.

    Returns observable Sequence containing the single element in the
    observable sequence that satisfies the condition in the predicate,
    or a default value if no such element exists.
    """

    return source.filter(predicate).single_or_default(
        None, default_value) if predicate else single_or_default_async(
            source, True, default_value)
Пример #7
0
def partition(
        source: ObservableBase,
        predicate: Predicate = None,
        predicate_indexed: PredicateIndexed = None) -> List[ObservableBase]:
    """Returns two observables which partition the observations of the
    source by the given function. The first will trigger observations for
    those values for which the predicate returns true. The second will
    trigger observations for those values where the predicate returns false.
    The predicate is executed once for each subscribed observer. Both also
    propagate all error observations arising from the source and each
    completes when the source completes.

    Keyword arguments:
    predicate -- The function to determine which output Observable will
        trigger a particular observation.

    Returns a list of observables. The first triggers when the predicate
    returns True, and the second triggers when the predicate returns False.
    """

    published = source.publish().ref_count()
    return [
        published.filter(predicate=predicate,
                         predicate_indexed=predicate_indexed),
        published.filter(predicate_indexed=lambda x, i: not (predicate(
            x) if predicate else predicate_indexed(x, i)))
    ]
Пример #8
0
def replay(
    source: ObservableBase,
    mapper: Mapper = None,
    buffer_size: int = None,
    window: timedelta = None,
    scheduler: Scheduler = None
) -> Union[ObservableBase, ConnectableObservable]:
    """Returns an observable sequence that is the result of invoking the
    mapper on a connectable observable sequence that shares a single
    subscription to the underlying sequence replaying notifications
    subject to a maximum time length for the replay buffer.

    This operator is a specialization of Multicast using a
    ReplaySubject.

    Example:
    res = source.replay(buffer_size=3)
    res = source.replay(buffer_size=3, window=500)
    res = source.replay(None, 3, 500)
    res = source.replay(lambda x: x.take(6).repeat(), 3, 500)

    Keyword arguments:
    mapper -- [Optional] Selector function which can use the multicasted
        source sequence as many times as needed, without causing
        multiple subscriptions to the source sequence. Subscribers to
        the given source will receive all the notifications of the
        source subject to the specified replay buffer trimming policy.
    buffer_size -- [Optional] Maximum element count of the replay
        buffer.
    window -- [Optional] Maximum time length of the replay buffer.

    Returns an observable sequence that contains the elements of a
    sequence produced by multicasting the source sequence within a
    mapper function.
    """

    if mapper:

        def subject_factory(scheduler):
            return ReplaySubject(buffer_size, window, scheduler)

        return source.multicast(subject_factory=subject_factory, mapper=mapper)

    return source.multicast(ReplaySubject(buffer_size, window, scheduler))
Пример #9
0
def mode(source: ObservableBase) -> ObservableBase:
    """
    Returns the most frequently emitted value (or "values" if they have the same number of occurrences).
    The sequence must be finite.
    """
    return source.group_by(lambda v: v) \
        .flat_map(lambda grp: grp.count().map(lambda ct: (grp.key, ct))) \
        .to_sorted_list(lambda t: t[1], reverse=True) \
        .flat_map(lambda l: Observable.from_(l).take_while(lambda t: t[1] == l[0][1])) \
        .map(lambda t: t[0])
Пример #10
0
def share(source: ObservableBase) -> ObservableBase:
    """Share a single subscription among multple observers.

    Returns a new Observable that multicasts (shares) the original
    Observable. As long as there is at least one Subscriber this
    Observable will be subscribed and emitting data. When all
    subscribers have unsubscribed it will unsubscribe from the source
    Observable.

    This is an alias for Observable.publish().ref_count().
    """
    return source.publish().ref_count()
Пример #11
0
def variance(source: ObservableBase) -> ObservableBase:
    """
    Returns the statistical variance of the numerical emissions.
    The sequence must be finite.
    """
    squared_values = source.to_list() \
        .flat_map(lambda l: Observable.from_(l).average().flat_map(lambda avg: Observable.from_(l).map(lambda i: i - avg))) \
        .map(lambda i: i * i) \
        .publish() \
        .auto_connect(2)

    return Observable.zip(squared_values.sum(), squared_values.count(), lambda sum, ct: sum / (ct - 1))
Пример #12
0
def do_while(condition: Callable[[Any], bool], source: ObservableBase) -> ObservableBase:
    """Repeats source as long as condition holds emulating a do while loop.

    Keyword arguments:
    condition -- The condition which determines if the source
        will be repeated.

    Returns an observable {Observable} sequence which is repeated as long
    as the condition holds.
    """

    return source.concat(Observable.while_do(condition, source))
Пример #13
0
def count(source: ObservableBase, predicate=None) -> ObservableBase:
    """Returns an observable sequence containing a value that represents
    how many elements in the specified observable sequence satisfy a
    condition if provided, else the count of items.

    1 - res = source.count()
    2 - res = source.count(lambda x: x > 3)

    Keyword arguments:
    source -- Observable sequence.
    predicate -- A function to test each element for a condition.

    Returns an observable sequence containing a single element with a
    number that represents how many elements in the input sequence
    satisfy the condition in the predicate function if provided, else
    the count of items in the sequence.
    """

    if predicate:
        return source.filter(predicate).count()
    else:
        return source.reduce(lambda count, _: count + 1, seed=0)
Пример #14
0
    def partial(source: Observable) -> Observable:
        nonlocal skip

        if skip is None:
            skip = count

        def mapper(value):
            return value.to_iterable().map(list)

        def predicate(value):
            return len(value) > 0

        return source.window_with_count(
            count, skip).flat_map(mapper).filter(predicate)
Пример #15
0
def pluck(source: ObservableBase, key: Any) -> ObservableBase:
    """Retrieves the value of a specified key using dict-like access (as in
    element[key]) from all elements in the Observable sequence.

    Keyword arguments:
    key -- The key to pluck.

    Returns a new Observable {Observable} sequence of key values.

    To pluck an attribute of each element, use pluck_attr.

    """

    return source.map(lambda x: x[key])
Пример #16
0
def pluck_attr(source: ObservableBase, prop: str) -> ObservableBase:
    """Retrieves the value of a specified property (using getattr) from
    all elements in the Observable sequence.

    Keyword arguments:
    property -- The property to pluck.

    Returns a new Observable {Observable} sequence of property values.

    To pluck values using dict-like access (as in element[key]) on each
    element, use pluck.

    """

    return source.map(lambda x: getattr(x, prop))
Пример #17
0
    def partial(source: ObservableBase) -> ObservableBase:
        def subscribe(observer, scheduler=None):
            def on_next(_):
                observer.on_next(True)
                observer.on_completed()

            def on_error():
                observer.on_next(False)
                observer.on_completed()

            return source.subscribe_(on_next, observer.on_error, on_error,
                                     scheduler)

        return source.filter(
            predicate).some() if predicate else AnonymousObservable(subscribe)
Пример #18
0
def do(source: ObservableBase, observer: Observer) -> ObservableBase:
    """Invokes an action for each element in the observable sequence and
    invokes an action on graceful or exceptional termination of the
    observable sequence. This method can be used for debugging, logging,
    etc. of query behavior by intercepting the message stream to run
    arbitrary actions for messages on the pipeline.

    1 - observable.do(observer)

    observer -- Observer

    Returns the source sequence with the side-effecting behavior
    applied.
    """

    return source.do_action(observer.on_next, observer.on_error,
                            observer.on_completed)
Пример #19
0
def single(source: ObservableBase,
           predicate: Predicate = None) -> ObservableBase:
    """Returns the only element of an observable sequence that satisfies the
    condition in the optional predicate, and reports an exception if there
    is not exactly one element in the observable sequence.

    Example:
    res = source.single()
    res = source.single(lambda x: x == 42)

    Keyword arguments:
    predicate -- [Optional] A predicate function to evaluate for
        elements in the source sequence.

    Returns observable sequence containing the single element in the
    observable sequence that satisfies the condition in the predicate.
    """

    return source.filter(predicate).single() if predicate else \
        single_or_default_async(source, False)
Пример #20
0
    def partial(source: ObservableBase):
        if result_mapper_indexed:

            def projection(x: Any, idx: int) -> Any:
                mapper_result = mapper_indexed(x, idx)
                if isinstance(mapper_result, collections.abc.Iterable):
                    result = Observable.from_(mapper_result)
                else:
                    result = Observable.from_future(
                        mapper_result) if is_future(
                            mapper_result) else mapper_result

                return result.mapi(lambda y, i: result_mapper_indexed(x, y, i))

            return source.flat_mapi(mapper_indexed=projection)

        if callable(mapper_indexed):
            ret = _flat_map(source, mapper_indexed=mapper_indexed)
        else:
            ret = _flat_map(source, mapper=lambda _: mapper_indexed)
        return ret
Пример #21
0
def contains(source: ObservableBase,
             value: Any,
             comparer=None) -> ObservableBase:
    """Determines whether an observable sequence contains a specified
    element with an optional equality comparer.

    Example
    1 - res = source.contains(42)
    2 - res = source.contains({ "value": 42 }, lambda x, y: x["value"] == y["value")

    Keyword parameters:
    source -- Observable sequence.
    value -- The value to locate in the source sequence.
    comparer -- [Optional] An equality comparer to compare elements.

    Returns an observable  sequence containing a single element
    determining whether the source sequence contains an element that has
    the specified value.
    """

    comparer = comparer or default_comparer
    return source.filter(lambda v: comparer(v, value)).some()
Пример #22
0
 def partial(source: Observable) -> Observable:
     return source.filter(predicate).first(
     ) if predicate else first_or_default_async(source, False)
Пример #23
0
def standard_deviation(source: ObservableBase) -> ObservableBase:
    """
    Returns the standard deviation of the numerical emissions:
    The sequence must be finite.
    """
    return source.variance().map(lambda i: math.sqrt(i))
Пример #24
0
 def partial(source: ObservableBase) -> ObservableBase:
     return source.pipe(filter(lambda v: not predicate(v)), some(),
                        map(lambda b: not b))
Пример #25
0
 def partial(source: ObservableBase) -> List[ObservableBase]:
     published = source.publish().ref_count()
     return [
         published.filter(predicate),
         published.filter(lambda x: not predicate(x))
     ]
Пример #26
0
def median(source: ObservableBase) -> ObservableBase:
    """
    Calculates the statistical median on numerical emissions. The sequence must be finite.
    """
    return source.to_sorted_list().map(lambda l: determine_median(l))
Пример #27
0
 def partial(source: Observable) -> Observable:
     return source.filter(predicate).first_or_default(
         None, default_value) if predicate else first_or_default_async(
             source, True, default_value)
Пример #28
0
 def partial(source: Observable) -> Observable:
     return source.do_action(observer.on_next, observer.on_error,
                             observer.on_completed)
Пример #29
0
    def partial(source: Observable) -> Observable:
        if predicate:
            return source.filter(predicate).count()

        return source.reduce(lambda count, _: count + 1, seed=0)
Пример #30
0
 def partial(source: Observable) -> Observable:
     return source.window(buffer_openings, buffer_closing_mapper).flat_map(
         lambda item: item.to_iterable().map(list))