def __init__(self, container, rows=20): table = html.TABLE(style=styles["panel"]) menu_td = html.TD(colspan=2, style=styles["menu"]) self.menu = menu.Menu(menu_td) m1 = self.menu.add_menu("Edition") m1.add_item("Search", self.search_dialog) table <= html.TR(menu_td) self.linenums = html.TEXTAREA(rows=21, cols=5, autocomplete="off", disabled=True, style=styles["linenums"]) self.editor = html.TEXTAREA(rows=20, cols=120, wrap="off", autocomplete="off", spellcheck="false", style=styles["editor"]) table <= html.TR( html.TD(self.linenums, valign="top") + html.TD(self.editor, valign="top")) container <= table self.editor.bind("keydown", self.keydown) self.editor.bind("keyup", self.keyup) self.editor.bind("scroll", self.scroll) self.set_line_nums() self.stack = [] self.store_undo()
def addFailure(self, test, err): self.failure_count += 1 TestResult.addFailure(self, test, err) row = html.TR(self.ident(test), Class="method") row <= html.TD('fail', Class="report_cell") row <= (html.TD(x) for x in self.excInfos(test, err)) document['report'] <= row
def display_map() -> None: table = html.TABLE(style={"border": "1 solid grey"}) table <= html.TR(html.TH("Text") + html.TH("Base64")) table <= (html.TR(html.TD(key) + html.TD(b64_map[key])) for key in b64_map) base64_display = document["b64-display"] base64_display.clear() base64_display <= table
def display_map(): table = html.TABLE(Class="pure-table") table <= html.THEAD(html.TR(html.TH("Text") + html.TH("Base64"))) table <= (html.TR(html.TD(key) + html.TD(b64_map[key])) for key in b64_map) base64_display = document["b64-display"] base64_display.clear() base64_display <= table document["text-src"].value = ""
def addError(self, test, err): self.error_count += 1 TestResult.addError(self, test, err) row = html.TR(self.ident(test), Class="method") row.style.backgroundColor = "violet" row <= html.TD('fail', Class="report_cell") row <= (html.TD(x) for x in self.excInfos(test, err)) document['report'] <= row
def ident(self, test): return [ html.TD(test.__class__.__name__), html.TD(test._testMethodName), html.TD(test.lineno, Class="number"), html.TD(round(1000 * (time.time() - test.startTime)), Class="number") ]
def show_results(self): """ show table of results""" doc['container'].clear() doc['container'] <= html.DIV( 'Browser Version: %s' % window.navigator.userAgent) _v = sys.implementation.version doc['container'] <= html.DIV('Brython Version: %s.%s.%s' % (_v.major, _v.minor, _v.micro)) doc['container'] <= html.DIV( 'Brython debug mode: %s' % sys.brython_debug_mode) doc['container'] <= html.DIV( 'CPython Version: %s' % self.cpython_version) doc['container'] <= html.P(html.I('Results are in milliseconds (ms)')) _table = html.TABLE() _tr = html.TR() _tr <= html.TH('Benchmark') _tr <= html.TH('Code') _tr <= html.TH('Brython') _tr <= html.TH('CPython') _tr <= html.TH('Difference') _tr <= html.TH('X Faster') _table <= _tr for _filename in self._timings.keys(): _tr = html.TR() _tr <= html.TD(_filename) _tr <= html.TD( highlight.highlight(self._timings[_filename]['code'])) for _platform in ('brython', 'cpython'): _tr <= html.TD('%5.0f' % self._timings[_filename][_platform], style={'text-align': 'right'}) _diff = self._timings[_filename]['cpython'] - self._timings[ _filename]['brython'] _x = self._timings[_filename]['cpython'] / self._timings[ _filename]['brython'] if _x > 1: _color = "green" elif _x < 0.5: _color = "red" else: _color = "black" _tr <= html.TD('%5.0f' % _diff, style={'text-align': 'right'}) _tr <= html.TD('%4.2f' % _x, style={ 'color': _color, 'text-align': 'right' }) _table <= _tr doc['container'] <= _table
def _make_item(self, name): if self.parent is None: # Add item to main menu bar td = html.TD(name, Class="menu-item-top") self.panel <= td else: # Add item to submenu td = html.TD(name, Class="menu-item-sub") self.panel <= html.TR(td) td.style.fontSize = self.fontSize return td
def display_map(): if not hash_map: return table = html.TABLE(Class="pure-table") table <= html.THEAD(html.TR(html.TH("Text") + html.TH("SHA-256"))) table <= (html.TR(html.TD(key) + html.TD(hash_map[key])) for key in hash_map) hash_display = document["hash-display"] hash_display.clear() hash_display <= table document["text-src"].value = ""
def addSuccess(self, test): self.success_count += 1 TestResult.addSuccess(self, test) row = html.TR(self.ident(test), Class="method") row.style.backgroundColor = "lightgreen" row <= html.TD('ok', colspan=2, Class="report_cell") document['report'] <= row
def build_grid(self) -> None: """Create the grid with the letters.""" table = html.TABLE(CLass='p300') tr = html.TR() table <= tr characters_train, ncols = CHARACTERS for i, char in enumerate(characters_train): char_print = CHARACTERS_SRLZ[i] row = i // ncols col = i % ncols if row == 6: style = {"font-size": "6vh"} else: style = {} td = html.TD( char, Class=f'p300-char p300-{char_print}- col-{col} row-{row}', style=style) td.attrs['char'] = char_print tr <= td if i != 0 and not (i + 1) % ncols: tr = html.TR() table <= tr self.stimuli_area <= table
def addSubTest(self, test, subtest, err): TestResult.addSubTest(self, test, subtest, err) # special case, don't use ident() cell2 = (test._testMethodName + html.BR() + str(subtest._subDescription())) row = html.TR([html.TD(test.__class__.__name__), html.TD(cell2), html.TD(test.lineno, Class="number"), html.TD(round(1000*(time.time() - test.startTime)), Class="number")], Class="method") row <= html.TD('ok', colspan=2, Class="report_cell") # reset startTime test.startTime = time.time() document['report'] <= row
def draw(self, parent_node): self.node = html.DIV(Class="task", Id=self.id, draggable=True) self.node.style.backgroundColor = DB["TASKS_COLORS"][self.color] parent_node <= self.node self.zprogress = html.DIV(Class="task_progress") self.progress_text = html.P("%d" % self.progress + "%", Class="task_progress_text") self.zprogress <= self.progress_text self.progress_bar = html.DIV(Class="task_progress_bar") self.progress_bar.style.width = percent(self.progress) self.zprogress <= self.progress_bar self.command_delete = html.DIV("X", Class="task_command_delete") self.command = html.TABLE(html.TR( html.TD(self.zprogress, Class="task_command") + html.TD(self.command_delete)), Class="task_command") self.node <= self.command self.zdesc = html.P(Class="task_desc") self.node <= self.zdesc self.node.drop_id = self.id self.node.task = self self.node.bind('dragstart', self.drag_start) self.node.bind('dragover', self.drag_over) self.node.bind('drop', self.drag_drop) self.node.bind('click', self.color_change) self.zprogress.task = self self.zprogress.bind('click', self.make_progress) self.command_delete.task = self self.command_delete.bind('click', self.task_delete) self.zdesc.task = self self.zdesc.desc = self.desc self.zdesc.bind('click', self.task_edit) self.set_text() for task in self.tasks: task.draw(self.node)
def __init__(self): super().__init__("Data Table", "#fbd0d0", tabwidth="12%", id="datatable") lines = open("cost-of-living-2018.csv").readlines() data = [line.strip().split(",") for line in lines[:26]] self.attach(html.TABLE( html.TR(html.TH(header) for header in data[0]) + (html.TR(html.TD(field) for field in row) for row in data[1:]) ))
def on_complete(*args): doc['container'] <= html.PRE('Results are in milliseconds (ms)') doc['container'] <= html.PRE( 'Browser Version:%s' % window.navigator.userAgent) _v = sys.implementation.version doc['container'] <= html.PRE('Brython Version:%s.%s.%s' % (_v.major, _v.minor, _v.micro)) _table = html.TABLE() _tr = html.TR() _tr <= html.TH('Benchmark') _tr <= html.TH('Brython') _tr <= html.TH('CPython') _tr <= html.TH('Difference') _tr <= html.TH('X Faster') _table <= _tr for _filename in self._timings.keys(): _tr = html.TR() _tr <= html.TD(_filename) for _platform in ('brython', 'cpython'): _tr <= html.TD( '%5.0f' % self._timings[_filename][_platform], style={'text-align': 'right'}) _diff = self._timings[_filename]['cpython'] - self._timings[ _filename]['brython'] _x = self._timings[_filename]['cpython'] / self._timings[ _filename]['brython'] if _x > 1: _bg = "green" elif _x < 0.5: _bg = "red" else: _bg = "yellow" _tr <= html.TD('%5.0f' % _diff, style={'text-align': 'right'}) _tr <= html.TD('%4.2f' % _x, style={ 'background': _bg, 'text-align': 'right' }) _table <= _tr doc['container'] <= _table doc['container'] <= html.PRE("results uploaded...")
def load(sheet_name=None): global current_cell_info, menu_file if sheet_name is None: sheet_name = 'New document' panel = document['panel'] title = html.DIV(style=dict(width='auto')) title <= html.H2(sheet_name, id="sheet_name") panel <= title menu = ui.Menu() menu_file = menu.add('File') menu_file.add('New', None) menu_file.add('Open...', select_sheet) menu_file.add('Save as...', save_as) panel <= html.SPAN(menu) panel <= html.BR() cell_editor = html.INPUT(style=dict(width="200px"), Id="current") cell_editor.bind('click', enter_editor) cell_editor.bind('keydown', editor_keydown) cell_editor.bind('keyup', update_from_editor) panel <= cell_editor t = html.TABLE(Id="sheet_table") srow = -1 rows, cols = 20, 20 col_widths = [100 for i in range(rows)] line = html.TR() line <= html.TH() for i in range(cols): col_name = chr(65 + i) line <= html.TH(col_name, style={'min-width': '%spx' % col_widths[i]}) t <= line for i in range(rows * cols): row, column = divmod(i, cols) if row > srow: line = html.TR() line <= html.TH(row + 1) t <= line srow = row cell = html.TD('', id='c%s_%s' % (row, column), style=dict(padding='2px')) cell.bind('click', select) cell.bind('dblclick', entry) cell.info = {'entry': ''} line <= cell panel <= html.DIV(t, style=dict(float='left')) mark_selected(t.get(selector='TD')[0])
def create_root(self): root = html.DIV() root <= html.DIV( html.B( f"Replicator - Un Ennemi du peuple ({version})")) + html.BR() table = html.TABLE() table <= html.TR( html.TD("1. Sélectionner le personnage", Id="char_sel_panel_title") + html.TD("2. Sélectionner la scène", Id="scene_sel_panel_title")) table <= html.TR( html.TD(self.create_character_selection_panel(), Id="char_sel_panel_td") + html. TD(self.create_scene_selection_panel(), Id="scene_sel_panel_td")) root <= table root <= html.HR() root <= html.DIV("3. Jouer", Id="start_game_panel_title") root <= html.DIV(self.create_start_game_panel(), Id="start_game_panel") return root
def add_item(self, label, callback=None, menu=False): if self.parent is None: # First level item = html.SPAN(label, Class="brython-menu-navbar-item") self.container <= item item.bind("click", self.hide_menus) else: # Next levels item = html.TR(Class="brython-menu-submenu-row") self.parent.submenu <= item item <= html.TD(label, Class="brython-menu-submenu-item") item <= html.TD(">" if menu else " ", Class="brython-menu-submenu-item", paddingLeft="2em") if callback is not None: item.bind("click", callback) return item
def cria_tabela(mapa, id): tbl = browser.document[id] tbl.innerHTML = '' for i in range(len(mapa)): linha = html.TR() for j in range(len(mapa[i])): celula = html.TD() celula.class_name = 'parede' if mapa[i][j] == '#' else 'chao' linha <= celula tbl <= linha
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)
def load(sheet_name=None): global current_cell_info, menu_file panel = document['panel'] cell_editor = html.DIV("A", style=dict(width="25%", padding="5px", marginBottom="20px", height="1.5em"), Id="current", contentEditable="true", Class="selected") cell_editor.bind('click', enter_editor) cell_editor.bind('keydown', editor_keydown) cell_editor.bind('keyup', update_from_editor) panel <= cell_editor t = html.TABLE(Id="sheet_table") srow = -1 rows, cols = 20, 20 col_widths = [100 for i in range(rows)] line = html.TR() line <= html.TH() for i in range(cols): col_name = chr(65 + i) line <= ColumnHead(col_name, Class="col-head", style={'min-width': '%spx' % col_widths[i]}) t <= line for i in range(rows * cols): row, column = divmod(i, cols) if row > srow: line = html.TR() line <= RowHead(row + 1, Class="row-head") t <= line srow = row cell = html.TD(contentEditable="true", style=dict(padding='2px')) cell.bind("click", select) cell.bind("focus", focus) cell.bind("keyup", keyup) cell.bind("blur", blur) cell.info = {'entry': ''} line <= cell panel <= html.DIV(t, style=dict(float='left')) for cell in document.get(selector="th.row-head"): cell.bind("mousedown", select_row) t.get(selector='TD')[0].dispatchEvent(window.MouseEvent.new("click"))
def draw_task(self, task, parent_node): node = html.DIV(Class="task", Id=task.id, draggable=True) node.style.backgroundColor = self.kanban.tasks_colors[task.color_id] parent_node <= node progress = html.DIV(Class="task_progress") progress_text = html.P("%d%%" % task.progress, Class="task_progress_text") progress <= progress_text progress_bar = html.DIV(Class="task_progress_bar") progress_bar.style.width = percent(task.progress) progress <= progress_bar command_delete = html.DIV("X", Class="task_command_delete") command = html.TABLE(html.TR( html.TD(progress, Class="task_command") + html.TD(command_delete)), Class="task_command") node <= command desc = html.P(Id="desc %s" % task.id, Class="task_desc") desc.html = task.desc node <= desc node.bind('dragstart', ev_callback(self.drag_start, task)) node.bind('dragover', self.drag_over) node.bind('drop', ev_callback(self.drag_drop, task)) node.bind('click', ev_callback(self.change_task_color, task, node)) progress.progress_bar = progress_bar progress.progress_text = progress_text progress.bind('click', ev_callback(self.make_task_progress, task, progress)) command_delete.bind('click', ev_callback(self.remove_task, task)) desc.bind('click', ev_callback(self.edit_task, task)) self.draw_tasks(task, node)
def process_inventory(event): global inventory try: inventory = JSON.parse(event.target.result) fusedict = {} mooglelist = [u['tmrId'] for u in inventory if u['id'] == moogleid] containerlist = [u['tmrId'] for u in inventory if u['id'] == containerid if u['tmr'] <1000] ownedunits = [u['id'][:-1] for u in inventory if u['id'][0] != '9' if u['tmr'] <1000 ] for tmrId in mooglelist: tmrName = weapondict[tmrId]['name'] tmrUnit = weapondict[tmrId]['tmrUnit'] unitName = unitdict[tmrUnit]['name'] if tmrUnit[:-1] in ownedunits: if tmrId in fusedict.keys(): fusedict[tmrId]['count'] += 1 else: fusedict.update({tmrId:{'tmr':tmrName, 'unit':unitName, 'count':1, 'unitid':tmrUnit}}) if tmrId in containerlist: if tmrId in fusedict.keys(): fusedict[tmrId]['count'] += 1 else: fusedict.update({tmrId:{'tmr':tmrName, 'unit':containername[code], 'count':1, 'unitid':containerid}}) fusesort = sorted(fusedict.items(), key = lambda item: item[1]['tmr']) document['results'].clear() table = html.TABLE(Class='table table-hover') tbody = html.TBODY() table <= tbody for l in fusesort: tbody <= html.TR([html.TD(l[1]['tmr']), html.TD('\tx' + str(l[1]['count']) + '\t'), html.TD(l[1]['unit']), html.TD(html.IMG(src='https://ffbeequip.com/img/units/unit_icon_' + l[1]['unitid'] + '.png' ) )] ) document['results'] <= table except: alert('Error: Invalid file!') if 'ion-md-checkmark-circle' in filestatus.classList: filestatus.classList.remove('ion-md-checkmark-circle') filestatus.classList.add('ion-md-close-circle') elif 'ion-md-hourglass' in filestatus.classList: filestatus.classList.remove('ion-md-hourglass') filestatus.classList.add('ion-md-close-circle')
def add_link(self, label, href): """Add a link to the specified address.""" if self.parent is None: # First level item = html.A(label, Class="brython-menu-navbar-link", href=href) self.container <= item else: # Next levels item = html.TR(Class="brython-menu-submenu-row") self.parent.submenu <= item item <= html.TD( html.A(label, Class="brython-menu-submenu-link", href=href)) return item
def make_numbers(): t = html.TABLE() tb = html.TBODY() t <= tb i = 1 val = "" for row in range(5): line = html.TR() tb <= line for column in range(10): b = html.BUTTON(str(i), id="x%s" % i, Class="nobutton") cell = html.TD(b) b.bind("click", on_number_button_pressed) line <= cell i += 1 return t
def init(): global state start_pos = (7, 7) for i in range(SIZE): row = html.TR() for j in range(SIZE): state[(i, j)] = None # Initialize game state square = html.TD('', id=f"square_{i}_{j}", Class="square") if (i, j) in PREMIUMS: kind = PREMIUMS[(i, j)] elif (i, j) == start_pos: kind = "start" else: kind = "white" square.style.backgroundColor = COLORS[kind] BOARD[(i, j)] = COLORS[kind] row <= square document["game-board"] <= row
def excInfos(self, test, err): tb = err[2] infos = [] while tb: fname = tb.tb_frame.f_code.co_filename if fname == test.__class__.__module__: infos.append(tb.tb_lineno) tb = tb.tb_next infos = infos or ['<nc>'] try: str(err[1]).splitlines() except: alert(err[1]) alert(type(err[1])) return [ html.TD("line %s - %s: %s" % (infos[-1], err[0].__name__, str(err[1]).splitlines()[0]), Class="error_message") ]
def excInfos(self, test, err): tb = err[2] infos = [] while tb: fname = tb.tb_frame.f_code.co_filename if fname == sys.modules[test.__class__.__module__].__file__: infos.append(tb.tb_lineno) tb = tb.tb_next infos = infos or ['<nc>'] try: str(err[1]).splitlines() except: alert(err[1]) alert(type(err[1])) lines = "\n".join(f"line {line}" for line in infos[:-1]) return [html.TD(lines + "\nline %s - %s: %s" %(infos[-1], err[0].__name__, str(err[1]).splitlines()[0].replace('<', '<')), Class="error_message")]
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
def make_grid(w, grid_size): t = html.TABLE(Class="ws") tb = html.TBODY() t <= tb for row in range(grid_size): wordline = w.grid[row] line = html.TR() tb <= line for column in range(grid_size): val = wordline[column] id = initCell(row + 1, column + 1) cell = html.TD(val, id=id, Class="ws") line <= cell cell.bind("mouseenter", on_mouse_enter) cell.bind("mouseleave", on_mouse_leave) cell.bind("click", on_grid_button_pressed) cell.bind("dblclick", dblclick) cell.style.contentEditable = True return t