Exemple #1
0
 def __init__(self):
     self.__stream__ = Subject()
Exemple #2
0
        def on_next(x):
            writer = None
            key = None

            try:
                key = key_selector(x)
            except Exception as e:
                for w in mapping.values():
                    w.on_error(e)

                observer.on_error(e)
                return

            fire_new_map_entry = False
            writer = mapping.get(key)
            if not writer:
                writer = Subject()
                mapping[key] = writer
                fire_new_map_entry = True

            if fire_new_map_entry:
                group = GroupedObservable(key, writer, ref_count_disposable)
                duration_group = GroupedObservable(key, writer)
                try:
                    duration = duration_selector(duration_group)
                except Exception as e:
                    for w in mapping.values():
                        w.on_error(e)

                    observer.on_error(e)
                    return

                observer.on_next(group)
                md = SingleAssignmentDisposable()
                group_disposable.add(md)

                def expire():
                    if mapping[key]:
                        del mapping[key]
                        writer.on_completed()

                    group_disposable.remove(md)

                def on_next(value):
                    pass

                def on_error(exn):
                    for wr in mapping.values():
                        wr.on_error(exn)
                    observer.on_error(exn)

                def on_completed():
                    expire()

                md.disposable = duration.take(1).subscribe(on_next, on_error, on_completed)

            try:
                element = element_selector(x)
            except Exception as e:
                for w in mapping.values():
                    w.on_error(e)

                observer.on_error(e)
                return

            writer.on_next(element)
Exemple #3
0
                WagtailPage.objects.live().public().specific(), info, **kwargs)

        # Return a specific page, identified by ID or Slug.
        def resolve_page(self, info, **kwargs):
            return get_specific_page(
                id=kwargs.get("id"),
                slug=kwargs.get("slug"),
                token=kwargs.get("token"),
                content_type=kwargs.get("content_type"),
            )

    return Mixin


# Subject to sync Django Signals to Observable
preview_subject = Subject()


@receiver(preview_update)
def on_updated(sender, token, **kwargs):
    preview_subject.on_next(token)


# Subscription Mixin
def PagesSubscription():
    def preview_observable(id, slug, token, content_type):
        return preview_subject.filter(
            lambda previewToken: previewToken == token).map(
                lambda token: get_specific_page(id, slug, token, content_type))

    class Mixin:
from rx import Observable
from rx.subjects import Subject

obs1 = Subject()
obs2 = Subject()
obs3 = Subject()
higher_order = Subject()

higher_order.switch_latest().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"))

higher_order.on_next(obs1)
obs1.on_next("1: 1")
obs1.on_next("1: 2")
higher_order.on_next(obs2)
obs1.on_next("1: 3")
obs2.on_next("2: 1")
obs2.on_next("2: 2")
higher_order.on_next(obs3)
obs2.on_next("2: 3")
obs3.on_next("3: 1")
obs3.on_next("3: 2")
Exemple #5
0
from rx.subjects import Subject
streams = {
    "/ws/testware/monitor": Subject(),
    "/ws/dbus/system/monitor": Subject(),
}
Exemple #6
0
 def __init__(self):
     self.subject = Subject()
 def emit_event(self, event):
     event_type, data = event
     print("messege recived")
     if event_type not in self.eventSubjects:
         self.eventSubjects[event_type] = Subject()
     self.eventSubjects[event_type].on_next(data)
    def display(self, path: str):
        self.rfd_subject = Subject()
        self.initial_query: Query = None
        self.rfds: list = []

        self.path = path
        self.rfds_path: str = self.path.replace(".csv", "-RFDs.json")
        self.csv_parser: CSVParser = CSVParser(path)
        self.data_frame: DataFrame = self.csv_parser.data_frame
        self.header = self.csv_parser.header
        self.separator = self.csv_parser.delimiter
        self.columns_count = self.csv_parser.columns_count
        self.rows_count = self.csv_parser.rows_count

        self.container_vertical_layout = QVBoxLayout()
        container_group_box = QGroupBox()
        container_group_box.setLayout(self.container_vertical_layout)
        self.setWidget(container_group_box)
        self.setWidgetResizable(True)

        for i in reversed(range(self.container_vertical_layout.count())):
            self.container_vertical_layout.itemAt(i).widget().deleteLater()

        self.rfds_tree_wrapper = QGroupBox()
        self.rfds_tree_wrapper.setMinimumHeight(200)
        self.rfds_tree_wrapper_layout = QVBoxLayout(self.rfds_tree_wrapper)

        buttons_group_box = QGroupBox()
        buttons_horizontal_layout = QHBoxLayout()
        buttons_horizontal_layout.setAlignment(Qt.AlignLeft)
        buttons_horizontal_layout.setAlignment(Qt.AlignTop)
        buttons_group_box.setLayout(buttons_horizontal_layout)

        self.container_vertical_layout.addWidget(buttons_group_box)

        discover_rfds_button = QPushButton("Discover RFDs")
        width = discover_rfds_button.fontMetrics().boundingRect(discover_rfds_button.text()).width() + 20
        discover_rfds_button.setMaximumWidth(width)
        discover_rfds_button.clicked.connect(lambda: self.discover_rfds())

        load_rfds_button = QPushButton("Load RFDs")
        width = load_rfds_button.fontMetrics().boundingRect(load_rfds_button.text()).width() + 20
        load_rfds_button.setMaximumWidth(width)
        load_rfds_button.clicked.connect(lambda: self.load_rfds())

        store_rfds_button = QPushButton("Store RFDs")
        width = store_rfds_button.fontMetrics().boundingRect(load_rfds_button.text()).width() + 20
        store_rfds_button.setMaximumWidth(width)
        store_rfds_button.clicked.connect(lambda: self.store_rfds())

        self.filters: dict = {RFDsTab.LHS: QCheckBox("LHS"), RFDsTab.RHS: QCheckBox("RHS")}
        lhs_filter_check_box: QCheckBox = self.filters[RFDsTab.LHS]
        lhs_filter_check_box.stateChanged.connect(lambda: self.__show_rfds(self.__filter_rfds()))
        lhs_filter_check_box.setToolTip("Show RFDs with at least ONE attribute of the query in the LHS")
        lhs_filter_check_box.setStyleSheet(RFDsTab.TOOLTIP_STYLE)

        rhs_filter_check_box: QCheckBox = self.filters[RFDsTab.RHS]
        rhs_filter_check_box.stateChanged.connect(lambda: self.__show_rfds(self.__filter_rfds()))
        rhs_filter_check_box.setToolTip("Show RFDs with NO attribute of the query in the RHS")
        rhs_filter_check_box.setStyleSheet(RFDsTab.TOOLTIP_STYLE)

        buttons_horizontal_layout.addWidget(discover_rfds_button)
        buttons_horizontal_layout.addWidget(load_rfds_button)
        buttons_horizontal_layout.addWidget(store_rfds_button)
        buttons_horizontal_layout.addWidget(lhs_filter_check_box)
        buttons_horizontal_layout.addWidget(rhs_filter_check_box)
        buttons_horizontal_layout.setAlignment(Qt.AlignLeft)
 def __init__(self, host='localhost', port='8888'):
     self._url = 'ws://{}:{}/exchange'.format(host, port)
     self.conn = None
     self.opened = Subject()
     self.messages = Subject()
Exemple #10
0
 def action1(scheduler, state=None):
     s[0] = Subject()
Exemple #11
0
        def subscribe(observer, scheduler_=None):
            _scheduler = scheduler or scheduler_ or timeout_scheduler

            n = [0]
            s = [None]
            timer_d = SerialDisposable()
            window_id = [0]
            group_disposable = CompositeDisposable(timer_d)
            ref_count_disposable = RefCountDisposable(group_disposable)

            def create_timer(_id):
                m = SingleAssignmentDisposable()
                timer_d.disposable = m

                def action(scheduler, state):
                    if _id != window_id[0]:
                        return

                    n[0] = 0
                    window_id[0] += 1
                    new_id = window_id[0]
                    s[0].on_completed()
                    s[0] = Subject()
                    observer.on_next(add_ref(s[0], ref_count_disposable))
                    create_timer(new_id)

                m.disposable = _scheduler.schedule_relative(timespan, action)

            s[0] = Subject()
            observer.on_next(add_ref(s[0], ref_count_disposable))
            create_timer(0)

            def on_next(x):
                new_window = False
                new_id = 0

                s[0].on_next(x)
                n[0] += 1
                if n[0] == count:
                    new_window = True
                    n[0] = 0
                    window_id[0] += 1
                    new_id = window_id[0]
                    s[0].on_completed()
                    s[0] = Subject()
                    observer.on_next(add_ref(s[0], ref_count_disposable))

                if new_window:
                    create_timer(new_id)

            def on_error(e):
                s[0].on_error(e)
                observer.on_error(e)

            def on_completed():
                s[0].on_completed()
                observer.on_completed()

            group_disposable.add(
                source.subscribe_(on_next, on_error, on_completed, scheduler_))
            return ref_count_disposable
Exemple #12
0
 def __init__(self):
     self.entities = []
     self.entities_subject = Subject()
Exemple #13
0
        def subscribe(observer, scheduler_=None):
            _scheduler = scheduler or scheduler_ or timeout_scheduler

            timer_d = SerialDisposable()
            next_shift = [timeshift]
            next_span = [timespan]
            total_time = [timedelta(0)]
            q = []

            group_disposable = CompositeDisposable(timer_d)
            ref_count_disposable = RefCountDisposable(group_disposable)

            def create_timer():
                m = SingleAssignmentDisposable()
                timer_d.disposable = m
                is_span = False
                is_shift = False

                if next_span[0] == next_shift[0]:
                    is_span = True
                    is_shift = True
                elif next_span[0] < next_shift[0]:
                    is_span = True
                else:
                    is_shift = True

                new_total_time = next_span[0] if is_span else next_shift[0]

                ts = new_total_time - total_time[0]
                total_time[0] = new_total_time
                if is_span:
                    next_span[0] += timeshift

                if is_shift:
                    next_shift[0] += timeshift

                def action(scheduler, state=None):
                    s = None

                    if is_shift:
                        s = Subject()
                        q.append(s)
                        observer.on_next(add_ref(s, ref_count_disposable))

                    if is_span:
                        s = q.pop(0)
                        s.on_completed()

                    create_timer()

                m.disposable = _scheduler.schedule_relative(ts, action)

            q.append(Subject())
            observer.on_next(add_ref(q[0], ref_count_disposable))
            create_timer()

            def on_next(x):
                for s in q:
                    s.on_next(x)

            def on_error(e):
                for s in q:
                    s.on_error(e)

                observer.on_error(e)

            def on_completed():
                for s in q:
                    s.on_completed()

                observer.on_completed()

            group_disposable.add(
                source.subscribe_(on_next, on_error, on_completed, scheduler_))
            return ref_count_disposable
Exemple #14
0
from rx import Observable, Observer
from rx.subjects import Subject


class PrintObserver(Observer):
    def on_next(self, value):
        print("Value :", value)

    def on_error(self, error):
        print("Error :", error)

    def on_completed(self):
        print("Completed")


subject = Subject()
subject.subscribe(PrintObserver())
for i in range(10):
    subject.on_next(i)
subject.on_completed()
    def provide_vista_detallada_subject(cls):

        if cls.vista_detallada_subject is None:
            cls.vista_detallada_subject = Subject()

        return cls.vista_detallada_subject
from rx import Observable
from rx.subjects import Subject

numbers = Subject()
sampler = Subject()
numbers.sample(sampler=sampler).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")
)

numbers.on_next(1)
numbers.on_next(2)
sampler.on_next(True)
numbers.on_next(3)
numbers.on_next(4)
numbers.on_next(5)
sampler.on_next(True)
    def provide_pantalla_espera_exportar_subject(cls):

        if cls.pantalla_espera_exportar_subject is None:
            cls.pantalla_espera_exportar_subject = Subject()

        return cls.pantalla_espera_exportar_subject
Exemple #18
0
from rx import Observable
from rx.subjects import Subject
import time

numbers = Subject()

numbers.timestamp().subscribe(
    on_next=lambda i: print("on_next {}: {}".format(i.value, i.timestamp)),
    on_error=lambda e: print("on_error: {}".format(e)),
    on_completed=lambda: print("on_completed"))

numbers.on_next(1)
time.sleep(0.1)
numbers.on_next(2)
time.sleep(0.1)
numbers.on_next(3)
time.sleep(0.1)
numbers.on_next(4)
 def __init__(self, ws):
     self.ws = ws
     self.websocketEvents = Subject()
     self.eventSubjects = {}
Exemple #20
0
 def provide_speed_profile_changed_subject(
         self) -> SpeedProfileChangedSubject:
     return Subject()
 def get_subject(self, event_type):
     if event_type not in self.eventSubjects:
         self.eventSubjects[event_type] = Subject()
     return self.eventSubjects[event_type]
Exemple #22
0
 def provide_speed_step_changed_subject(self) -> SpeedStepChangedSubject:
     return Subject()
    def test_connectable_observable_multiple_non_overlapped_connections(self):
        scheduler = TestScheduler()

        xs = scheduler.create_hot_observable(
            on_next(210, 1),
            on_next(220, 2),
            on_next(230, 3),
            on_next(240, 4),
            on_next(250, 5),
            on_next(260, 6),
            on_next(270, 7),
            on_next(280, 8),
            on_next(290, 9),
            on_completed(300)
        )

        subject = Subject()

        conn = xs.pipe(ops.multicast(subject))

        c1 = [None]

        def action10(scheduler, state):
            c1[0] = conn.connect(scheduler)
        scheduler.schedule_absolute(225, action10)

        def action11(scheduler, state):
            c1[0].dispose()
        scheduler.schedule_absolute(241, action11)

        def action12(scheduler, state):
            c1[0].dispose()  # idempotency test
        scheduler.schedule_absolute(245, action12)

        def action13(scheduler, state):
            c1[0].dispose()  # idempotency test
        scheduler.schedule_absolute(251, action13)

        def action14(scheduler, state):
            c1[0].dispose()  # idempotency test
        scheduler.schedule_absolute(260, action14)

        c2 = [None]

        def action20(scheduler, state):
            c2[0] = conn.connect(scheduler)
        scheduler.schedule_absolute(249, action20)

        def action21(scheduler, state):
            c2[0].dispose()
        scheduler.schedule_absolute(255, action21)

        def action22(scheduler, state):
            c2[0].dispose()  # idempotency test
        scheduler.schedule_absolute(265, action22)

        def action23(scheduler, state):
            c2[0].dispose()  # idempotency test
        scheduler.schedule_absolute(280, action23)

        c3 = [None]

        def action30(scheduler, state):
            c3[0] = conn.connect(scheduler)
        scheduler.schedule_absolute(275, action30)

        def action31(scheduler, state):
            c3[0].dispose()
        scheduler.schedule_absolute(295, action31)

        res = scheduler.start(lambda: conn)

        assert res.messages == [
            on_next(230, 3),
            on_next(240, 4),
            on_next(250, 5),
            on_next(280, 8),
            on_next(290, 9)]

        assert xs.subscriptions == [
            subscribe(225, 241),
            subscribe(249, 255),
            subscribe(275, 295)]
Exemple #24
0
 def __init__(self):
     self._error_stream = Subject()
     self._price_stream = Subject()
     self._symbol_stream = Subject()
     self.latest_valid_order = None
Exemple #25
0
from rx import Observable
from rx.subjects import Subject

logging.config.fileConfig("logging.conf")


def printMessage(prefix):
    def handler(x):
        ws, path, msg = [x.get(key) for key in ['ws', 'path', 'msg']]
        print(prefix, msg)

    return handler


entitlementStatusStream = Subject()
subscriptionManagerStream = Subject()

entitlementStatusStream.subscribe(
    printMessage('entitlement status arrived \t'), lambda err: print(err),
    lambda: print('end of the show'))
subscriptionManagerStream.subscribe(
    printMessage('subscription manager message arrived\t'),
    lambda err: print(err), lambda: print('end of the show'))

entitlementUnknownStatusStream = entitlementStatusStream\
    .distinct_until_changed(lambda x: x['msg']['overallStatus'])\
    .filter(lambda x: x['msg']['overallStatus'] == 'Unknown')

entitlementUnknownStatusStream\
    .subscribe(printMessage('entitlement status is unknown\t'))
from PyQt5.QtWidgets import QApplication
from tornado.ioloop import IOLoop

from rx import Observable
from rx.subjects import Subject
from rx.concurrency import QtScheduler, AsyncIOScheduler

from client.client import Client
from client.client_window import ClientWindow

import utils

if __name__ == '__main__':
    app = QApplication(sys.argv)
    scheduler = QtScheduler(QtCore)
    stock_prices = Subject()
    client = Client(port='9999')

    loop = asyncio.new_event_loop()
    asyncio_scheduler = AsyncIOScheduler(loop)

    def run_client():
        asyncio.set_event_loop(loop)
        asyncio.get_event_loop().call_soon(utils.run_client_websocket, client,
                                           stock_prices)
        asyncio.get_event_loop().run_forever()

    thread = Thread(target=run_client, daemon=True)
    thread.start()

    client_window = ClientWindow(stock_prices_stream=stock_prices)
Exemple #27
0
        def on_next(x):
            writer = None
            key = None

            try:
                key = key_mapper(x)
            except Exception as e:
                for wrt in writers.values():
                    wrt.on_error(e)

                observer.on_error(e)
                return

            fire_new_map_entry = False
            writer = writers.get(key)
            if not writer:
                writer = Subject()
                writers[key] = writer
                fire_new_map_entry = True

            if fire_new_map_entry:
                group = GroupedObservable(key, writer, ref_count_disposable)
                duration_group = GroupedObservable(key, writer)
                try:
                    duration = duration_mapper(duration_group)
                except Exception as e:
                    for wrt in writers.values():
                        wrt.on_error(e)

                    observer.on_error(e)
                    return

                observer.on_next(group)
                sad = SingleAssignmentDisposable()
                group_disposable.add(sad)

                def expire():
                    if writers[key]:
                        del writers[key]
                        writer.on_completed()

                    group_disposable.remove(sad)

                def on_next(value):
                    pass

                def on_error(exn):
                    for wrt in writers.values():
                        wrt.on_error(exn)
                    observer.on_error(exn)

                def on_completed():
                    expire()

                sad.disposable = duration.take(1).subscribe_(
                    on_next, on_error, on_completed, scheduler)

            try:
                element = element_mapper(x)
            except Exception as error:
                for wrt in writers.values():
                    wrt.on_error(error)

                observer.on_error(error)
                return

            writer.on_next(element)
    def provide_pantalla_principal_subject(cls):

        if cls.pantalla_principal_subject is None:
            cls.pantalla_principal_subject = Subject()

        return cls.pantalla_principal_subject
Exemple #29
0
from rx import Observable, Observer
from rx.subjects import Subject

AA = Subject()

aa = AA.filter(lambda s: s == 'A') \
    .map(lambda s: s.lower()).publish()

aa.subscribe(lambda a: print(a))
AA.subscribe(lambda a: print("{}".format(2)))

aa.connect()
Observable.from_("A,B,C,D,D,E,F,G,H".split(','))\
    .subscribe(AA.on_next)

for s in "A,B,C,D,D,E,F,G,H":
    AA.on_next(s)
Exemple #30
0
from rx import Observable
from rx.subjects import Subject


def component_a(input):
    return input.map(lambda i: i * 2)


def component_b(input):
    input.subscribe(on_next=lambda i: print("item: {}".format(i)),
                    on_error=lambda e: print("error: {}".format(e)),
                    on_completed=lambda: print("completed"))
    return Observable.from_([1, 2, 3])


b_in_proxy = Subject()
b_out = component_b(b_in_proxy)
a_out = component_a(b_out)
a_out.subscribe(b_in_proxy)