示例#1
0
文件: demo.py 项目: Konubinix/flexx
def demo(ctx):
    """show a quick Flexx demo
    """
    from flexx.ui.examples.demo import Demo
    from flexx import app
    app.launch(Demo)
    app.run()
示例#2
0
def demo(ctx):
    """show a quick Flexx demo
    """
    from flexx.ui.examples.demo import Demo
    from flexx import app
    app.launch(Demo)
    app.run()
示例#3
0
 def inner(simulation):
     database = dataset.connect('sqlite:///parameter.db')
     abcEconomics.parameter_database = database['parameter']
     Form = form(parameter_mask, names)  # pylint: disable=C0103
     if serve:
         flexx.config.hostname = hostname
         flexx.config.port = port
         app.serve(
             basiclayout(Form,
                         simulation,
                         title,
                         header,
                         truncate_rounds,
                         texts=texts,
                         pages=pages,
                         histograms=histograms))
         app.start()
     else:
         app.launch(basiclayout(Form,
                                simulation,
                                title,
                                header,
                                truncate_rounds,
                                texts=texts,
                                pages=pages,
                                histograms=histograms),
                    windowmode='maximized',
                    runtime=runtime)
         app.run()
     return lambda _: None
示例#4
0
def graphs(parameter_mask=None, names=None):
    """ After the simulation simulation.graphs displays all logged data,
    this can not be use in conjuncture with @gui.

    Args:

        parameter_mask (optional):
            simulation parameters to display
        names (optional):
            a dictionary with the parameter name as key and an alternative
            text to be displayed instead.
    """
    names = ({} if names is None else names)

    if platform.python_implementation() == 'PyPy':
        try:
            call(['python3', '-mabce.show'])
        except Exception:
            call(['python', '-mabce.show'])
    else:

        database = dataset.connect('sqlite:///parameter.db')
        abce.parameter_database = database['parameter']
        parameter_mask = ({} if parameter_mask is None else parameter_mask)

        Form = form(parameter_mask, names)

        app.launch(basiclayout(Form, None, parameter_mask['name'],
                               graphs=True),
                   runtime='browser-X')
        app.run()
示例#5
0
def test_setting_properties():
    class MyPropClass(app.Model):
        @event.prop
        def foo(self, v=1):
            return v

    m = app.launch(MyPropClass)
    assert m.foo == 1
    m.session.close()

    m = app.launch(MyPropClass, None, dict(foo=3))
    assert m.foo == 3
    m.session.close()
示例#6
0
文件: test_live.py 项目: silky/flexx
def runner(cls):

    # Run with a fresh server
    server = app.create_server(port=0, new_loop=True)

    t = app.launch(cls, 'firefox-app')
    t.test_init()
    t.test_set_result()
    # Install failsafe. Use a closure so failsafe wont spoil a future test
    isrunning = True

    def stop():
        if isrunning:
            app.stop()

    app.call_later(TIMEOUT1, stop)
    # Enter main loop until we get out
    t0 = time.time()
    app.start()
    print('ran %f seconds' % (time.time() - t0))
    isrunning = False
    # Check result
    if True:  # not (ON_TRAVIS and ON_PYPY):  # has intermittent fails on pypy3
        t.test_check()
    # Shut down
    t.session.close()
示例#7
0
def runner(cls):
    t = app.launch(cls, 'firefox')
    t.test_init()
    app.call_later(5, app.stop)
    app.run()
    if not (ON_TRAVIS and ON_PYPY):  # has intermittent fails on pypy3
        t.test_check()
示例#8
0
def runner(cls):
    t = app.launch(cls, 'firefox')  # fails somehow with XUL
    t.test_init()
    app.call_later(TIMEOUT1, app.stop)
    app.run()
    if not (ON_TRAVIS and ON_PYPY):  # has intermittent fails on pypy3
        t.test_check()
    t.session.close()
示例#9
0
def test_launching_with_props():

    m = app.launch(MyPropClass1)
    assert m.foo == 1
    m.session.close()

    m = app.App(MyPropClass1, foo=3).launch()
    assert m.foo == 3
    m.session.close()
示例#10
0
文件: test_app.py 项目: silky/flexx
def test_launching_with_init_args():

    m = app.launch(MyPropClass2)
    assert m.foo == 11
    m.session.close()

    m = app.App(MyPropClass2, 13).launch()
    assert m.foo == 13
    m.session.close()
示例#11
0
    def inner(simulation):
        if not IMPORTERROR:
            if pypy is not None:

                def simulation(parameters):
                    print("CALLING PYPY")
                    call([
                        pypy, sys.argv[0],
                        json.dumps(parameters), abce.simulation_name
                    ])

            database = dataset.connect('sqlite:///parameter.db')
            abce.parameter_database = database['parameter']
            Form = form(parameter_mask, names)  # pylint: disable=C0103
            if serve:
                flexx.config.hostname = hostname
                flexx.config.port = port
                app.serve(
                    basiclayout(Form,
                                simulation,
                                title,
                                header,
                                truncate_rounds,
                                texts=texts,
                                pages=pages,
                                histograms=histograms))
                app.start()
            else:
                app.launch(basiclayout(Form,
                                       simulation,
                                       title,
                                       header,
                                       truncate_rounds,
                                       texts=texts,
                                       pages=pages,
                                       histograms=histograms),
                           windowmode='maximized',
                           runtime=runtime)
                app.run()
        else:
            print("RUN PYPY")
            abce.simulation_name = sys.argv[2]
            simulation(json.loads(sys.argv[1]))
        return lambda _: None
示例#12
0
def graph(parameter_mask=None, names=None):
    """ After the simulation simulation.graphs displays all logged data,
    this can not be use in conjuncture with @gui.

    Args:

        parameter_mask (optional):
            simulation parameters to display
        names (optional):
            a dictionary with the parameter name as key and an alternative
            text to be displayed instead.
    """
    names = ({} if names is None else names)

    database = dataset.connect('sqlite:///parameter.db')
    abcEconomics.parameter_database = database['parameter']
    parameter_mask = ({} if parameter_mask is None else parameter_mask)

    Form = form(parameter_mask, names)

    app.launch(basiclayout(Form, None, parameter_mask['name'], graphs=True),
               runtime='browser-X')
    app.run()
示例#13
0
# doc-export: Split
"""
Splitter widgets are cool!
"""

from flexx import app, ui


class Split(ui.Widget):
    def init(self):

        with ui.HSplit():
            ui.Widget(style='background:#f00')
            with ui.VSplit():
                ui.Widget(style='background:#0f0')
                with ui.HSplit():
                    ui.Widget(style='background:#ff0')
                    with ui.VSplit():
                        ui.Widget(style='background:#f0f')
                        with ui.HSplit():
                            ui.Widget(style='background:#0ff')
                            ui.Widget(style='background:#00f')


if __name__ == '__main__':
    m = app.launch(Split)
    app.run()
示例#14
0
"""
Hello world that creats an app from a custom Widget.
"""


from flexx import app, ui

class MyApp(ui.Widget):
    def init(self):
        self.b = ui.Button(text='Hello world!')

main = app.launch(MyApp)
app.run()
示例#15
0
文件: find_prime.py 项目: silky/flexx
        i += 1
        if isprime(i):
            primes.append(i)
    t1 = perf_counter()
    print(i, 'found in ', t1-t0, 'seconds')


class PrimeFinder(app.Model):
    
    def find_prime_py(self, n):
        find_prime(n)
    
    def find_prime_js(self, n):
        self.call_js('_find_prime(%i)' % n)
    
    class JS:
        
        def _find_prime(self, n):
            find_prime(n)


if __name__ == '__main__':
    
    # Create app instance
    finder = app.launch(PrimeFinder, 'app or chrome-app')
    
    finder.find_prime_py(2000)  # 0.7 s
    finder.find_prime_js(2000)  # 0.2 s
    
    app.run()
示例#16
0
# doc-export: Form
"""
Simple example that shows two forms, one which is stretched, and one
in which we use a dummy Widget to fill up space so that the form is
more compact.
"""

from flexx import app, ui


class Form(ui.Widget):
    def init(self):

        with ui.BoxPanel():
            with ui.FormLayout() as self.form:
                self.b1 = ui.Button(title='Name:', text='Hola')
                self.b2 = ui.Button(title='Age:', text='Hello world')
                self.b3 = ui.Button(title='Favorite color:', text='Foo bar')
            with ui.FormLayout() as self.form:
                self.b4 = ui.Button(title='Name:', text='Hola')
                self.b5 = ui.Button(title='Age:', text='Hello world')
                self.b6 = ui.Button(title='Favorite color:', text='Foo bar')
                ui.Widget(flex=1)  # Add a flexer


if __name__ == '__main__':
    m = app.launch(Form, 'firefox')
    app.run()
示例#17
0
    def init(self):
        with MyHBox():

            with MyVBox(flex=2):

                with MyVBox(flex=4, spacing=30):
                    ui.Widget(flex=1, css_class='white')
                    ui.Widget(flex=1, css_class='white')

                with MyVBox(flex=2, css_class='blue'):
                    ui.Widget(flex=1, css_class='edge')
                    ui.Widget(flex=1, css_class='edge')

            with MyVBox(flex=6):

                with MyVBox(flex=4, spacing=30, css_class='red'):
                    ui.Widget(flex=1, css_class='edge')
                    ui.Widget(flex=1, css_class='edge')

                with MyHBox(flex=2):
                    ui.Widget(flex=6, css_class='white')

                    with MyVBox(flex=1):
                        ui.Widget(flex=1, css_class='white')
                        ui.Widget(flex=1, css_class='yellow')


if __name__ == '__main__':
    app.launch(Mondriaan, 'firefox')
    app.run()
示例#18
0
    def init(self):

        with MyLayout('v') as self.s:
            self.w1 = MyWidget(text=text)

            with MyLayout('h') as self.s:
                self.w2 = MyWidget(text='hello world!')
                with MyLayout('v'):
                    self.w3 = MyWidget(text='hi')
                    self.w4 = MyWidget(text='hello world! ' * 4)
                with MyLayout('v'):
                    self.w5 = MyWidget(text='min-size: 50',
                                       style='min-width:50px; min-height:50px')
                    self.w6 = MyWidget(
                        text='min-size: 100',
                        style='min-width:100px; min-height:100px')
                    self.w7 = MyWidget(
                        text='min-size: 150',
                        style='min-width:150px; min-height:150px')

            with ui.Widget(flex=1):
                with MyLayout('h'):
                    self.w8 = MyWidget()
                    self.w9 = MyWidget(style='min-width:250px;')
                    self.w8 = MyWidget()


if __name__ == '__main__':
    m = app.launch(TestApp)
    app.run()
示例#19
0
# Associate assets needed by this app.
app.assets.associate_asset(__name__, "http://code.jquery.com/jquery-1.10.2.js")
app.assets.associate_asset(__name__,
                           "http://code.jquery.com/ui/1.11.4/jquery-ui.js")
app.assets.associate_asset(
    __name__,
    "http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css")


class DatePicker(ui.Widget):
    class JS:
        def _init_phosphor_and_node(self):
            self.phosphor = self._create_phosphor_widget('input')
            self.node = self.phosphor.node

            RawJS('$')(self.node).datepicker()


class Example(ui.Widget):
    def init(self):

        with ui.FormLayout():
            self.start = DatePicker(title='Start date')
            self.end = DatePicker(title='End date')
            ui.Widget(flex=1)


if __name__ == '__main__':
    m = app.launch(Example, 'browser')
    app.run()
示例#20
0
"""
Simple example that shows two forms, one which is stretched, and one
in which we use a dummy Widget to fill up space so that the form is
more compact.
"""

from __future__ import print_function, absolute_import, with_statement, unicode_literals, division

from flexx import app, ui


class Form(ui.Widget):
    
    def init(self):
        
        with ui.BoxPanel():
            with ui.FormLayout() as self.form:
                self.b1 = ui.Button(title='Name:', text='Hola')
                self.b2 = ui.Button(title='Age:', text='Hello world')
                self.b3 = ui.Button(title='Favorite color:', text='Foo bar')
            with ui.FormLayout() as self.form:
                self.b4 = ui.Button(title='Name:', text='Hola')
                self.b5 = ui.Button(title='Age:', text='Hello world')
                self.b6 = ui.Button(title='Favorite color:', text='Foo bar')
                ui.Widget(flex=1)  # Add a flexer


if __name__ == '__main__':
    m = app.launch(Form)
    app.run()
示例#21
0
        self.call_js('_benchmark()')

    def benchmark(self):
        print('\n==== Python %s %s =====\n' %
              (platform.python_implementation(), platform.python_version()))
        pystone.main()
        convolve()
        bench_str()

        # Trigger benchmark in JS
        self.run_js_benchmark()

    class JS:

        BACKEND = BACKEND
        convolve = convolve
        bench_str = bench_str

        def _benchmark(self):
            print()
            print('==== PyScript on %s =====' % self.BACKEND)
            print()
            pystone.main()
            self.convolve()
            self.bench_str()


b = app.launch(Benchmarker, BACKEND)
b.benchmark()
app.run()
示例#22
0
"""
Example demonstrating how signals in Py can connect to signals in JS.
"""

from flexx import react
from flexx import app


class Clock(app.Pair):
    @react.connect('time')
    def show_time(t):
        print(t)

    class JS:
        def _init(this):
            that = this

            def _set_time():
                that.time._set(time.perf_counter()
                               )  # perf_counter() is a PyScript feature

            setInterval(_set_time, 200)

        @react.source
        def time(t):
            return float(t)


clock = app.launch(Clock, 'nodejs')
app.run()
示例#23
0
        if True:
            # The client will load these assets from the URL's. Good for web apps.
            self.session.use_remote_asset(
                "http://code.jquery.com/jquery-1.10.2.js")
            self.session.use_remote_asset(
                "http://code.jquery.com/ui/1.11.4/jquery-ui.js")
            self.session.use_remote_asset(
                "http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"
            )
        else:
            # Flexx will download the assets and serve them to the client. Good for desktop/exported apps.
            self.session.add_global_asset(
                "jquery.js", "http://code.jquery.com/jquery-1.10.2.js")
            self.session.add_global_asset(
                "jquery-ui.js",
                "http://code.jquery.com/ui/1.11.4/jquery-ui.js")
            self.session.add_global_asset(
                "jquery-ui.css",
                "http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"
            )

        with ui.FormLayout():
            self.start = DatePicker(title='Start date')
            self.end = DatePicker(title='End date')
            ui.Widget(flex=1)


if __name__ == '__main__':
    app.launch(Example)
    app.run()
示例#24
0
        width: 10px;
        height: 10px;
    }
    """

class App(ui.Widget):
    def init(self):
        self._circles = []
        
        with ui.PinboardLayout():
            for i in range(32):
                x = math.sin(i*0.2)*0.3 + 0.5
                y = math.cos(i*0.2)*0.3 + 0.5
                w = Circle(pos=(x,y))
                self._circles.append(w)
        
        self.tick()
        # todo: animate in JS!
    
    def tick(self):
        t = time.time()
        for i, circle in enumerate(self._circles):
            x = math.sin(i*0.2 + t)*0.3 + 0.5
            y = math.cos(i*0.2 + t)*0.3 + 0.5
            circle.pos((x, y))
        app.call_later(0.03, self.tick)

if __name__ == '__main__':
    m = app.launch(App)
    app.run()
示例#25
0
文件: test.py 项目: rohithpr/flexx
            with ui.HBox():
                with ui.VBox():
                    self.buta = ui.Button(text='red')
                    self.butb = ui.Button(text='green')
                    self.butc = ui.Button(text='blue')
                with ui.StackedPanel(flex=1) as self.stack:
                        self.a = ui.Widget(style='background:#a00;')
                        self.b = ui.Widget(style='background:#0a0;')
                        self.c = ui.Widget(style='background:#00a;')
        #self.win = ui.Window(self, 'A new window!')

    
    class JS:
        
        @react.connect('buta.mouse_down', 'butb.mouse_down', 'butc.mouse_down')
        def _stacked_current(a, b, c):
            if a:
                self.stack.current(self.a)
            if b:
                self.stack.current(self.b)
            if c:
                self.stack.current(self.c)
                

# app.serve(MyApp)
a = app.launch(MyApp, 'firefox')
app.start()
# app.b1.set_text('asdasd')

# MyApp.export('/home/almar/test.html')
示例#26
0
    def init(self):

        self.im = html.Div(text='<img src="https://github.com/fluidicon.png">',
                           css_class='leftimage')
        self.text = html.Div(text=LIPSUM * 10)

        # First list, still a bit the "Flexx way"
        html.h1(text='List 1')
        with html.Ul() as self.thelist:
            html.Li(text='Foo')
            html.Li(text='Bar')
            html.Li(text='Spam')

        # Second list, let's just embed HTML
        html.h1(text='List 2')
        html.Div(text="""<ul>
                            <li>Foo</li>
                            <li>Bar</li>
                            <li>Spam</li>
                        </ul>""")

    class JS:
        @event.connect('text.mouse_down')
        def on_text_clicked(self, *events):
            self.thelist.children[-1].text = window.Date.now()


if __name__ == '__main__':
    m = app.launch(Example, 'xul')
    app.run()
示例#27
0
        @event.connect('btnr.mouse_click')
        def handle_seamap_remove(self, *events):
            self.leaflet.layers = [
                ('http://a.tile.openstreetmap.org/', 'OpenStreetMap'),
            ]

        @event.connect('cbs.checked', 'cbl.checked')
        def handle_checkboxes(self, *events):
            self.leaflet.show_scale = self.cbs.checked
            self.leaflet.show_layers = self.cbl.checked

        @event.connect('leaflet.mouse_event')
        def handle_leaflet_mouse(self, *events):
            ev = events[-1]
            latlng = tuple(ev['latlng'])
            flexx.ui.Label(text='%.5f, %.5f' % tuple(latlng), parent=self.list)

        class JS:
            @event.connect('leaflet.mouse_event')
            def handle_leaflet_mouse(self, *events):
                ev = events[-1]
                latlng = tuple(ev['latlng'])
                if ev['event'] == 'click':
                    m = L.marker(ev['latlng'])
                    m.bindTooltip('%f, %f' % (latlng[0], latlng[1]))
                    m.addTo(self.leaflet.map)

    app.launch(MapWidget, 'xul')
    app.run()
示例#28
0
        self.slider2.set_value(value)


## Main


class Tricky(ui.Widget):
    """ A collection of tricky cases.
    """
    def init(self):
        with ui.VBox():

            self.reset = ui.Button(text='Reset event system')
            with ui.HFix(flex=1):
                SyncedSlidersWrong(flex=1)
                SyncedSlidersRight(flex=1)

            ui.Widget(flex=1)  # spacer

    @event.reaction('reset.mouse_click')
    def _reset(self):
        # You probably don't want to ever do this in a normal app.
        # Do via a timeout because reactions get handled by the event system,
        # so the reset will not work correctly.
        global window
        window.setTimeout(event.loop.reset, 0)


m = app.launch(Tricky, 'app')
app.run()
示例#29
0
            
            def isprime(x):
                if x <= 1:
                    return False
                elif x == 2:
                    return True
                for i in range(2, x//2+1):
                    if x % i == 0:
                        return False
                return True
            
            import time  # import here, so PyScript picks is up
            t0 = time.perf_counter()
            i = 0
            while len(primes) < n:
                i += 1
                if isprime(i):
                    primes.append(i)
            t1 = time.perf_counter()
            print(i, 'found in ', t1-t0, 'seconds')

if __name__ == '__main__':
    
    # Create app instance
    finder = app.launch(PrimeFinder, 'nodejs')  # can also use Firefox or Chrome
    
    finder.find_prime_py(2000)  # 0.7 s
    finder.find_prime_js(2000)  # 0.2 s
    
    app.run()
示例#30
0
文件: errors.py 项目: silky/flexx
        def raise_error(self):
            raise RuntimeError('Deliberate error')

    class JS:
        @event.prop
        def bar(self, v):
            self.raise_error()

        # Handlers for four buttons

        @event.connect('b1.mouse_click')
        def error_in_JS_prop(self, *events):
            self.bar = 2

        @event.connect('b2.mouse_click')
        def error_in_JS_handler(self, *events):
            self.raise_error()

        @event.connect('b3.mouse_click')
        def error_in_Py_prop(self, *events):
            self.foo = 0

    @event.connect('b4.mouse_click')
    def error_in_Py_handler(self, *events):
        self.raise_error()


if __name__ == '__main__':
    m = app.launch(Errors, 'browser')
    app.run()
示例#31
0
    def init(self):
        with ui.VBox():
            
            with ui.HBox():
                self.first_edit = ui.LineEdit(placeholder_text='first name',
                                              text='Jane')
                self.last_edit = ui.LineEdit(placeholder_text='last name',
                                             text='Doe')
                ui.Widget(flex=1)  # spacer
                
            with ui.HBox():
                ui.Label(text=lambda: self.root.first_name,
                         style='border:1px solid red')
                ui.Label(text=lambda: self.root.last_name,
                         style='border:1px solid red')
                ui.Widget(flex=1)  # spacer
            
            MyPersonLabel(style='border:1px solid blue')
            
            ui.Widget(flex=1)  # spacer
    
    @event.reaction
    def _update_name(self):
        self.root.set_first_name(self.first_edit.text)
        self.root.set_last_name(self.last_edit.text)


if __name__ == '__main__':
    m = app.launch(MyApp)
    app.run()