def _window_to_group(self, value): return value.pipe( ops.to_iterable(), ops.map( lambda x: rx.from_iterable(x).pipe(ops.group_by( _group_by), ops.map(_group_to_batch), ops.merge_all())), ops.merge_all())
def on_mouse_up(self) -> Observable[MouseButtonEvent]: return self.on_state_change.pipe( ops.map(lambda s: s.buttons), ops.distinct_until_changed(), ops.pairwise(), ops.flat_map(lambda b: b[0] - b[1]), ops.map(lambda b: MouseUpEvent(self, self.state.unwrap(), b)))
def action1(scheduler, state): xs[0] = reactivex.from_iterable( ["alpha", "apple", "beta", "bat", "gamma"] ).pipe( ops.group_by(lambda s: s[0]), ops.map(lambda xs: xs.pipe(ops.to_iterable(), ops.map(list))), ops.merge_all(), )
def main(): app = QApplication(sys.argv) scheduler = QtScheduler(QtCore) window = Window() window.show() text = "TIME FLIES LIKE AN ARROW" def on_next(info): label, (x, y), i = info label.move(x + i * 12 + 15, y) label.show() def handle_label(label, i): delayer = ops.delay(i * 0.100) mapper = ops.map(lambda xy: (label, xy, i)) return window.mousemove.pipe( delayer, mapper, ) labeler = ops.flat_map_indexed(handle_label) mapper = ops.map(lambda c: QLabel(c, window)) reactivex.from_(text).pipe( mapper, labeler, ).subscribe(on_next, on_error=print, scheduler=scheduler) sys.exit(app.exec_())
def mapper(ys, i): def proj(y): return "%s %s" % (i, y) return ys.pipe( ops.map(proj), ops.concat(reactivex.return_value("%s end" % i)))
def main() -> None: root = Tk() root.title("Rx for Python rocks") scheduler = TkinterScheduler(root) mousemoves: Subject[Event[Any]] = Subject() frame = Frame(root, width=600, height=600) frame.bind("<Motion>", mousemoves.on_next) text = "TIME FLIES LIKE AN ARROW" def on_next(info: Tuple[tkinter.Label, "Event[Frame]", int]) -> None: label, ev, i = info label.place(x=ev.x + i * 12 + 15, y=ev.y) def label2stream( label: tkinter.Label, index: int ) -> Observable[Tuple[tkinter.Label, "Event[Frame]", int]]: return mousemoves.pipe( ops.map(lambda ev: (label, ev, index)), ops.delay(index * 0.1), ) def char2label(char: str) -> Label: return Label(frame, text=char, borderwidth=0, padx=0, pady=0) reactivex.from_(text).pipe( ops.map(char2label), ops.flat_map_indexed(label2stream), ).subscribe(on_next, on_error=print, scheduler=scheduler) frame.pack() root.mainloop()
def main(): xs = reactivex.from_marbles("1-2-3-4-5-6-7-9-|").pipe(ops.publish()) xs.pipe(ops.map(failing), ops.retry()).subscribe(print) xs.connect() # Must connect. Cannot use ref_count() with publish() time.sleep(5)
def open(self): scheduler = AsyncIOScheduler(asyncio.get_event_loop()) print("WebSocket opened") # A Subject is both an observable and observer, so we can both subscribe # to it and also feed (send) it with new values self.subject: Subject[Dict[str, str]] = Subject() # Get all distinct key up events from the input and only fire if long enough and distinct searcher = self.subject.pipe( ops.map(lambda x: x["term"]), ops.filter(lambda text: len(text) > 2 ), # Only if the text is longer than 2 characters ops.debounce(0.750), # Pause for 750ms ops.distinct_until_changed(), # Only if the value has changed ops.flat_map_latest(search_wikipedia), ) def send_response(x: HTTPResponse) -> None: self.write_message(x.body) def on_error(ex: Exception): print(ex) searcher.subscribe(on_next=send_response, on_error=on_error, scheduler=scheduler)
def main(): parse_row.progress = 0 url = "https://github.com/influxdata/influxdb-client-python/wiki/data/stock-prices-example.csv" response = requests.get(url, stream=True) data = rx \ .from_iterable(DictReader(response.iter_lines(decode_unicode=True))) \ .pipe(ops.map(lambda row: parse_row(row))) client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org", debug=False) write_api = client.write_api( write_options=WriteOptions(batch_size=50_000, flush_interval=10_000)) write_api.write(bucket="my-bucket", record=data) write_api.close() query = ''' from(bucket:"my-bucket") |> range(start: 0, stop: now()) |> filter(fn: (r) => r._measurement == "financial-analysis") |> filter(fn: (r) => r.symbol == "AAPL") |> filter(fn: (r) => r._field == "close") |> drop(columns: ["_start", "_stop", "table", "_field","_measurement"]) ''' result = client.query_api().query_data_frame(query=query) print(result.head(100)) """ Close client """ client.close()
def test_map_disposeinsidemapper(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(100, 1), on_next(200, 2), on_next(500, 3), on_next(600, 4) ) results = scheduler.create_observer() d = SerialDisposable() invoked = [0] def projection(x, *args, **kw): invoked[0] += 1 if scheduler.clock > 400: d.dispose() return x d.disposable = xs.pipe(map(projection)).subscribe(results, scheduler) def action(scheduler, state): return d.dispose() scheduler.schedule_absolute(ReactiveTest.disposed, action) scheduler.start() assert results.messages == [on_next(100, 1), on_next(200, 2)] assert xs.subscriptions == [ReactiveTest.subscribe(0, 500)] assert invoked[0] == 3
def create(): def mapper(x): return TimeInterval(x.value, x.interval) return xs.pipe( ops.time_interval(), ops.map(mapper), )
def _retryable(self, data: str, delay: datetime.timedelta): return rx.of(data).pipe( ops.delay(duetime=delay, scheduler=self._scheduler), ops.map(lambda x: self._http(x)), ops.catch(handler=lambda exception, source: self._retry_handler( exception, source, data)), )
def handle_label(label, i): delayer = ops.delay(i * 0.100) mapper = ops.map(lambda xy: (label, xy, i)) return window.mousemove.pipe( delayer, mapper, )
def factory(scheduler_: Optional[abc.SchedulerBase] = None): _scheduler = scheduler or scheduler_ or TimeoutScheduler.singleton( ) def mapper(value: _T) -> Timestamp[_T]: return Timestamp(value=value, timestamp=_scheduler.now) return source.pipe(operators.map(mapper))
def create(): def mapper(x): return Timestamp(x.value, x.timestamp) return xs.pipe( ops.timestamp(), ops.map(mapper), )
def label2stream( label: tkinter.Label, index: int ) -> Observable[Tuple[tkinter.Label, "Event[Frame]", int]]: return mousemoves.pipe( ops.map(lambda ev: (label, ev, index)), ops.delay(index * 0.1), )
def factory(): def key_mapper(x): key_invoked[0] += 1 return x.lower().strip() return xs.pipe( ops.group_by(key_mapper, lambda x: x), ops.map(lambda g: g.key), )
def factory(): def projection(x): invoked[0] += 1 if invoked[0] == 3: raise Exception(ex) return x + 1 return xs.pipe(map(projection))
def test_map_throws(self): mapper = map(lambda x: x) with self.assertRaises(RxException): return_value(1).pipe(mapper).subscribe(lambda x: _raise("ex")) with self.assertRaises(RxException): throw("ex").pipe(mapper).subscribe(on_error=lambda ex: _raise(ex)) with self.assertRaises(RxException): empty().pipe(mapper).subscribe( lambda x: x, lambda ex: ex, lambda: _raise("ex") ) def subscribe(observer, scheduler=None): _raise("ex") with self.assertRaises(RxException): create(subscribe).pipe(map(lambda x: x)).subscribe()
def sum_( key_mapper: Optional[Mapper[Any, float]] = None ) -> Callable[[Observable[Any]], Observable[float]]: if key_mapper: return compose(ops.map(key_mapper), ops.sum()) def accumulator(prev: float, cur: float) -> float: return prev + cur return ops.reduce(seed=0, accumulator=accumulator)
def __init__(self) -> None: self._subject = Subject() self._scheduler = ThreadPoolScheduler(max_workers=1) obs = self._subject.pipe(ops.observe_on(self._scheduler)) self._disposable = obs \ .pipe(ops.window_with_time_or_count(count=5, timespan=datetime.timedelta(milliseconds=10_000)), ops.flat_map(lambda x: self._window_to_group(x)), ops.map(mapper=lambda x: self._retryable(data=x, delay=self._jitter_delay(jitter_interval=1000))), ops.merge_all()) \ .subscribe(self._result, self._error, self._on_complete) pass
def test_groupby_count(self): res = [] counts = reactivex.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)]
def factory(): def key_mapper(x): key_invoked[0] += 1 return x.lower().strip() def element_mapper(x): ele_invoked[0] += 1 return x[::-1] # Yes, this is reverse string in Python return xs.pipe( ops.group_by(key_mapper, element_mapper), ops.map(lambda g: g.key), )
def window_toggle(source: Observable[_T]) -> Observable[Observable[_T]]: def mapper(args: Tuple[Any, Observable[_T]]): _, window = args return window return openings.pipe( ops.group_join( source, closing_mapper, lambda _: empty(), ), ops.map(mapper), )
def factory(): def key_mapper(x): key_invoked[0] += 1 return x.lower().strip() def element_mapper(x): ele_invoked[0] += 1 return x[::-1] return xs.pipe( ops.group_by(key_mapper, element_mapper), ops.map(lambda g: g.key), )
def average(source: Observable[Any]) -> Observable[float]: """Partially applied average operator. Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. Examples: >>> res = average(source) Args: source: Source observable to average. Returns: An observable sequence containing a single element with the average of the sequence of values. """ key_mapper_: typing.Mapper[_T, float] = key_mapper or ( lambda x: float(cast(Any, x))) def accumulator(prev: AverageValue, cur: float) -> AverageValue: return AverageValue(sum=prev.sum + cur, count=prev.count + 1) def mapper(s: AverageValue) -> float: if s.count == 0: raise Exception("The input sequence was empty") return s.sum / float(s.count) seed = AverageValue(sum=0, count=0) ret = source.pipe( operators.map(key_mapper_), operators.scan(accumulator, seed), operators.last(), operators.map(mapper), ) return ret
def create(): def mapper(xy): x, y = xy return "{}{}".format(x.value, y.value) return xs.pipe( ops.join( ys, lambda x: reactivex.timer(x.interval), lambda y: reactivex.timer(y.interval), ), ops.map(mapper), )
def all_( predicate: Predicate[_T] ) -> Callable[[Observable[_T]], Observable[bool]]: def filter(v: _T): return not predicate(v) def mapping(b: bool) -> bool: return not b return compose( ops.filter(filter), ops.some(), ops.map(mapping), )
def pluck_attr_(prop: str) -> Callable[[Observable[Any]], Observable[Any]]: """Retrieves the value of a specified property (using getattr) from all elements in the Observable sequence. Args: 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 ops.map(lambda x: getattr(x, prop))
def is_empty_() -> Callable[[Observable[Any]], Observable[bool]]: """Determines whether an observable sequence is empty. Returns: An observable sequence containing a single element determining whether the source sequence is empty. """ def mapper(b: bool) -> bool: return not b return compose( ops.some(), ops.map(mapper), )