Beispiel #1
0
from flexx import flx


class Avocado(flx.Widget):
    def init(self):
        with flx.HBox():
            flx.Button(text='hello', flex=1)
            flx.Button(text='world', flex=2)


app = flx.App(Avocado)
app.launch('app')  # to run as a desktop app
# app.launch('browser')  # to open in the browser
flx.run()  # mainloop will exit when the app is closed
Beispiel #2
0
class Icons1(flx.Widget):
    def init(self):
        flx.Button(text='Not much to see here ...')


class Icons2(flx.Widget):
    def init(self):
        self.set_title('Icon demo')
        self.set_icon(black_png)
        flx.Button(text='Not much to see here ...')


if __name__ == '__main__':

    # Select application icon. Can be a url, a relative url to a shared asset,
    # a base64 encoded image, or a local filename. Note that the local filename
    # works for setting the aplication icon in a desktop-like app, but not for
    # a web app. File types can be ico or png.

    # << Uncomment any of the lines below >>

    # icon = None  # use default
    # icon = 'https://assets-cdn.github.com/favicon.ico'
    # icon = flx.assets.add_shared_data('ico.icon', open(fname, 'rb').read())
    icon = black_png
    # icon = fname

    m = flx.App(Icons1, title='Icon demo', icon=icon).launch('app')
    flx.start()
from flexx import flx


class Example(flx.Widget):
    def init(self):
        self.set_title("A simple GUI")
        with flx.VBox():
            flx.Label(text="This is our first GUI!")
            flx.Button(text='Greet')
            flx.Button(text='Close')


app = flx.App(Example)
app.launch('app')  # to run as a desktop app
#app.launch('browser')  # to open in the browser
flx.run()  # mainloop will exit when the app is closed
Beispiel #4
0
        self.name.set_text(media['name'])
        self.type.set_selected_index(types.index(media['type']))
        self.media.set_text(media['media'])
        #self.name.set_disabled(not editable)
        #self.media.set_disabled(not editable)
        # self.type.set_editable(editable)

    @flx.reaction('browse.pointer_click')
    def on_browse(self, *events):
        input = window.document.createElement('input')
        input.type = 'file'
        input.multiple = 'multiple'

        def on_select_file(e):
            for i in range(e.target.files.length):
                if e.target.files[i]['type'].includes('image'):
                    pass
                main.upload_file(url + '/media/' + e.target.files[i].name, e.target.files[i])
            window.alert('Uploaded file' + ('s' if e.target.files.length > 1 else ''))
            # update media after 1 second
            main.update_media_list()
            self.media.set_options(medias)
        input.onchange = on_select_file
        input.click()


if __name__ == '__main__':
    a = flx.App(Root, title='Display interface')
    m = a.launch()
    flx.run()
                                           xlabel='year',
                                           ylabel=u'temperature (°C)')
            flx.Widget(flex=1)

    @flx.reaction
    def _update_plot(self):
        smoothing = self.smoothing.value
        yy1 = data[self.month.selected_index]
        yy2 = []

        sm2 = int(smoothing / 2)
        for i in range(len(yy1)):
            val = 0
            n = 0
            for j in range(max(0, i - sm2), min(len(yy1), i + sm2 + 1)):
                val += yy1[j]
                n += 1
            if n == 0:
                yy2.append(yy1[i])
            else:
                yy2.append(val / n)

        self.plot.set_data(self.plot.xdata, yy2)


if __name__ == '__main__':
    a = flx.App(Twente,
                title='Temperature 1951 - 2014',
                style='background:#eaeaea;')
    m = a.launch('app', size=(900, 400))
    flx.run()
Beispiel #6
0
# doc-export: Demo
"""
A demo with few lines of code with some fancy widgets, which works
as an exported app, so it can be embedded e.g. on the main page.
"""

from flexx import flx
from flexxamples.demos.splines import Splines
from flexxamples.demos.twente import Twente
from flexxamples.demos.drawing import Drawing

class Demo(flx.Widget):

    def init(self):
        with flx.TabLayout():
            Splines(title='Spline demo')
            Twente(title='Temperature vis')
            Drawing(title='Drawing app')
            flx.YoutubeWidget(title='Video')


if __name__ == '__main__':
    a = flx.App(Demo, title='Flexx demo')
    m = a.launch()
    flx.run()
Beispiel #7
0
        def init(self):
            super().init()
            with self:
                with flx.VBox():
                    self.echart = (EchartWidget(
                        echart_id="any_unique_id",
                        echart_options=self.option1,
                    ), )
                    with flx.HBox():
                        self.btn_change_chart = flx.Button(
                            text="Change Chart1")
                    with flx.HBox():
                        self.echart2 = (EchartWidget(
                            echart_id="any_unique_id_2",
                            echart_div_style="width: 400px;height:400px;",
                            echart_options=self.option2,
                        ), )
                        self.echart3 = (EchartWidget(
                            echart_id="any_unique_id_3",
                            echart_div_style="width: 400px;height:400px;",
                            echart_options=self.option3,
                        ), )
            # to dynamic change
            self.tick()

    app = flx.App(MyApp)
    # export to static SPA JS with a fiew files
    # app.export('c:/xampp/htdocs/demo/myapp/index.html')
    app.launch("chrome-app")
    flx.run()
Beispiel #8
0
    def prompt(self, message, validator=None, **kwargs):
        error = ':)'
        while error:
            ans = self.choice(
                message=message,
                options=[],
                **kwargs,
            )
            error = validator(ans) if ans != None and validator else None
            if error:
                self.print(error)
        return ans

    def wait_interrupt(self):
        self._interrupt.wait()
        self._interrupt.clear()


if __name__ == '__main__':
    _, *args = sys.argv
    app = flx.App(MyGUI_PY)

    title = 'Amigo CPCP'
    icon = 'icon.ico'
    if args and args[0].endswith('browser'):
        app.launch(args[0], title=title, icon=icon)
    else:
        app.launch('app', title=title, icon=icon)
    #app.export('example.html', link=0)
    flx.run()
        for fir in [(fir2_file, "fir2"), (fir1_file, "fir1")]:
            with open(fir[0], "r") as fil:
                filedata = fil.read()
            data = [
                min(2**23 - 1,
                    (max(-2**23, int(float(f.replace("\r", "")) * 2**23))))
                for f in filedata.split("\n") if len(f) > 0
            ]
            mapper.fir_update(data, fir[1])


if __name__ == "__main__":
    import_defaults_active = True
    lock_settings = [("Mixing, Serial Data and Automute Configuration", "*")]
    mappers = [DAC_9038Q2M_Control(0x48), DAC_9038Q2M_Control(0x49)]
    defaults = os.path.join(os.path.dirname(__file__), "configs", "default")

    for m in mappers:
        m.i2c_init()
        if import_defaults_active:
            import_defaults(defaults, m)
        # m.importYaml(
        #     r"C:\Users\webco\Documents\Projects\SABRE_I2C_Controller\configs\device_0x48_config_std.yml"
        # )
        pass
    flx_app = flx.App(ControlApp, mappers, lock_settings)
    # app.launch("app", title="ES9038Control")  # to run as a desktop app
    app.create_server(host="", port=5000, backend="tornado")
    flx_app.launch("browser")  # to open in the browser
    flx.start()  # mainloop will exit when the
Beispiel #10
0
from flexx import flx

app = flx.App(MainComponent)
app.launch('app')  # to run as a desktop app
# app.launch('browser')  # to open in the browser
flx.run()  # mainloop will exit when the app is closed
Beispiel #11
0
    
    CSS = """
    .flx-Circle {
        background: #f00;
        border-radius: 10px;
        width: 10px;
        height: 10px;
    }
    """

class Circles(flx.Widget):
    
    def init(self):
        with flx.PinboardLayout():
            self._circles = [Circle() for i in range(32)]
        self.tick()
    
    def tick(self):
        global Math, window
        t = time()
        for i, circle in enumerate(self._circles):
            x = Math.sin(i*0.2 + t) * 30 + 50
            y = Math.cos(i*0.2 + t) * 30 + 50
            circle.apply_style(dict(left=x + '%', top=y + '%'))
        window.setTimeout(self.tick, 30)


if __name__ == '__main__':
    m = flx.App(Circles).launch('app')
    flx.run()
Beispiel #12
0
    LINEAR_TEXT = LINEAR_TEXT
    BASIS_TEXT = BASIS_TEXT
    CARDINAL_TEXT = CARDINAL_TEXT
    CATMULLROM_TEXT = CATMULLROM_TEXT
    LAGRANGE_TEXT = LAGRANGE_TEXT
    LANCZOS_TEXT = LANCZOS_TEXT

    @flx.reaction('b1.checked', 'b2.checked', 'b3.checked', 'b4.checked',
                  'b5.checked', 'b6.checked')
    def _set_spline_type(self, *events):
        ev = events[-1]
        if not ev.new_value:
            return  # init event
        type = ev.source.text.replace(' ', '')
        self.spline.set_spline_type(type)
        self.explanation.set_text(self[type.upper() + '_TEXT'])

    @flx.reaction
    def __show_hide_tension_slider(self):
        if self.spline.spline_type == 'CARDINAL':
            self.tension.apply_style('visibility: visible')
        else:
            self.tension.apply_style('visibility: hidden')


if __name__ == '__main__':
    a = flx.App(Splines)
    a.launch('firefox-browser')
    flx.run()
Beispiel #13
0
    evo = Evolution(
        problem,
        mutation_param=hyperparameter["MUTATION_PARAM"],
        num_of_generations=hyperparameter["NUM_OF_GENERATIONS"],
        num_of_individuals=hyperparameter["NUM_OF_INDIVIDUALS"],
        num_of_tour_particips=hyperparameter["NUM_OF_TOUR_PARTICIPS"],
        concurrency=hyperparameter["CONCURRENCY"],
        max_proc=hyperparameter["MAX_PROC"])

    # draw the last one with 3d box.
    func = [i.objectives for i in evo.evolve()]

    obj1 = [i[0] for i in func]
    obj2 = [i[1] for i in func]
    obj3 = [i[2] for i in func]
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(obj1, obj2, obj3, c='r', marker='o')
    plt.draw()
    plt.savefig('results/epMOO_fig.png')
    plt.show()

    print("<Finished in {}, your patient is impressive, Congrads! Author: Jimmy Yao; From github.com/jummy233/epMOO>".format(time.ctime()))


if __name__ == "__main__":
    app = flx.App(Run)
    app.launch('app')
    flx.run()
Beispiel #14
0
            code += f.read()
        if self.BasicAlgo['Gen93 NWSEL']:
            with open(ROOT_PATH + r'\plmnsearch_93.py', 'r') as f:
                code += f.read()
        if self.BasicAlgo['Gen97 NWSEL w.o. INTERRAT RSSI']:
            with open(ROOT_PATH + r'\plmnsearch_97.py', 'r') as f:
                code += f.read()
        if self.BasicAlgo['Gen97 NWSEL with INTERRAT RSSI']:
            with open(ROOT_PATH + r'\plmnsearch_97_INTERRAT_RSSI_n2.py',
                      'r') as f:
                code += f.read()

        flx.logger.info(code)
        code += self.msg_edit.text
        exec(code)


# Dump it to a dictionary of assets that we can serve. Make the main
# page index.html. The link=0 means to pack the whole app into a single
# html page (note that data (e.g. images) will still be separate).
app = flx.App(SmartMS)
assets = app.dump('index.html', link=0)

from django.shortcuts import render
from django.http import HttpResponse


# Create your views here.
def index(request):
    return HttpResponse(assets['index.html'].decode())
Beispiel #15
0
        # Set connections
        n = info.sessions, info.total_sessions
        self.status.set_html('There are %i connected clients.<br />' % n[0] +
                             'And in total we served %i connections.<br />' %
                             n[1])

        # Prepare plots
        times = list(self.cpu_plot.xdata)
        times.append(time() - self.start_time)
        times = times[-self.nsamples:]

        # cpu data
        usage = list(self.cpu_plot.ydata)
        usage.append(info.cpu)
        usage = usage[-self.nsamples:]
        self.cpu_plot.set_data(times, usage)

        # mem data
        usage = list(self.mem_plot.ydata)
        usage.append(info.mem)
        usage = usage[-self.nsamples:]
        self.mem_plot.set_data(times, usage)


if __name__ == '__main__':
    a = flx.App(Monitor)
    a.serve()
    # m = a.launch('browser')  # for use during development
    flx.start()
Beispiel #16
0
        text = self.msg_edit.text
        if text:
            name = self.name_edit.text or 'anonymous'
            relay.create_message(name, text)
            self.msg_edit.set_text('')

    @relay.reaction('create_message')  # note that we connect to relay
    def _push_info(self, *events):
        for ev in events:
            self.messages.add_message(ev.name, ev.message)

    @flx.manager.reaction('connections_changed')
    def _update_participants(self, *event):
        if self.session.status:
            # Query the app manager to see who's in the room
            sessions = flx.manager.get_connections(self.session.app_name)
            names = [s.app.name_edit.text for s in sessions]
            del sessions
            text = '<br />%i persons in this chat:<br /><br />' % len(names)
            text += '<br />'.join(
                [name or 'anonymous' for name in sorted(names)])
            self.people_label.set_html(text)
            asyncio.get_event_loop().call_later(2, self._update_participants)


if __name__ == '__main__':
    a = flx.App(ChatRoom)
    a.serve()
    # m = a.launch('firefox')  # for use during development
    flx.start()
Beispiel #17
0
from flexx import flx


class Exemplo(flx.Widget):
    def init(self):
        flx.Button(text='Olá')
        flx.Button(text='Mundo')


if __name__ == '__main__':
    a = flx.App(Exemplo, title='Flexx demonstração')
    m = a.launch()
    flx.run()
"""
The init method

In the above example one can see the use of the init() method, which is a common use in Flexx. It is generally better to use it instead of __init__(), because Flexx calls it at a very approproate time in the initialization process. For example, when init() is called, the corresponding widget is the default parent.

Further, the init() gets the positional instantiation arguments: creating a component Person("john", 32) matches def init(self, name, age)."""
"""Structuring widgets

Flexx comes with it’s own layout system. (Therefore you should generally not use CSS for widget layout, though you can very well use CSS inside a widget).
Any widget class can also be used as a context manager. Within the context, that widget is the default parent; any widget that is created in that context and that does not specify a parent will have that widget as a parent. (This mechanism is thread-safe.) This allows for a style of writing that clearly shows the structure of your app"""

from flexx import flx


class HSplit(flx.Widget):
    def init(self):
        with flx.HSplit():
            flx.Button(text='foo')
            with flx.VBox():
                flx.Widget(style='background:red;', flex=1)
                flx.Widget(style='background:blue;', flex=1)


app = flx.App(HSplit)
app.export('renders/hsplit.html', link=0)