Exemple #1
0
def word_counter(file_name):
    # count words using `group_by()`
    # tuple the word with the count
    return words_from_file(file_name).pipe(
        ops.group_by(lambda word: word),
        ops.flat_map(lambda grp: grp.pipe(ops.count(),
                                          ops.map(lambda ct: (grp.key, ct)))))
Exemple #2
0
def subscribe_group_observable(group_observable):
    def print_count(count):
        print(f'Group key={group_observable.key} contains {count} items')

    group_observable.pipe(
        ops.count()
    ).subscribe(print_count)
Exemple #3
0
def _count(predicate: Predicate = None) -> Callable[[Observable], Observable]:

    if predicate:
        filtering = ops.filter(predicate)
        return pipe(filtering, ops.count())

    counter = ops.reduce(lambda n, _: n + 1, seed=0)
    return pipe(counter)
Exemple #4
0
def _count(predicate: Optional[Predicate] = None) -> Callable[[Observable], Observable]:

    if predicate:
        filtering = ops.filter(predicate)
        return pipe(filtering, ops.count())

    counter = ops.reduce(lambda n, _: n + 1, seed=0)
    return pipe(counter)
        def create():
            def predicate(x):
                if x == 3:
                    raise Exception(ex)
                else:
                    return True

            return xs.pipe(_.count(predicate))
 def test_count_some(self):
     scheduler = TestScheduler()
     xs = scheduler.create_hot_observable(
         on_next(150, 1),
         on_next(210, 2),
         on_next(220, 3),
         on_next(230, 4),
         on_completed(250))
     res = scheduler.start(create=lambda: xs.pipe(_.count())).messages
     assert res == [on_next(250, 3), on_completed(250)]
Exemple #7
0
    def test_groupby_count(self):
        res = []
        counts = rx.from_(range(10)).pipe(
            ops.group_by(lambda i: 'even' if i % 2 == 0 else 'odd'),
            ops.flat_map(lambda i: i.pipe(
                ops.count(),
                ops.map(lambda ii: (i.key, ii)),
            )))

        counts.subscribe(on_next=res.append)
        assert res == [('even', 5), ('odd', 5)]
Exemple #8
0
def run(onComplete=lambda: None):
    limit = 10 ** 22
    optimal_thread_count = multiprocessing.cpu_count()
    pool_scheduler = ThreadPoolScheduler(optimal_thread_count)

    count = rx.from_iterable(pandigital_step_numbers()) \
        .pipe(
        ops.take_while(lambda n: n < limit),
        ops.count(),
    ) \
        .run()

    onComplete(count)
def test_completion():
    data = [1, 2, 3]
    actual_data = []
    actual_completed = []

    rx.from_(data).pipe(
        rs.ops.tee_map(
            ops.count(),
            rs.math.sum(reduce=True),
        )
    ).subscribe(
        on_next=actual_data.append,
        on_completed=lambda: actual_completed.append(True)
    )

    assert actual_completed == [True]
    assert actual_data == [(3, 6)]
Exemple #10
0
def _solve_rx(print=print):
    """Benchmark: 15/1_000_000 takes 30s """
    print(f'\n\n\n***************')

    turns = 15
    game_count = 1_000_000

    #scheduler=rx.scheduler.CurrentThreadScheduler()
    scheduler = rx.scheduler.ThreadPoolScheduler(4)

    wins = rx.range(0,game_count,scheduler=scheduler)\
             .pipe(
                 ops.filter(lambda i: play_w(turns)),
                 ops.count()
             ).run()

    print(f'  Max prize: {math.floor(game_count/wins)}')

    print(f"Not done")
    return False
 def create():
     return xs.pipe(_.count(lambda _: True))
Exemple #12
0
import rx
from rx import operators as ops

rx.from_(["Alpha", "Beta", "Gamma",
          "Delta", "Epsilon"]).pipe(ops.filter(lambda s: len(s) != 5),
                                    ops.count()).subscribe(lambda i: print(i))
Exemple #13
0
print('-- window_with_count | FlatMap')
rx.from_(range(3)).pipe(ops.window_with_count(2),
                        ops.flat_map(lambda x: x)).subscribe(print_value)
# flatmap 은
# flat 하면 리스트를 푼다.
# [[1,2], [3]] -> [1,2,3]
# 그리고 나서 map 한다. x -> x
# [1, 2, 3] -> [1, 2, 3]

print('-- window_with_time')

test_scheduler = TestScheduler()
rx.interval(0.05, test_scheduler).pipe(ops.take_until(
    rx.timer(0.1)), ops.window_with_time(0.01)).subscribe(
        lambda observable: observable.pipe(ops.count()).subscribe(print_value))
test_scheduler.start()
time.sleep(0.5)
# 결과가 이게 맞나?? 단위가 뭐지?

print('-- combine_latest')
rx.combine_latest(
    rx.interval(0.1).pipe(ops.map(lambda x: 'a- {}'.format(x))),
    rx.interval(0.2).pipe(ops.map(lambda x: 'b- {}'.format(x)))).pipe(
        ops.take_until(rx.timer(0.5))).subscribe(print_value)
time.sleep(1)
# 누가 먼저 결과를 배출할지 예상 불가

print('-- zip')
rx.zip(
    rx.interval(0.1).pipe(ops.map(lambda x: 'a- {}'.format(x))),

rx.throw()
rx.interval()
rx.from_()
rx.interval()
rx.just()
rx.range()
rx.repeat_value()
rx.start()
rx.timer()

"""Mathematical"""
op.average()
op.concat()
op.count()
op.max()
op.min()
op.reduce()
op.sum()

"""Transformation"""
op.buffer()
op.group_by()
op.map()
op.scan()
# ...

"""Filtering"""
op.debounce()
op.distinct()
import rx
from rx import operators as ops

rx.from_(["Alpha", "Beta", "Gamma", "Delta", "Epsilon"]).pipe(
    ops.group_by(lambda s: len(s)),
    ops.flat_map(
        lambda grp: grp.pipe(ops.count(), ops.map(lambda ct: (grp.key, ct)))),
    ops.to_dict(lambda key_value: key_value[0],
                lambda key_value: key_value[1])).subscribe(lambda i: print(i))
Exemple #16
0
import rx
import rx.operators as ops

numbers = rx.from_([1, 2, 3, 4])

numbers.pipe(ops.count(lambda i: i > 2)).subscribe(
    on_next=lambda i: print("on_next {}".format(i)),
    on_error=lambda e: print("on_error: {}".format(e)),
    on_completed=lambda: print("on_completed"))
 def test_sample_file(self):
     self.source.observable().pipe(count()).subscribe(
         lambda aantal: assert_that(aantal, equal_to(34)),
         lambda e: fail(e))
Exemple #18
0
"""this operator takes in an observable with values, and converts it into observable
that will have single value. the count function takes in predicate function as an optional argument.
the function is of type boolean, and will add value to the output only, if it satisfies the condition

:parameter
    the count function takes in predicate function as an optional argument.
    the function is of type Boolean, and will add value to the output only, if it satisfies the condition.

:return
    it will return an observable with a single value, i.e. the count from the source observable.

"""

from rx import of, operators as op

test = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

sub1 = test.pipe(op.count(lambda x: x % 2)).subscribe(
    lambda x: print("the count is {}".format(x)))

# result
# the count is 5

# remove lambda argument the count is 10
 def test_count_never(self):
     scheduler = TestScheduler()
     xs = scheduler.create_hot_observable(on_next(150, 1))
     res = scheduler.start(create=lambda: xs.pipe(_.count())).messages
     assert res == []
 def test_count_on_error(self):
     ex = 'ex'
     scheduler = TestScheduler()
     xs = scheduler.create_hot_observable(on_next(150, 1), on_error(210, ex))
     res = scheduler.start(create=lambda: xs.pipe(_.count())).messages
     assert res == [on_error(210, ex)]
 def create():
     return xs.pipe(_.count(lambda x: x % 2 == 0))
 def create():
     return xs.pipe(_.count())
 def create():
     return xs.pipe(_.count(lambda _: False))
Exemple #24
0
            k3=random.randint(0, k3_range),
            data=random.random() * 1000,
        )


source = dataset(dataset_size)

rx.from_(source).pipe(
    rs.state.with_memory_store(
        rx.pipe(
            rs.ops.group_by(
                lambda i: i.k1,
                rx.pipe(
                    rs.ops.group_by(
                        lambda i: i.k2,
                        rx.pipe(
                            rs.data.roll(5, 5,
                                         rx.pipe(rs.ops.count(
                                             reduce=True), )), )), )), )),
    ops.count(),
).run()
'''
subscribe(
    on_next=lambda i: print(i),
    on_error=lambda e: print(e),
)
'''

print("done!")
time.sleep(5.0)