Exemplo n.º 1
0
def event_order(_msg):
    global Orders
    _doc = document['order']
    _dict = _msg['data']
    _id = "order_{}_{}".format(_msg['_account_'],_dict['OrderRef'])
    _str = str(datetime.datetime.now())[11:19]+" [ {} ] {} 报{}价:{} {} 手数:{} {}".format(_msg['_account_'],_dict['InstrumentID'],DirectionDict.get(_dict['Direction'],"未知方向"),'%.2f'%float(_dict['LimitPrice']),OffsetFlagDict.get(_dict['CombOffsetFlag'],"未知开平"),_dict['VolumeTotalOriginal'],_dict['StatusMsg'])
    _content = html.LABEL(_str)
    _content.style = DirectionStyle.get(_dict['Direction'],{})
    some = html.DIV(_content,id=_id)
    some.style={"text-align":"left"}
    if Orders and Orders[0].id == _id:
        Orders = [some]+Orders[1:count]
    else:
        Orders = [some]+Orders[:count]
    _doc.clear()
    for one in Orders:
        _doc <= one
Exemplo n.º 2
0
def event_trade(_msg):
    global Trades
    _doc = document['trade']
    _dict = _msg['data']
    _id = "trade_{}_{}".format(_msg['_account_'],_dict['OrderRef'])
    _str = str(datetime.datetime.now())[11:19]+" [ {} ] {} {} {} 成交手数:{} 成交价:{}".format(_msg['_account_'],_dict['InstrumentID'],DirectionDict.get(_dict['Direction'],"未知方向"),OffsetFlagDict.get(_dict['OffsetFlag'],"未知开平"),_dict['Volume'],'%.2f'%float(_dict['Price']))
    _content = html.LABEL(_str)
    _content.style = DirectionStyle.get(_dict['Direction'],{})
    some = html.DIV(_content,id=_id)
    some.style={"text-align":"left"}
    if Trades and Trades[0].id == _id:
        Trades = [some]+Trades[1:count]
    else:
        Trades = [some]+Trades[:count]
    _doc.clear()
    for one in Trades:
        _doc <= one
Exemplo n.º 3
0
 def __init__(self, codigo=[], cena=INVENTARIO, img="", vai=None, style=NS):
     class Mark:
         def __init__(self, code):
             self.keys = {"#": self.header, "!": self.image}
             self.code = code = self.process(code)
             self.div = html.DIV(code)
         def process(self, code):
             code = "".join(self.keys[cd.group(0)[0]](cd) for rx in ps for cd in re.finditer(rx, code))
             return code
         def header(self, rg):
             return "<H{l}>{c}</H{l}>".format(l=len(rg.group(1)), c=rg.group(2))
         def image(self, rg):
             return '<img src="{c}" alt="{l}"></img>'.format(l=rg.group(1), c=rg.group(2))
                 
     class Code(Mark):
         def __init__(self, code):
             super().__init__(code)
             self.code = code = self.process(code)
             self.div = html.DIV(code)
         def process(self, code):
             return code
     self.img = img
     self.kind = {0:Mark, 1: Code}
     self.vai = vai if vai else lambda _=0: None
     self.cena = cena
     self.opacity = 0
     self.style = dict(**PSTYLE)
     # self.style["min-width"], self.style["min-height"] = w, h
     self.style.update(backgroundColor='rgba(210, 220, 220, 0.85)', **style)
     self.elt = html.DIV(style=self.style)
     self.xy = (-111, -111)
     istyle = dict(EIMGSTY)
     istyle.update(opacity=0.3)
     self.cell = [self.kind[kind](content) for kind, content in codigo]
     self.codigo = "".join(c.code for c in self.cell)
     if img:
         self.img = html.IMG(src=img, style=istyle)
         self.elt <= self.img
     self.elt.onclick = self._click
     self.scorer = dict(ponto=1, valor=cena.nome, carta=img, casa=self.xy, move=None)
     self._code = html.CODE(codigo)
     self._area = html.PRE(self._code, Class="python", style=dict(
         position='relative', top=0, left=0, backgroundColor='transparent'))
     self.elt <= self._area
     self.code = codigo
     _ = self.entra(cena) if cena and (cena != INVENTARIO) else None
Exemplo n.º 4
0
def show_page(slideshow, zone, page_num):
    # if table of contents is not empty, add it
    if slideshow.contents:
        toc = html.SELECT(name="toc")
        toc.bind(
            'change', lambda ev: show_page(
                slideshow, zone,
                int(ev.target.options[ev.target.selectedIndex].value)))
        for content in slideshow.contents:
            toc <= html.OPTION(
                content[0], value=content[1], selected=page_num >= content[1])

    slideshow.page_num = int(page_num)

    # store page num in a cookie
    document.cookie = "page={}".format(page_num)

    zone.clear()

    body = html.DIV()
    body.html = markdown.mark(slideshow.pages[page_num])[0]

    if slideshow.contents:
        body = html.DIV(toc + body)

    footer = html.DIV(Id="footer")
    if slideshow.title:
        footer <= html.DIV(slideshow.title, style=dict(display='inline'))
    if slideshow.show_page_num:
        footer <= html.SPAN(' (%s/%s)' % (page_num + 1, len(slideshow.pages)),
                            style=dict(display='inline'))
    timeline = html.DIV(Id='timeline')
    tl_pos = html.DIV(Id='tl_pos')
    timeline <= tl_pos
    timeline.bind('click', lambda ev: move_to(ev, slideshow, zone))
    tl_pos.bind('click', click_on_tl_pos)
    zone <= body + footer + timeline
    wh = window.innerHeight
    footer.style.top = "{}px".format(int(wh * 0.9))
    timeline.style.top = "{}px".format(int(wh * 0.85))
    tl_pos.style.left = '%spx' % (timeline.width * page_num /
                                  len(slideshow.pages))
    document["cours"].style.minHeight = "{}px".format(int(wh * 0.8))

    for elt in zone.get(selector='.python'):
        src = elt.text.strip()
        width = max(len(line) for line in src.split('\n'))
        width = max(width, 30)
        # replace element content by highlighted code
        elt.html = highlight.highlight(src).html
        elt.style.width = '%sem' % int(0.7 * width)
        elt.bind('click', run_code)
Exemplo n.º 5
0
def refresh_UI(new_app_info):
    global app_info, current_activity, data_hub, user_info
    user, session_code, app, app_secret = user_info
    window.set_user_name(user)
    window.user_info = ''
    if app in ('me', 'ui', 'elt') and user != '':
        window.user_info = JSON.stringify({
            'user': user,
            'session_code': session_code,
            'app': app,
            'app_secret': app_secret
        })
    document["login"].hidden = (user == '')
    document["logout"].hidden = (user != '')

    for activity in app_info['activities']:
        document['nav-' + activity['id']].unbind('click')
    document["main-nav"].clear()
    app_info.update(new_app_info)
    for activity in app_info['activities']:
        a = html.A(activity['name'], **{
            'id': 'nav-' + activity['id'],
            'class': 'nav-link'
        })
        li = html.LI(a, **{'class': 'nav-item'})
        document["main-nav"] <= li
        a.bind('click', lambda ev: show_activity(ev.target.id))
    document["main"].clear()
    client = user_info[0]
    data_hub = DataHub(client if app_info['app'] == 'db' else '', True)
    for i, activity in enumerate(app_info['activities']):
        page = html.DIV(**{'id': 'page-' + activity['id']})
        document["main"] <= page
        if activity['ui_json'] == '':
            pass
        else:
            make_ui(JSON.parse(activity['ui_json']), page, data_hub)
        page.style.display = 'none'
    if len(app_info['activities']) > 0:
        current_activity = None
        show_activity('nav-' + app_info['activities'][0]['id'])
        data_hub.onevent('', '', '')
    else:
        window.hide_spinner_modal()
Exemplo n.º 6
0
    def __init__(self, config, is_editing):
        self.event_listener = None
        assert 'js_css_files' not in config, config
        files = []
        if 'files' in config:
            files = config['files']
            for file in files:
                if file.endswith('.js') or file.endswith('.css'):
                    window.load_js_css_file(file)
                else:
                    load_py_file(file)
        assert 'tag' in config or 'init' in config, config
        if 'tag' in config:
            self.obj = None
            elt = html.maketag(config['tag'])()

            def handle_event(event):
                if self.event_listener is not None:
                    self.event_listener(event, None)

            for event in config['events']:
                elt.bind(event, lambda ev: handle_event(event))
        else:
            obj = None
            if config['init'] in globals():
                exec('obj = %s()' % config['init'], locals=locals())
            elif config['init'] in window:
                exec('from browser import self as window\nobj = window.%s()' %
                     config['init'],
                     locals=locals())
            if obj is not None:
                self.obj = obj
                elt = obj.elt
            else:
                self.obj = None
                elt = html.DIV(
                    '错误: 无控件', **{
                        'class': 'alert alert-info',
                        'role': 'alert'
                    })
        super(Custom_Component, self).__init__(elt, is_editing)
        self.set_config(config, False)
        if is_editing:
            self.use_example_data()
Exemplo n.º 7
0
def manage_progress(id, percent):
    bar = document.select_one(id)
    bar.style.width = f'{percent}%'
    bar['data-filled'] = f'Loading {percent}%'

    if percent == 0:
        text = document.select_one('#finished')
        text.remove()

    if percent == 100:
        progress_bar = document.select_one('#progress-bar')
        progress_bar.clear()
        progress_bar <= html.BR()
        alert = html.DIV('Carregamento concluído',
                         ID='finished',
                         Class='terminal-alert')
        alert.style.color = '#08D10E'
        alert.style.borderColor = '#08D10E'
        progress_bar <= alert
Exemplo n.º 8
0
    def add_item(self, name, callback=None):
        if self.parent is None:
            # First level
            item = html.SPAN(name)
            if "menu-item-top" in css:
                item.attrs["class"] = css["menu-item-top"]
            self.container <= item
            item.bind("click", self.hide_menus)
        else:
            # Next levels
            item = html.DIV(name)
            self.submenu <= item
            if "menu-item-sub" in css:
                item.attrs["class"] = css["menu-item-sub"]

        if callback is not None:
            item.bind("click", callback)

        return item
Exemplo n.º 9
0
def update_filebrowser(current=None):
    """Update the file browser with all the open files, highlight current
    script."""
    files = list(open_files)
    files.sort()
    filebrowser.clear()
    for f in files:
        line = html.DIV(f, Class="pyfile")
        if f == current:
            line.classList.add("current")
        line.bind("click", display)
        filebrowser <= line
    if current:
        # set information on the "export to local file" button
        content = editor.getValue()
        b64 = base64.b64encode(content.encode("utf-8")).decode("utf-8")
        document["export"].href = ("data:text/plain;charset=utf-8;base64," +
                                   b64)
        document["export"].download = current
Exemplo n.º 10
0
def make_grid(grid):
    # returns an HTML table with 9 rows and 9 columns
    global current_cell, gridDict

    t = html.TABLE(Class="grid")
    for i in range(grid_step):
        cg = html.COLGROUP()
        for j in range(grid_step):
            cg <= html.COL()
        t <= cg
    srow = -1
    # for i,val in enumerate(grid):
    #    row, column = divmod(i, boardSize)
    val = " "
    for row in range(board_size):
        for column in range(board_size):
            if row > srow:
                if row % grid_step == 0:
                    tb = html.TBODY()
                    t <= tb
                line = html.TR()
                tb <= line
                srow = row

            id = initCell(row + 1, column + 1)
            cell = html.DIV(val, id=id, Class="unused")
            cell.bind("mouseenter", on_mouse_enter)
            cell.bind("mouseleave", on_mouse_leave)
            cell.bind("click", on_grid_button_pressed)
            cell.style.contentEditable = True
            
            td = html.TD(id="td"+id)
            td <= cell
            if column % grid_step == 0:
                td.style.borderLeftWidth = "1px"
            if column == board_size - 1:
                td.style.borderRightWidth = "1px"
            line <= td

    current_cell = None
    print(t)
    return t
Exemplo n.º 11
0
 def __init__(self, img="", vai=None, style=NDCT, tit="", alt="",
              x=0, y=0, w=100, h=100, texto='',
              cena=INVENTARIO, score=NDCT, drag=False, drop='', **kwargs):
     self._auto_score = self.score if score else self._auto_score
     self.img, self.title, self.real, self.alt = img, tit, drop, alt
     self._drag = self._over = self._drop = self._dover = self.vai = lambda *_: None
     self.cena = cena
     self.opacity = 0
     self.texto = texto
     self.vai = Texto(cena, texto, foi=self.foi).vai if texto else vai if vai else self.vai
     # height = style["height"] if "height" in style else style["maxHeight"] if "maxHeigth" in style else 100
     # height = height[:-2] if isinstance(height, str) and "px" in height else height
     self.style = dict(**PSTYLE)
     self.style.update(**{'position': 'absolute', 'overflow': 'hidden',
                          'left': x, 'top': y, 'width': '{}px'.format(w), 'height': '{}px'.format(h),
                          'background-image': 'url({})'.format(img),
                          'background-position': '{} {}'.format(0, 0),
                          'background-size': '{}px {}px'.format(w, h)
                          })
     # self.style["min-width"], self.style["min-height"] = w, h
     self.style.update(**style)
     self.elt = html.DIV(Id=tit + drop, title=tit, style=self.style)
     self.xy = (-111, -111)
     self.scorer= {}
     #self.scorer = dict(ponto=1, valor=cena.nome, carta=tit or img, casa=self.xy, move=None)
     #self.scorer.update(score)  
     # if False:
     #     self.img = html.IMG(Id="img_" + tit, src=img, title=tit, alt=alt,
     #                         style=EIMGSTY)  # width=self.style["width"])
     #     self.elt <= self.img
     self.elt.onclick = self._click
     self.c(**kwargs)
     # _ = Dragger(self.elt) if drag else None
     # _ = Droppable(self.elt, drop, self.vai) if drop else None
     _ = self.entra(cena) if cena and (cena != INVENTARIO) else None
     self.elt.ondragstart = lambda ev: self._drag(ev)
     self.elt.onmouseover = lambda ev: self._over(ev)
     self.elt.ondrop = lambda ev: self._drop(ev)
     self.elt.ondragover = lambda ev: self._dover(ev)
     # self.img.onmousedown = self.img_prevent
     self.do_drag(drag)
     self.do_drop(drop)
Exemplo n.º 12
0
 def add_menu(self, name):
     """Add a new submenu in the current menu."""
     if self.parent is not None:
         name += "..."
     li = self.add_item(name)
     # create a DIV for the submenu
     div = html.DIV(style=div_style, Class="submenu")
     if self.parent is None:
         div.style.left = f"{li.abs_left}px"
         div.style.top = f"{li.abs_top + li.offsetHeight}px"
     else:
         left = self.container.abs_left + self.container.offsetWidth
         div.style.left = f"{left}px"
         div.style.top = f"{li.abs_top}px"
     div.style.fontSize = self.container.style.fontSize
     print("font size", div.style.fontSize)
     div.style.display = "none"
     document <= div
     li.bind("click", lambda ev: self.unfold(ev, div))
     return Menu(div, self)
Exemplo n.º 13
0
 def __init__(self,
              cena=NADA,
              tit="",
              txt="",
              texto=None,
              foi=None,
              indo=None,
              **kwargs):
     super().__init__(cena=cena, tit=tit, txt=txt, foi=foi, **kwargs)
     # self.elt = Popup.POP.popup
     self.t = []
     self.cena, self.area = cena, html.DIV()
     if texto is not None:
         self.area = html.TEXTAREA(texto,
                                   Id="_TEXT_POPUP_",
                                   rows=4,
                                   style=dict(width='100%', resize=None))
         self.area.bind('keypress', self.indo)
     self._esconde = foi if foi else lambda: None
     self.indo = indo if indo else self.indo
Exemplo n.º 14
0
	def __init__(self, is_editing):
		style = {'text-align':'center'}
		elt = html.DIV(style=style, **{'class':'ui_placehoder'})
		elt.draggable = False
		super(UI_Placehoder, self).__init__(elt, False)
		self.config = {}
		self.is_editing = is_editing
		if not self.is_editing: return
		elt_img = html.maketag('img')(**{'src':'web/lib/icons/true/ios-add-circle-outline.svg', 'width':'28', 'height':'28'})
		elt_img.draggable = False
		elt <= elt_img
		def dragover(ev):
			if UI_Component.dragging is not None:
				if not UI_Component.dragging.ancestor_of(self):
					if UI_Placehoder.drag_over is None or UI_Placehoder.drag_over is not self:
						if UI_Placehoder.drag_over is not None:
							remove_class(UI_Placehoder.drag_over.elt, 'drop_target')
						if not isinstance(self.parent, UI_Source):
							add_class(self.elt, 'drop_target')
							UI_Placehoder.drag_over = self
			ev.preventDefault() # needed
		def dragleave(ev):
			if UI_Component.dragging is not None:
				if not UI_Component.dragging.ancestor_of(self):
					remove_class(self.elt, 'drop_target')
					UI_Placehoder.drag_over = None
			ev.preventDefault()
		def drop(ev):
			if UI_Placehoder.drag_over is not None:
				if self.parent is not None and (UI_Placehoder.dragging.parent.is_editing or isinstance(UI_Placehoder.dragging.parent, UI_Editor)):
					self.parent.child_drop(self)
				if UI_Placehoder.drag_over is not None:
					remove_class(UI_Placehoder.drag_over.elt, 'drop_target')
					UI_Placehoder.drag_over = None
				if UI_Component.dragging is not None:
					remove_class(UI_Component.dragging.elt, 'drop_source')
					UI_Component.dragging = None
			ev.preventDefault()
		self.elt.bind('drop', drop)
		self.elt.bind('dragover', dragover)
		self.elt.bind('dragleave', dragleave)
Exemplo n.º 15
0
    def code():
        from browser import document, html

        # Construction de la calculatrice
        calc = html.TABLE()
        calc <= html.TR(
            html.TH(html.DIV("0", id="result"), colspan=3) + html.TD("C"))
        lines = ["789/", "456*", "123-", "0.=+"]

        calc <= (html.TR(html.TD(x) for x in line) for line in lines)

        document <= calc

        result = document["result"]  # direct acces to an element by its id

        def action(event):
            """Handles the "click" event on a button of the calculator."""
            # The element the user clicked on is the attribute "target" of the
            # event object
            element = event.target
            # The text printed on the button is the element's "text" attribute
            value = element.text
            if value not in "=C":
                # update the result zone
                if result.text in ["0", "error"]:
                    result.text = value
                else:
                    result.text = result.text + value
            elif value == "C":
                # reset
                result.text = "0"
            elif value == "=":
                # execute the formula in result zone
                try:
                    result.text = eval(result.text)
                except:
                    result.text = "error"

        # Associate function action() to the event "click" on all buttons
        for button in document.select("td"):
            button.bind("click", action)
Exemplo n.º 16
0
    def __init__(self,
                 img=IMAGEM,
                 esquerda=NADA,
                 direita=NADA,
                 meio=NADA,
                 vai=None,
                 nome='',
                 **kwargs):
        width = STYLE["width"]
        self.img = img
        self.nome = nome
        self.dentro = []
        self.esquerda, self.direita, self.meio = esquerda or NADA, direita or NADA, meio or NADA
        self.N, self.O, self.L = [NADA] * 3
        self.vai = vai or self.vai
        self.elt = html.DIV(style=STYLE)
        self.elt <= html.IMG(
            src=self.img, width=width, style=STYLE, title=nome)
        Cena.c(**kwargs)

        self._cria_divs(width)
Exemplo n.º 17
0
    def __init__(self, container=document.body, parent=None, level=0):
        """Create a new menu, inserted inside the container. For the top level
        menu, parent is None, otherwise it is a SPAN item."""
        self.container = container
        self.level = level
        self.parent = parent
        self.submenus = []

        if parent:
            self.submenu = html.DIV(Class="sub")
            if "menu-submenu" in css:
                self.submenu.classList.add(css["menu-submenu"])
            self.submenu.style.position = "absolute"
            self.submenu.style.display = "none"
            self.container <= self.submenu

            parent.bind("click", self.unfold)

        if not hasattr(self.container, "bind_document"):
            document.bind("click", self.hide_menus)
            self.container.bind_document = True
Exemplo n.º 18
0
 def __init__(self,
              bloco,
              certa,
              left=0,
              top=0,
              size=dict(width="25%", height="25%")):
     self.ladrilho = None
     style = {
         'position': "absolute",
         'overflow': 'hidden',
         'border': '1px solid white'
     }
     w, h = int(size['width'][:-1]), int(size['height'][:-1])
     style.update(size)
     style.update(left="%d%%" % (left * w), top="%d%%" % (top * h))
     self.certa = certa
     self.folha = html.DIV(style=style)
     bloco.suporte <= self.folha
     self.folha.ondragover = self.drag_over
     self.folha.ondrop = self.drop
     self.bloco = bloco
Exemplo n.º 19
0
 def __init__(self, bloco, left=0, top=0, ileft=0, itop=0,
              size=dict(width="100px", height="100px")):
     self.suporte = None
     w, h = int(size['width'][:-2]), int(size['height'][:-2])
     ileft, itop = "%dpx" % (ileft*w), "%dpx" % (itop*h)
     style = {'position': 'absolute', 'overflow': 'hidden', 'margin':'1%',
             'background-image': 'url({})'.format(bloco.img),
             'background-position': '{} {}'.format(ileft, itop),
             'background-size': '{}px {}px'.format(400, 400),
     }
     image_style = {'position': "relative", 'min-width': '400px',
     'height': '400px'}  # , 'pointer-events': 'none'}
     style.update(size)
     style.update(left="%dpx" % (left*(w+10)), top="%dpx" % (top*(h+10)))
     #image_style.update(left="%dpx" % (-ileft*w), top="%dpx" % (-itop*h))
     fid = "folha%d" % (10*top+left)
     self.folha = html.DIV(Id=fid, style=style, draggable=True)        
     bloco.folha <= self.folha
     self.folha.ondragstart = self.drag_start
     self.folha.onmouseover = self.mouse_over
     bloco.folhas[fid]=self
Exemplo n.º 20
0
Arquivo: repl.py Projeto: x00b/brython
    def __init__(self):
        frame = sys._getframe().f_back
        Repl.__init__(self,
                      title="Debugger",
                      globals=frame.f_globals,
                      locals=frame.f_locals)

        frames_sel = html.SELECT()
        self.frames = []
        while frame:
            self.frames.append(frame)
            name = frame.f_code.co_name
            name = name.replace("<", "&lt;").replace(">", "&gt;")
            frames_sel <= html.OPTION(name)
            frame = frame.f_back
        frames_sel.bind("change", self.change_frame)
        frame_div = html.DIV("Frame " + frames_sel)
        panel_style = window.getComputedStyle(self.dialog.panel)
        frame_div.style.paddingLeft = panel_style.paddingLeft
        frame_div.style.paddingTop = panel_style.paddingTop
        self.dialog.insertBefore(frame_div, self.dialog.panel)
Exemplo n.º 21
0
    def __init__(self, todo):
        classes = []
        if todo.completed:
            classes.append('completed')
        if todo.editing:
            classes.append('editing')

        super().__init__(
            [
                H.DIV(
                    [
                        TodoCheckbox(todo),
                        TodoEditingLabel(todo),
                        TodoDestroy(todo),
                    ],
                    Class='view',
                ),
                TodoEditor(todo),
            ],
            Class=' '.join(classes),
        )
Exemplo n.º 22
0
 def __init__(self, n):
     html.DIV.__init__(self,
                       "",
                       style={
                           "position": "absolute",
                           'height': "80%",
                           'width': "40%",
                           "background-color": "#1F1F1F"
                       })
     if n % 2 == 1:
         self <= html.DIV(Class="dot", style={'left': "40%", 'top': "40%"})
     if n > 1:
         self <= html.DIV(Class="dot", style={'left': "0%", 'top': "0%"})
         self <= html.DIV(Class="dot", style={'left': "80%", 'top': "80%"})
     if n > 3:
         self <= html.DIV(Class="dot", style={'left': "80%", 'top': "0%"})
         self <= html.DIV(Class="dot", style={'left': "0%", 'top': "80%"})
     if n == 6:
         self <= html.DIV(Class="dot", style={'left': "0%", 'top': "40%"})
         self <= html.DIV(Class="dot", style={'left': "80%", 'top': "40%"})
Exemplo n.º 23
0
Arquivo: main.py Projeto: kwarwp/ada
        def tiler(wd, tile):
            #box <= tile
            tile <= html.BUTTON(
                wd.upper(),
                Class="tile is-child is-dark is-outlined is-inverted")
            lines = [
                html.DIV(Class="tile is-ancestor is-dark") for _ in range(12)
            ]
            [tile <= div for div in lines]
            disp = [(p.nome, tuple(range(inicio, inicio + fim)))
                    for i, p in enumerate(as_pessoas)
                    for wy, inicio, fim in p.disponibilidade if wd == wy]
            slots = {
                slot: [person if slot in dsp else "_" for person, dsp in disp]
                for slot in range(7, 19)
            }
            [[
                lines[slot - 7] <= button(person) for person in persons
                if (slot - 7) < 12
            ] for slot, persons in slots.items()]

            return (disp, slots)
Exemplo n.º 24
0
 def render(self, **ns):
     """Returns the HTML code for the template, with key / values in ns.
     """
     self.python = ''
     self.indent = 0
     self.html = ''
     
     # create empty DIV to store the content of template file
     self.zone = html.DIV(style=dict(display="none"))
     self.zone.html = open(self.url).read()
     document <= self.zone
     
     # Generate the Python code to execute
     self.ns = ns
     self.parse(self.zone)
     
     # Add name "__write__" to namespace, alias for self.write, used in the
     # generated Python code
     self.ns.update({'__write__': self.write})
     
     # Executing the Python code will store HTML code in self.html
     try:
         exec(self.python, self.ns)
     except Exception as exc:
         print(self.python)
         if isinstance(exc, SyntaxError):
             line_no = exc.args[2]
         else:
             line_no = exc.traceback.tb_lineno
         elt = self.line_mapping[line_no]
         for item in elt.attributes:
             if item.name in ["code", "expr"]:
                 print(item.value)
                 print('{}:'.format(exc.__class__.__name__), exc)
 
     # Remove temporary DIV
     self.zone.remove()
     
     return self.html
Exemplo n.º 25
0
    def add_menu(self, name):
        """Add a new submenu in the current menu."""
        if self.parent is not None:
            name += "..."
        td = self._make_item(name)
        # create a DIV for the submenu
        div = html.DIV(Class="submenu")
        div.open_child = None
        if self.parent is None:
            div.style.left = f"{td.abs_left}px"
            div.style.top = f"{td.abs_top + td.offsetHeight}px"
        else:
            left = self.container.abs_left + self.container.offsetWidth
            div.style.left = f"{left}px"
            div.style.top = f"{td.abs_top}px"
        div.style.fontSize = self.fontSize
        div.style.display = "none"
        document <= div
        if self.parent is None:
            @bind(td, "click")
            def click(ev):
                if not self.selecting:
                    self.hide_submenus()
                    self.unfold(ev, div)

            @bind(td, "mouseover")
            def mouseover(ev):
                if self.selecting:
                    self.hide_submenus()
                    self.unfold(ev, div)
        else:
            @bind(td, "mouseover")
            def unfold(ev):
                self.unfold(ev, div)

        self.ignore_dblclick(td)

        return Menu(div, self)
Exemplo n.º 26
0
 def __init__(self,
              img="",
              vai=None,
              style=NS,
              tit="",
              alt="",
              tel=DOC_PYDIV,
              **kwargs):
     self.img = img
     self.vai = vai if vai else lambda _=0: None
     self.tela = tel
     self.opacity = 0
     self.style = dict(**PSTYLE)
     # self.style["min-width"], self.style["min-height"] = w, h
     self.style.update(style)
     self.elt = html.DIV(Id=tit, style=self.style)
     if img:
         self.img = html.IMG(src=img, title=tit, alt=alt,
                             style=EIMGSTY)  # width=self.style["width"])
         self.elt <= self.img
     self.elt.onclick = self._click
     self.tela <= self.elt
     self.c(**kwargs)
Exemplo n.º 27
0
    def __init__(self, title="Frames inspector",
                   rows=30, cols=84, default_css=True):
        frame = sys._getframe().f_back
        super().__init__(None, title,
                      globals=frame.f_globals.copy(),
                      locals=frame.f_locals.copy(),
                      rows=rows, cols=cols, default_css=default_css)

        frames_sel = html.SELECT()
        self.frames = []
        while frame:
            self.frames.append([frame.f_globals.copy(),
                                frame.f_locals.copy()])
            name = frame.f_code.co_name
            name = name.replace("<", "&lt;").replace(">", "&gt;")
            frames_sel <= html.OPTION(name)
            frame = frame.f_back
        frames_sel.bind("change", self.change_frame)
        frame_div = html.DIV("Frame " + frames_sel)
        panel_style = window.getComputedStyle(self.dialog.panel)
        frame_div.style.paddingLeft = panel_style.paddingLeft
        frame_div.style.paddingTop = panel_style.paddingTop
        self.dialog.insertBefore(frame_div, self.dialog.panel)
Exemplo n.º 28
0
    def __init__(self, *args, **kwargs):
        """"""
        super().__init__(*args, **kwargs)

        tone = Tone()
        style = {
            'margin-top': '25vh',
            'width': '30vw',
            'display': 'grid',
            'grid-auto-flow': 'unset',
            'grid-row-gap': '10px',
            'margin-left': '35vw',
        }
        parent = html.DIV(style=style)

        select = MDCSelect('Tone', note_values.items(), outline=True)
        play_button = MDCButton("Play", raised=True)
        play_button.bind('click', lambda evt: tone(select.mdc['value'], 100))

        parent <= select
        parent <= play_button

        document <= parent
Exemplo n.º 29
0
def event_tick(_msg):
    global Ticks
    global TickDict
    _doc = document['marketdata']
    _l = _doc.children
    _data = _msg['data']
    _id = "tick_{}".format(_data['InstrumentID'])
    _content = width_label(_data['InstrumentID'],100)
    _content += width_label("叫卖1",30)+width_label(_data["AskPrice1"],50)+width_label(_data["AskVolume1"],50)
    _content += width_label("叫买1",50)+width_label(_data["BidPrice1"],50)+width_label(_data["BidVolume1"],50)
    _content += width_label("最新价",40)
    _content += width_label(_data["LastPrice"],50)
    _content += width_label("成交量",40)
    _content += width_label(_data["Volume"],50)
    _content += width_label(_data["UpdateTime"],50)
    _content += width_label(_msg["_qsize_"],10)
    some = html.DIV(_content,id=_id)
    some.style={"text-align":"left"}
    Ticks.add(_id)
    TickDict[_id] = some
    _doc.clear()
    for one in Ticks:
        _doc <= TickDict[one]
Exemplo n.º 30
0
def event_account(_msg):
    global Accounts
    global AccDict
    _doc = document['account']
    _dict = _msg['data']
    _id = "account_{}".format(_msg['_account_'])
    Accounts.add(_id)
    _str = ''
    _str += width_label("帐号", 30)
    _str += width_label(_msg['_account_'], 80)
    _str += width_label("持仓盈亏", 50)
    _str += width_label('%.2f' % float(_dict['PositionProfit']), 80)
    _str += width_label("可用", 30)
    _str += width_label('%.2f' % float(_dict['Available']), 80)
    _str += width_label("净值", 30)
    _str += width_label('%.2f' % float(_dict['Balance']), 80)
    _content = html.LABEL(_str)
    some = html.DIV(_content, id=_id)
    some.style = {"text-align": "left"}
    AccDict[_id] = some
    _doc.clear()
    for one in Accounts:
        _doc <= AccDict[one]