def create_search(self):
     dindex.style.display = 'none'
     dtop.clear()
     doutput.clear()
     #
     document.title = f'{self.release} Search'
     dtop <= SPAN(f'{self.release}')
     dtop <= SPAN(A('Index', href='#'))
     #
     dsearch = DIV()
     doutput <= dsearch
     dsearch.style.paddingLeft = '20px'
     chars = sorted({item[0].upper() for item in self.udf_list})
     div = DIV()
     div.style.marginBottom = '10px'
     dsearch <= div
     for c in chars:
         span = SPAN(c)
         span.style.color = 'blue'
         span.style.textDecoration = 'underline'
         span.style.padding = '2px 5px 10px 5px'
         span.style.cursor = 'pointer'
         span.onclick = self.click_one
         div <= span
     #
     input = INPUT(type="text")
     input.title = 'Search'
     input.style.width = '40ch'
     input.style.marginBottom = '10px'
     dsearch <= input
     input.bind('input', self.input_change)
     #
     dsearch <= DIV(id='searchresult')
示例#2
0
 def render(self):
     return group(DIV(Class="card shadow-sm", style={"margin": "20px"}), [
         group(DIV(Class="card-header"), [
             H3(f"Title: {self.title}", style={"font-weight": "bolder"}),
         ]),
         H5(f"Description: {self.description}", Class="card-body")
     ])
示例#3
0
def header():
    """
    Footer que será usado em todas as páginas.

    A implementação desse header está baseada na implementação do terminal CSS

    Foi feita uma cópia do header princial e resontruíuda em bryhton.
    link: https://terminalcss.xyz/dark/#Navigation
    """
    div_container = DIV(Class='container')
    terminal_nav = DIV(Class='terminal-nav')
    header = DIV(Class='terminal-logo', id='header')
    terminal_menu = NAV(Class='terminal-menu')
    logo = DIV(Class='logo terminal-prompt')
    link_logo = A('Olar Jovis :)', Class='no-style')
    link_logo.href = '/'

    ul = UL()
    youtube = nav_element('Youtube', 'https://www.youtube.com/eduardomendes')
    apoiase = nav_element('Apoia.se', 'https://apoia.se/livedepython')
    curso = nav_element('Curso',
                        'https://dunossauro.github.io/curso-python-selenium')
    cdc = nav_element(
        'CDC',
        'https://github.com/dunossauro/curso-python-selenium/blob/master/cdc.md',  # NOQA
    )

    logo <= link_logo
    header <= logo
    ul <= youtube + apoiase + curso + cdc
    terminal_menu <= ul
    terminal_nav <= header
    terminal_nav <= terminal_menu
    div_container <= terminal_nav
    document['header'] <= div_container
示例#4
0
def menu():
    div = DIV(Class="menu")
    ul = UL()

    li_inicio = LI(A('Início', href="index.html"))
    li_curriculo = LI(A('Currículo', href="curriculo.html"))
    li_sobre = LI(A('Sobre', href="sobre.html"))

    a_utilidades = A('Utilidades', href="utilidades.html", Class="dropbtn")
    li_utilidades = LI(Class="dropdown")
    li_utilidades <= a_utilidades
    div_utilidades = DIV(Class="dropdown-content")
    div_utilidades <= A('Sites Úteis', href="sites.html") + A(
        'Dicas Úteis', href="dicas.html") + A(
            'Códigos Úteis', href="codigos.html") + A(
                'Livros Úteis', href="livros.html") + A(
                    'Programas Úteis', href="programas.html") + A(
                        'Frases Úteis', href="frases.html") + A(
                            'Materiais Úteis', href="materiais.html")
    li_utilidades <= div_utilidades

    li_python = LI(A('Python', href="python.html"))
    li_jquery = LI(A('JQuery', href="jquery.html"))
    li_contato = LI(A('Contato', href="contato.html"))

    ul <= li_inicio + li_curriculo + li_sobre + li_utilidades + li_python + li_jquery + li_contato
    div <= ul
    return div
示例#5
0
文件: dashboard.py 项目: Enforcer/PAW
 def appendCommentToDom(author, when, content):
     length = len(cell6.get(selector='.comment'))
     colour = '' if length % 2 == 0 else ' callout'
     #colour = ''
     panel = DIV()
     panel.class_name = 'panel comment' + colour
     panel <= B('{0} dnia {1}'.format(author, when))
     panel <= P(content)
     cell6 <= panel
示例#6
0
文件: app.py 项目: pbandierapaiva/nut
	def __init__(self):
		DIV.__init__(self) #, style={'max-width':'90px'})
		selTable = TABLE()
		self <= selTable
		self.inText = INPUT(Class="form-control")
		self.inText.bind('keyup',self.entrou)
		selTable<=TR(TD(P("Busca: ")+self.inText))   #,name="intext"))
		self.sel = SELECT(size=8,Class='form-control')     # style={'max_width':'90px'})
		self.sel.bind('input',self.selec)
		selTable<=TR(TD(self.sel))
		self.sel.style.display = 'none'
		self.nutTab = MostraNut()
		self <= self.nutTab
示例#7
0
文件: gui.py 项目: boribs/chessengine
def create_moving_piece(origin_id):
    origin = get_square(origin_id)
    x = 4 if int(origin_id) % 8 == 0 else 3  # Idk why, but it fixes things.
    y = 2 if int(origin_id) < 8 else 1

    piece_div = DIV(id='moving-piece',
                    style={
                        'left': f'{origin.x + x}px',
                        'top': f'{origin.y + y}px',
                        'z-index': -1,
                    })
    piece_div.innerHTML = origin.innerHTML
    document <= piece_div
示例#8
0
def barra_lateral():
    barraLateral = DIV(Class="barra-lateral")
    espacamento = DIV(Class="espacamento")
    mais = H1("Mais")
    palavra = P(
        "Se algum de vocês tem falta de sabedoria, peça-a a Deus, que a todos dá livremente, de boa vontade; e lhe será concedida. - Tiago 1:5"
    )
    img = IMG(src="img/psg7.jpg")
    espacamento <= mais
    espacamento <= palavra
    espacamento <= img
    barraLateral <= espacamento
    return barraLateral
示例#9
0
def cabecalho():
    div = DIV(Class="cabecalho")

    logo = DIV(Class="logo-cabecalho")
    logo <= A("Meu Blog", href="index.html")

    pesquisa = DIV(Class="pesquisa")
    pesquisa <= INPUT(type="text")
    pesquisa <= INPUT(type="submit", value="Pesquisar")

    div <= logo
    div <= pesquisa
    return div
示例#10
0
文件: app.py 项目: pbandierapaiva/nut
 def __init__(self):
     DIV.__init__(self)  #, style={'max-width':'90px'})
     selTable = TABLE()
     self <= selTable
     self.inText = INPUT(Class="form-control")
     self.inText.bind('keyup', self.entrou)
     selTable <= TR(TD(P("Busca: ") + self.inText))  #,name="intext"))
     self.sel = SELECT(size=8,
                       Class='form-control')  # style={'max_width':'90px'})
     self.sel.bind('input', self.selec)
     selTable <= TR(TD(self.sel))
     self.sel.style.display = 'none'
     self.nutTab = MostraNut()
     self <= self.nutTab
示例#11
0
def homePage():
    return group(
        DIV(Class=
            "container d-flex flex-column justify-content-center align-items-center",
            style={"height": "100vh"}),
        [
            H1("Breact: A python framework for single page webapps",
               Class="text-center"),
            P('''
            This app was coded in python in Breact. Look in the inspector, and you will see
            <br>
            <code>&lt;script src="text/python" &gt; </code>
        ''',
              Class="text-center"),

            # P('''
            #     Breact is similar to react,
            #     with components and state. The main difference, however, is that
            #     Breact doesn't have a virtual dom; instead, each stateful element
            #     (element that uses setState) is assigned a unique id and is retrieved
            #     and changed when necessary. Breact is very lightweight- the main base
            #     class file is at around 40 lines of code; but that's just because some parts of react;
            #     lifecycle methods, or stateful functional components, haven't been implemented yet.
            # ''', Class="text-center"),
            H3("Sample Apps:"),
            Link("/todo").render(
                BUTTON("Simple Todolist", Class="btn btn-primary m-2")),
            Link('/quiz').render(
                BUTTON("Small Quiz", Class="btn btn-primary m-2")),
            Link('/playground').render(
                BUTTON("A Little Playground", Class="btn btn-primary m-2")),
            Link('/router-playground').render(
                BUTTON("Router Playground", Class="btn btn-warning m-2"))
        ])
示例#12
0
    def render(self):
        return group(
            DIV(Class=
                "container d-flex flex-column justify-content-center align-items-center",
                style={"height": "100vh"}), [Quiz().render()])


# document <= Main().render()
示例#13
0
    def toast(event):
        new = DIV(event.path[2].id + " / " + event.path[1].id, Class='toast')
        document['desenv'] <= new

        def hidden():
            new.style.display = 'none'

        timer.set_timeout(hidden, 3000)
示例#14
0
def handle_msg_process_mgr_closed(msg):
    """<div class="alert alert-danger" role="alert">...</div>"""
    ctn = doc['ctn_alerts']
    # TODO - Fix the dismiss button:
    #<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    new_div = DIV("Process manager closed",
                  Class="alert alert-danger alert-dismissible",
                  role="alert")
    ctn <= new_div
示例#15
0
    def update(self, one_state_change=False):
        if self.state["question"] >= len(QUIZ_CONTENT):
            print("Reached!")
            app = group(DIV(Class="m-3"), [
                H1(f"Correct: {self.state['correct']}"),
                H1(f"Wrong: {self.state['wrong']}"), reset := BUTTON(
                    "reset", Class="btn btn-danger")
            ])

            @bind(reset, "click")
示例#16
0
def append_to_chat_area(data, is_mine=False):
    chat_area = document['chat-area']
    time_as_str = str(datetime.datetime.now().time())
    separator = " | "
    if not is_mine:
        main_msg_css_class = 'text-left alert alert-primary'
        message = time_as_str + separator + data
    else:
        main_msg_css_class = 'text-right alert alert-dark'
        message = data + separator + time_as_str
    chat_area <= DIV(message, Class=main_msg_css_class)
    send_button.scrollIntoView()
示例#17
0
    def render(self):
        txt = TxtManager()
        todo = List()
        app = group(
            DIV(Class="container d-flex flex-column justify-content-center"),
            group(DIV(Class="container-sm m-3"), [
                DIV(style={"margin": "10px"}),
                txt.render(),
                H1("Todo List With Breact"),
                DIV(style={"margin": "10px"}),
                todo.render(),
                group(DIV(Class="row"), [
                    group(DIV(Class="col-sm form-group"), [
                        LABEL("Enter Title", to="inputt", Class="form-label"),
                        title := INPUT(
                            id="inputt", type="text", Class="form-control"),
                    ]),
                    description := group(DIV(Class="col-sm form-group"), [
                        LABEL("Enter Description",
                              to="inputts",
                              Class="form-label"),
                        TEXTAREA(
                            id="inputts", type="text", Class="form-control")
                    ]),
                ]), btn := BUTTON("Submit please",
                                  Class="btn btn-primary m-2"),
                DIV(style={"margin": "40px"})
            ]))

        @bind(title, "keyup")
        def updateTitle(e):
            txt.setState({"title": e.target.value})

        @bind(description, "keyup")
        def updateDesc(e):
            txt.setState({"description": e.target.value})

        @bind(btn, "click")
        def submit(e):
            submission = {
                "title": txt.state["title"],
                "description": txt.state["description"]
            }
            todo.state["items"].append(submission)
            todo.setState({"items": todo.state["items"]})

        return app


# document["root"] <= Main().render()
示例#18
0
def create_table(name):
    global ie_desc_array
    ie_desc_array = []
    #
    m = name_msg_map[name]
    document.title = f'{g.release}: {m.id} {m.name}'
    document['title'] <= document.title
    #
    button = BUTTON('show IE description')
    document['top'] <= button
    button.bind('click', toggle_ie_desc)
    #
    document['top'] <= SPAN(' ')
    document['top'] <= A('Index', href='')
    document['output'] <= PRE(m.id + ' ' + m.name + '\n' + m.definition,
                              Class='definition')
    table = TABLE(id='msgtable')
    document['output'] <= table
    for r, row in enumerate(m.aoa):
        tr = TR(Class=f'r{r}')
        table <= tr
        for c, v in enumerate(row):
            title = ''
            if r == 0 and c in (2, 3, 4, 5):
                title, v = v, ''
            elif c == 2:
                lst = v.replace('\n', ' ').split(' ')
                lst2 = [ie for ieid, ie in id_ie_map.items() if ieid in lst]
                if len(lst2) == 1:
                    ie = lst2[0]
                    title = f'{ie.id} {ie.name}\n{ie.definition}'
                    v = A(f'{ie.id}', href=f'#ie{ie.id}')
                ie_desc_array.append(title)
            elif r != 0 and c == 6:
                if v:
                    v = DIV(v) + DIV('', Class='iedescdiv', needsep='y')
                else:
                    v = DIV('', Class='iedescdiv', needsep='n')
            tr <= TD(v, title=title, Class=f'c{c}')
示例#19
0
def handle_msg_cfg_process_mgr_details(msg):
    global code_blks

    print("Setting process mgr")
    print(msg)
    process_mgr_name = msg['name']
    doc["procmgrdropbox"].text = process_mgr_name

    # Clear out the old contents from process_container:
    ctn = doc['ctn_process']
    code_blks = {}
    ctn.clear()

    for process in msg['processes']:
        process_name = process['name']
        process_id = process['id']

        heading = DIV("[%s] %s (%d)" %
                      (process_mgr_name, process_name, process_id),
                      Class="panel-heading")
        contents = ""  #H2(process_name)
        new_div = DIV(heading + DIV(contents, Class="panel-body"),
                      Class="panel panel-default")
        ctn <= new_div

        for output_pipe in process['outpipes'].values():
            print("output_pipe", output_pipe)
            nCode = CODE("XX", id="jlk")
            container = DIV(DIV(nCode,
                                style={
                                    'overflow': 'scroll',
                                    'height': '150px'
                                }),
                            Class='container')
            new_div <= H3(output_pipe, )
            new_div <= container
            code_blks[(process_id, output_pipe)] = nCode
示例#20
0
def _create_input(
    name,
    type,
    label='',
    Class='',
    text='',
    value='',
    required=False,
):
    """
    Cria um input completo.

    Baseados nas implementações do CSS, insere uma div `form-group`
    um input e um label

    Args:
    ----
        name: id do input
        type: tipo do input
        label: texto do label
        Class: classe CSS
        text: texto do componente
        value: valur do componente
        required: input validator required

    Retorna uma div do grupo com o elemto inserido na div.

    Example:
    -------
    >>> _create_input('nome', 'text', 'Seu nome')

    <div class="form-group">
        <label for="nome"> Seu nome </label>
        <input id="nome", type="text">
    </div>

    """
    d = DIV(Class='form-group')
    d <= LABEL(f'{label}: ' if label else '', For=name, id=f'l{name}')
    d <= INPUT(
        text,
        id=name,
        name=name,
        type=type,
        Class=Class,
        value=value,
        required=required,
    )
    return d
示例#21
0
    def update(self, one_state_change=False):
        def func(item):
            return ListItemWidget(item["title"], item["description"]).render()

        return group(
            DIV(
                Class="bg-primary",
                style={
                    "height": "400px",
                    "overflowY": "scroll",
                    "margin-bottom": "50px",
                    # "background-color": "#AABBFF",
                    "border-radius": "5px"
                }),
            [func(item) for item in self.state["items"]])
示例#22
0
文件: dashboard.py 项目: Enforcer/PAW
                def addColours(task, task_div):
                    colour_container = DIV()
                    colour_container.class_name = 'colour_container'
                    task_div.append(colour_container)

                    colours = task.get('colours', [])
                    for colour_nr in colours:
                        colour_div = DIV()
                        colour_div.class_name = 'label-colour' + colour_nr
                        colour_container.append(colour_div)
示例#23
0
def showartis(ev):
    if 'vertical-menu' in doc:
        del doc['vertical-menu']
    doc.unbind('mouseclick', custom_menu)

    ev.stopPropagation()
    # Set up artifact select
    arti = DIV(Id='vertical-menu', Class='vertical-menu')
    for art in artifacts:
        temp = DIV(strings[art],
                   Id=art,
                   data_id=ev.target.attrs["data-id"],
                   Class='vertical-menu menu-item')
        temp.bind('click', custom_menu)
        arti <= temp
    arti.top = ev.y
    arti.left = ev.x
    doc <= arti
    doc.bind('click', custom_menu)
示例#24
0
文件: dashboard.py 项目: Enforcer/PAW
    def on_complete(response):
        data = loads(response.text)

        container = DIV()
        container <= H2('Organizacje')
        form = FORM(method='POST', action='#')
        #input0 = INPUT(name='id', type='hidden', value=task_details['id'], id='id_field')
        #form <= input0

        row1 = DIV()
        row1.class_name = 'row'
        cell11 = DIV()
        cell11.class_name = 'large-12 columns'
        label11 = LABEL('Nazwa')
        input11 = INPUT(placeholder='Nazwa organizacji', type='text', value='', name='name', id='org_name_field')
        label11 <= input11
        cell11 <= label11
        row1 <= cell11

        row2 = DIV()
        row2.class_name = 'row'
        cell2 = DIV()
        cell2.class_name = 'large-12 columns'
        label2 = LABEL('Tablice')
        input2 = SELECT(name='boards', id='org_boards', multiple=True)
        for board in data['boards']:
            input2 <= OPTION(board[0], value=getApiLink('boards', board[1]))
        label2 <= input2
        cell2 <= label2
        row2 <= cell2

        row3 = DIV()
        row3.class_name = 'row'
        cell3 = DIV()
        cell3.class_name = 'large-12 columns'
        label3 = LABEL('Użytkownicy')
        input3 = SELECT(name='users', id='org_users', multiple=True)
        for user in data['users']:
            input3 <= OPTION(user[0], value=getApiLink('users', user[1]))
        label3 <= input3
        cell3 <= label3
        row3 <= cell3

        row4 = DIV()
        row4.class_name = 'row'
        cell4 = DIV()
        cell4.class_name = 'large-12 columns'
        submit_btn = A('Zapisz', type='submit', href='#')
        submit_btn.class_name = 'button tiny'
        cell4 <= submit_btn
        row4 <= cell4

        form <= row1
        form <= row2
        form <= row3
        form <= row4
        container <= form

        def on_submit(event):
            event.preventDefault()
            name = document['org_name_field'].value
            boards = [o.value for o in input2 if hasattr(o, 'selected') and o.selected]
            users = [o.value for o in input3 if hasattr(o, 'selected') and o.selected]
            owner = getApiLink('users', document['body'].__getattribute__('data-userid'))
            if name and boards and users:
                data = {
                    'name': name,
                    'boards': boards,
                    'users': users,
                    'owner': owner
                }
                def on_complete(response):
                    if response.status == 201:
                        hide_modal()
                    else:
                        alert(response.text)

                req2 = ajax.ajax()
                req2.bind('complete', on_complete)
                req2.open('POST', '/api/organizations/?format=json', True)
                req2.set_header('content-type', 'application/x-www-form-urlencoded')
                req2.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
                req2.send(data)

        submit_btn.bind('click', on_submit)

        show_modal(container)
示例#25
0
def init_characters():
	t = TABLE(Class='body')
	t <= COLGROUP(
		COL() +
		COL() +
		COL(Class='left_border') +
		COL(Class='left_dotted') +
		COL(Class='left_border') +
		COL(Class='left_dotted') +
		COL(Class='left_border') +
		COL(Class='left_dotted') +
		COL(Class='left_border') +
		COL(Class='left_dotted') +
		COL(Class='left_border') +
		COL(Class='left_dotted') +
		COL(Class='left_dotted') +
		COL(Class='left_border') +
		COL(Class='left_dotted') +
		COL(Class='left_dotted')
	)
	t <= TR(
		TH(strings["character"], colspan=2) +
		TH(strings["level"], colspan=2) +
		TH(strings["normal"], colspan=2) +
		TH(strings["skill"], colspan=2) +
		TH(strings["burst"], colspan=2) +
		TH(strings["weapon"], colspan=3) +
		TH(strings["artifacts"], colspan=3)
	)
	t <= TR(
		TH() +
		TH(strings["name"]) +
		TH(strings["now"]) +
		TH(strings["goal"]) +
		TH(strings["now"]) +
		TH(strings["goal"]) +
		TH(strings["now"]) +
		TH(strings["goal"]) +
		TH(strings["now"]) +
		TH(strings["goal"]) +
		TH() +
		TH(strings["now"]) +
		TH(strings["goal"]) +
		TH(strings["click_to_remove"], colspan=3)
	)
	for char in sorted(characters):
		if char == 'traveler':
			continue
		# set up level select
		lvlc = SELECT(Id=f"level_c-{char}", Class=f"{char} save")
		lvlt = SELECT(Id=f"level_t-{char}", Class=f"{char} save")
		for lvl in [lvlc, lvlt]:
			for c, val in [(0, "1"),
						   (1, "20"), (11, "20 A"),
						   (2, "40"), (12, "40 A"),
						   (3, "50"), (13, "50 A"),
						   (4, "60"), (14, "60 A"),
						   (5, "70"), (15, "70 A"),
						   (6, "80"), (16, "80 A"),
						   (7, "90")]:
				lvl <= OPTION(f"{val}", value=c)
		# Set up talent select
		t1c = SELECT(Id=f"talent_1_c-{char}", Class=f"{char} save")
		t1t = SELECT(Id=f"talent_1_t-{char}", Class=f"{char} save")
		t2c = SELECT(Id=f"talent_2_c-{char}", Class=f"{char} save")
		t2t = SELECT(Id=f"talent_2_t-{char}", Class=f"{char} save")
		t3c = SELECT(Id=f"talent_3_c-{char}", Class=f"{char} save")
		t3t = SELECT(Id=f"talent_3_t-{char}", Class=f"{char} save")
		for st in [t1t, t1c, t2t, t2c, t3t, t3c]:
			for cost in costs['talent']:
				st <= OPTION(cost)
		# Set up weapon select
		ws = SELECT(Id=f"weapon-{char}", data_id=f"select-{char}", Class=f'weapon {char} save')
		ws <= OPTION('--', value='--')
		sort_dict_wep = {}
		for item in weapons[characters[char]['weapon']]:
			if weapons[characters[char]['weapon']][item]['wam'] != 'unk':
				sort_dict_wep[strings[item]] = item
			else:
				if f"missing-{item}" not in doc:
					doc['missing'] <= LI(strings[item], Id=f"missing-{item}")

		for k in sorted(sort_dict_wep):
			ws <= OPTION(k, value=sort_dict_wep[k])
		wlvlc = SELECT(Id=f"weapon_c-{char}", Class=f"{char} save")
		wlvlt = SELECT(Id=f"weapon_t-{char}", Class=f"{char} save")
		for lvl in [wlvlc, wlvlt]:
			for c, val in [(0, "1"),
						   (1, "20"), (11, "20 A"),
						   (2, "40"), (12, "40 A"),
						   (3, "50"), (13, "50 A"),
						   (4, "60"), (14, "60 A"),
						   (5, "70"), (15, "70 A"),
						   (6, "80"), (16, "80 A"),
						   (7, "90")]:
				lvl <= OPTION(f"{val}", value=c)
		# Create table row for character
		t <= TR(
			TD(INPUT(Id=f"check-{char}", type='checkbox', data_id=f"check-{char}", Class='char_select save')) +
			TD(IMG(src=f"img/{char}.png", alt=strings[char], title=strings[char], loading="lazy")) +
			TD(lvlc) +
			TD(lvlt) +
			TD(t1c) +
			TD(t1t) +
			TD(t2c) +
			TD(t2t) +
			TD(t3c) +
			TD(t3t) +
			TD(ws) +
			TD(wlvlc) +
			TD(wlvlt) +
			TD(INPUT(Id=f"use_arti-{char}", type='checkbox', Class='save', checked='checked')) +
			TD(BUTTON(strings["add"], Class='arti_list text_button', data_id=f"arti-{char}")) +
			TD(DIV(Id=f"arti-{char}", Class=f'arti_span'))
			,
			data_id=f"check-{char}", Class='unchecked', data_color=characters[char]['element'], data_weapon=characters[char]['weapon']
		)
	# set up traveler base row
	# set up level select
	char = 'traveler'
	lvlc = SELECT(Id=f"level_c-{char}", Class=f"{char} save")
	lvlt = SELECT(Id=f"level_t-{char}", Class=f"{char} save")
	for lvl in [lvlc, lvlt]:
		for c, val in [(0, "1"),
					   (1, "20"), (11, "20 A"),
					   (2, "40"), (12, "40 A"),
					   (3, "50"), (13, "50 A"),
					   (4, "60"), (14, "60 A"),
					   (5, "70"), (15, "70 A"),
					   (6, "80"), (16, "80 A"),
					   (7, "90")]:
			lvl <= OPTION(f"{val}", value=c)
	# Set up weapon select
	ws = SELECT(Id=f"weapon-{char}", data_id=f"select-{char}", Class=f'weapon {char} save')
	ws <= OPTION('--', value='--')
	sort_dict_wep = {}
	for item in weapons[characters[char]['weapon']]:
		if weapons[characters[char]['weapon']][item]['wam'] != 'unk':
			sort_dict_wep[strings[item]] = item
		else:
			if f"missing-{item}" not in doc:
				doc['missing'] <= LI(strings[item], Id=f"missing-{item}")

	for k in sorted(sort_dict_wep):
		ws <= OPTION(k, value=sort_dict_wep[k])
	wlvlc = SELECT(Id=f"weapon_c-{char}", Class=f"{char} save")
	wlvlt = SELECT(Id=f"weapon_t-{char}", Class=f"{char} save")
	for lvl in [wlvlc, wlvlt]:
		for c, val in [(0, "1"),
					   (1, "20"), (11, "20 A"),
					   (2, "40"), (12, "40 A"),
					   (3, "50"), (13, "50 A"),
					   (4, "60"), (14, "60 A"),
					   (5, "70"), (15, "70 A"),
					   (6, "80"), (16, "80 A"),
					   (7, "90")]:
			lvl <= OPTION(f"{val}", value=c)
	# Create table row for character
	t <= TR(
		TD(INPUT(Id=f"check-{char}", type='checkbox', data_id=f"check-{char}", Class='char_select save')) +
		TD(IMG(src=f"img/{char}.png", alt=strings[char], title=strings[char], loading="lazy")) +
		TD(lvlc) +
		TD(lvlt) +
		TD() +
		TD() +
		TD() +
		TD() +
		TD() +
		TD() +
		TD(ws) +
		TD(wlvlc) +
		TD(wlvlt) +
		TD(INPUT(Id=f"use_arti-{char}", type='checkbox', Class='save', checked='checked')) +
		TD(BUTTON(strings["add"], Class='arti_list text_button', data_id=f"arti-{char}")) +
		TD(DIV(Id=f"arti-{char}", Class=f'arti_span'))
		,
		data_id=f"check-{char}", Class='unchecked', data_color='multi', data_weapon=characters[char]['weapon']
	)
	# set up traveler anemo/geo row
	for char in sorted(traveler_talent):
		ele = char.split('_')[1]
		# Set up talent select
		t1c = SELECT(Id=f"talent_1_c-{char}", Class=f"{char} save")
		t1t = SELECT(Id=f"talent_1_t-{char}", Class=f"{char} save")
		t2c = SELECT(Id=f"talent_2_c-{char}", Class=f"{char} save")
		t2t = SELECT(Id=f"talent_2_t-{char}", Class=f"{char} save")
		t3c = SELECT(Id=f"talent_3_c-{char}", Class=f"{char} save")
		t3t = SELECT(Id=f"talent_3_t-{char}", Class=f"{char} save")
		for st in [t1t, t1c, t2t, t2c, t3t, t3c]:
			for cost in costs['talent']:
				st <= OPTION(cost)
		# Create table row for character
		t <= TR(
			TD(INPUT(Id=f"check-{char}", type='checkbox', data_id=f"check-{char}", Class='char_select save')) +
			TD(IMG(src=f"img/{char}.png", alt=strings['traveler'], title=strings['traveler'], loading="lazy")) +
			TD() +
			TD() +
			TD(t1c) +
			TD(t1t) +
			TD(t2c) +
			TD(t2t) +
			TD(t3c) +
			TD(t3t) +
			TD() +
			TD() +
			TD() +
			TD() +
			TD() +
			TD()
			,
			data_id=f"check-{char}", Class='unchecked', data_color=ele, data_weapon=characters['traveler']['weapon']
		)
	doc['character_list'] <= t
示例#26
0
    agente_jogador.adquirirPercepcao(gerarCampoVisao(jogo.tabuleiro))
    acao = agente_jogador.escolherProximaAcao()

    if acao is not None:
        jogo.registrarProximaAcao(acao[0], acao[1])

        jogo.validarEstado()
        jogo.atualizarEstado()
    else:
        alert("fim")
        caf(id)


def animate(i):

    global id
    id = raf(animate)
    jogador_agente()
    document['tabelajogo'] <= gerarCampoVisao(jogo.tabuleiro)


jogo = construir_jogo()
#linha toast
document <= DIV('', Class='desenv', id='desenv')
#linha jogo
agente_jogador = agente()

document['tabelajogo'] <= gerarCampoVisao(jogo.tabuleiro)

document['btn-animate'].bind('click', animate)
示例#27
0
文件: gui.py 项目: boribs/chessengine
    def animated_move(timestamp, x_dir, y_dir, step, max_step, castle_dir):
        moving_piece.left += int(x_dir)
        moving_piece.top += int(y_dir)

        if step < max_step:
            timer.request_animation_frame(lambda timestamp: animated_move(
                timestamp, x_dir, y_dir, step + 1, max_step, castle_dir))
        else:
            if castle_dir != 0:
                destiny.innerHTML = ''

                put_piece_in_square(str(int(origin_id + 2 * castle_dir)),
                                    'king', team_str)
                put_piece_in_square(str(int(origin_id) + castle_dir), 'rook',
                                    team_str)

                t_value = 0 if team_str == 'WHITE' else 1

                C.has_king_moved[t_value] = True
                C.has_rook_moved[t_value][int(not dx == 0)] = True
            else:
                global can_move, turn
                destiny.innerHTML = moving_piece_img

                if promotion == True and turn == PieceTeam.WHITE:  # Display menu for options
                    can_move = False
                    selection_box = DIV(id='piece-select')

                    for name in (PieceName.QUEEN, PieceName.ROOK,
                                 PieceName.BISHOP, PieceName.KNIGHT):
                        container = DIV(
                            Class="container",
                            onclick=
                            f'promote_pawn({dx}, {dy}, "{name}", "{team_str}");'
                        )
                        container <= IMG(
                            src=
                            f'static/pieces/{team_str.lower()}_{name.name.lower()}.png'
                        )

                        selection_box <= container

                    offset_x = (moving_piece.clientWidth // 2) - (52 * 2)
                    offset_y = -50 if team_str == 'WHITE' else moving_piece.clientWidth

                    selection_box.style.left = str(moving_piece.left +
                                                   offset_x) + 'px'
                    selection_box.style.top = str(moving_piece.top +
                                                  offset_y) + 'px'
                    document <= selection_box

                elif promotion == True and turn == PieceTeam.BLACK:
                    piece = choice(['ROOK', 'BISHOP', 'KNIGHT'])
                    C.replace_piece(dx, dy, eval('PieceName.' + piece),
                                    turn.name)
                    put_piece_in_square(destiny_id, piece, turn.name)

            piece_columns = {
                PieceTeam.WHITE: document['rpieces'],
                PieceTeam.BLACK: document['lpieces'],
            }

            if destiny_name != None and castle_dir == 0:
                piece_columns[destiny_team] <= IMG(
                    src=
                    f'static/pieces/{destiny_team.name.lower()}_{destiny_name.name.lower()}.png'
                )

            if not promotion:
                turn = PieceTeam.BLACK if turn == PieceTeam.WHITE else PieceTeam.WHITE

            can_move = turn == PieceTeam.WHITE and not promotion
            del document['moving-piece']
            display_message()
示例#28
0
			t_row <= t_td
			if not (c % width):
				if lookup[c]:
					t_row <= TD(colspan=lookup[c], Class='notvis')
				t_own <= t_row
				t_row = TR(Class='tr_odd' if row % 2 else 'tr_even')
				row += 1
				c = 0
			elif c % width < width:
				t_row <= TD()

	if c % width:
		if lookup[c]:
			t_row <= TD(colspan=lookup[c], Class='notvis')
		t_own <= t_row

	doc['inventory'] <= t_own

	b_reset = BUTTON(strings["reset_all_data"], Id='reset_all')
	doc["reset"] <= b_reset

	b_reset = BUTTON(strings["reset_character"], Id='reset_character')
	doc["reset"] <= b_reset

	b_reset = BUTTON(strings["reset_inventory"], Id='reset_inventory')
	doc["reset"] <= b_reset


init_page()
doc['loading'] <= DIV(Id='prerendered')
示例#29
0
 def correctWrong():
     if "prev" in self.state:
         if self.state["prev"] == True:
             return H3("Your answer is correct", Class="text-success")
         return H3("Your answer was wrong", Class="text-danger")
     return DIV()
示例#30
0
文件: dashboard.py 项目: Enforcer/PAW
                            def usersLoaded(req):
                                users = loads(req.text)

                                container = DIV()
                                container <= H2('Edycja zadania')
                                form = FORM(method='PATCH', action='#')
                                input0 = INPUT(name='id', type='hidden', value=task_details['id'], id='id_field')
                                form <= input0

                                row1 = DIV()
                                row1.class_name = 'row'
                                cell11 = DIV()
                                cell11.class_name = 'large-6 columns'
                                label11 = LABEL('Nazwa')
                                input11 = INPUT(placeholder='Nazwa zadania', type='text', value=task_details['name'], name='name', id='name_field')
                                label11 <= input11
                                cell11 <= label11
                                error_panel1 = DIV(id='name_error')
                                error_panel1.class_name = 'panel error'
                                cell11 <= error_panel1
                                row1 <= cell11

                                row2 = DIV()
                                row2.class_name = 'row'
                                cell2 = DIV()
                                cell2.class_name = 'large-6 columns'
                                label2 = LABEL('Opis')
                                input2 = INPUT(placeholder='Opis zadania', name='description', id='description_field', type='text')
                                input2.value = task_details['description']
                                label2 <= input2
                                cell2 <= label2
                                row2 <= cell2

                                cell3 = DIV()
                                cell3.class_name = 'large-6 columns'
                                label3 = LABEL('Przypisane do')
                                input3 = SELECT(name='assignee', id='assignee_field')
                                input3 <= OPTION('---', value=None)
                                for user in users:
                                    input3 <= OPTION(user['username'], value=getApiLink('users', user['id']))
                                input3.value = task_details['assignee']
                                label3 <= input3
                                cell3 <= label3
                                row1 <= cell3

                                cell7 = DIV()
                                cell7.class_name = 'large-6 columns'
                                label7 = LABEL('Termin wykonania')
                                input7 = INPUT(name='deadline', id='deadline_field', placeholder='yyyy-mm-dd', type='text')
                                input7.value = task_details['deadline'] if task_details['deadline'] else ''
                                label7 <= input7
                                cell7 <= label7
                                error_panel7 = DIV(id='deadline_error')
                                error_panel7.class_name = 'panel error'
                                cell7 <= error_panel7
                                row2 <= cell7

                                row3 = DIV()
                                row3.class_name = 'row'
                                cell33 = DIV()
                                cell33.class_name = 'large-6 columns'
                                label33 = LABEL('Trudność')
                                input33 = SELECT(name='difficulty', id='difficulty_field')
                                input33 <= OPTION('---', value='None')
                                input33 <= OPTION('łatwe', value='easy')
                                input33 <= OPTION('średnie', value='intermediate')
                                input33 <= OPTION('trudne', value='hard')
                                if task_details['difficulty'] and task_details['difficulty'] in ('easy', 'intermediate', 'hard'):
                                    input33.value = task_details['difficulty']

                                label33 <= input33
                                cell33 <= label33

                                cell34 = DIV()
                                cell34.class_name = 'large-6 columns'
                                label34 = LABEL('')
                                label34 <= BR()
                                input34 = BUTTON('Archiwizuj', id='archive_task', data_task_id=task_details['id'])
                                input34.class_name = 'button tiny'
                                label34 <= input34
                                cell34 <= label34
                                row3 <= cell33
                                row3 <= cell34

                                input34.bind('click', archiveTask)

                                row6 = DIV()
                                row6.class_name = 'row'
                                cell6 = DIV()
                                cell6.class_name = 'large-12 columns'
                                cell6.id = 'comments-container'
                                cell6 <= H4('Komentarze')
                                def appendCommentToDom(author, when, content):
                                    length = len(cell6.get(selector='.comment'))
                                    colour = '' if length % 2 == 0 else ' callout'
                                    #colour = ''
                                    panel = DIV()
                                    panel.class_name = 'panel comment' + colour
                                    panel <= B('{0} dnia {1}'.format(author, when))
                                    panel <= P(content)
                                    cell6 <= panel

                                if len(task_details['comments']) == 0:
                                    panel = DIV()
                                    panel.class_name = 'panel'
                                    panel <= P('No comments')
                                    cell6 <= panel
                                else:
                                    i = 0
                                    for comment in task_details['comments']:
                                        author = [user['username'] for user in users if getApiLink('users', user['id']) == comment['author']].pop()
                                        when = comment['created_at']
                                        content = comment['content']
                                        appendCommentToDom(author, when, content)
                                row6 <= cell6

                                row5 = DIV()
                                row5.class_name = 'row'
                                cell5 = DIV()
                                cell5.class_name = 'large-12 columns'
                                label5 = LABEL('Skomentuj')
                                input5 = TEXTAREA(placeholder='Treść komentarza', name='comment', id='comment_field')
                                label5 <= input5
                                cell5 <= label5
                                comment_btn = A('Dodaj komentarz', href='#')
                                comment_btn.class_name = 'button tiny'
                                cell5 <= comment_btn
                                row5 <= cell5

                                def addComment(event):
                                    event.preventDefault()
                                    content = document['comment_field'].value
                                    author = document['body'].__getattribute__('data-username')
                                    author_id = document['body'].__getattribute__('data-userid')
                                    when = window.Date()
                                    if content:
                                        appendCommentToDom(author, when, content)
                                        data = {
                                            'author': getApiLink('users', author_id),
                                            'content': content,
                                            'task': getApiLink('tasks', task_details['id'])
                                        }
                                        a2 = ajax.ajax()
                                        a2.open('POST', '/api/comments2/?format=json')
                                        a2.set_header('content-type', 'application/x-www-form-urlencoded')
                                        a2.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
                                        a2.send(data)
                                        document['comment_field'].value = ''


                                comment_btn.bind('click', addComment)

                                row4 = DIV()
                                row4.class_name = 'row'
                                cell4 = DIV()
                                cell4.class_name = 'large-12 columns'
                                submit_btn = A('Zapisz zmiany', type='submit', href='#')
                                submit_btn.class_name = 'button tiny'
                                cell4 <= submit_btn
                                row4 <= cell4

                                form <= row1
                                form <= row2
                                form <= row3
                                form <= row4

                                form <= row6
                                form <= row5

                                container <= form

                                for i in range(1, 6):
                                    colour_name = 'colour{0}'.format(i)
                                    if str(i) in task_details['colours']:
                                        document[colour_name].class_name = 'colour-btn checked'
                                    else:
                                        document[colour_name].class_name = 'colour-btn'

                                #/api/tasks/
                                def on_submit(event):
                                    assignee = None if document['assignee_field'].value == 'None' \
                                        else document['assignee_field'].value
                                    deadline = '' if document['deadline_field'].value == '' \
                                        else document['deadline_field'].value + 'T01:01'
                                    difficulty = None if document['difficulty_field'].value == '---' \
                                        or document['difficulty_field'].value not in ('easy', 'intermediate', 'hard') \
                                        else document['difficulty_field'].value

                                    colours = []
                                    for checked_colour in document.get(selector='a.colour-btn.checked'):
                                        colours.append(checked_colour.id[-1])

                                    data = {
                                        'id': document['id_field'].value,
                                        'name': document['name_field'].value,
                                        'description': document['description_field'].value,
                                        'assignee': assignee,
                                        'deadline': deadline,
                                        'difficulty': difficulty,
                                        'colours': ','.join(colours)
                                    }

                                    def taskUpdated(req):
                                        data = loads(req.text)
                                        if 'id' in data: # zapisalo sie poprawnie
                                            document['task_' + str(data['id'])].clear()
                                            data['colours'] = data['colours'].split(',') if data['colours'] else []
                                            addColours(data, document['task_' + str(data['id'])])
                                            document['task_' + str(data['id'])] <= H3(data['name'], **{'data-task-id': data['id']})
                                            hide_modal()
                                        else:
                                            for field, errors in data.items():
                                                error_field_name = field + '_error'
                                                for error in errors:
                                                    document[error_field_name] <= error

                                    for error_field in document.get(selector='.panel.error'):
                                        error_field.clear()

                                    a = ajax.ajax()
                                    a.open('PATCH', '/api/tasks/' + str(data['id']) + '/?format=json')
                                    a.bind('complete', taskUpdated)
                                    a.set_header('content-type', 'application/x-www-form-urlencoded')
                                    a.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
                                    a.send(data)
                                    return False

                                submit_btn.bind('click', on_submit)

                                show_modal(container)
示例#31
0
文件: dashboard.py 项目: Enforcer/PAW
    def on_complete(req):
        response = loads(req.text)
        if response['success']:
            for l in response['lists']:
                column = DIV()
                column.class_name = 'large-3 columns listsColumns'
                tasks_container = DIV(id='tasks_for_list_' + str(l['id']), data_list_id=l['id'])
                tasks_container.class_name = 'tasksContainer'
                column <= tasks_container
                header = H4(l['name'])
                archive_icon = SPAN()
                archive_icon.class_name = 'fi-trash size-24 archive_list_icon'
                archive_icon.bind('click', archiveList)
                header <= archive_icon
                tasks_container <= header
                new_task_input_params = {'placeholder': 'Nowe zadanie', 'class': 'newTaskInput', 'type': 'text', 'data-lists-id': l['id']}
                new_task_input = INPUT(**new_task_input_params)
                tasks_container <= new_task_input

                def drag_over(ev):
                    ev.dataTransfer.dropEffect = 'move'
                    ev.preventDefault()

                def on_drop(ev):
                    ev.preventDefault()
                    task_element_id = ev.dataTransfer.getData('text')
                    element = document[task_element_id]
                    task_id = task_element_id.split('_')[-1]

                    target = ev.target
                    if not hasattr(ev.target, 'class_name') or ev.target.class_name != 'tasksContainer':
                        if ev.target.class_name == 'taskDiv' or ev.target.class_name == 'newTaskInput':
                            target = ev.target.parent
                        elif ev.target.class_name == 'task_name_header':
                            target = ev.target.parent.parent
                        elif ev.target.class_name == 'newTaskInput':
                            target = ev.target.parent
                        else:
                            return

                    dragee_pos = ev.clientY

                    positions_elements = {dragee_pos: element}
                    new_elements_positions = [dragee_pos]
                    
                    for el in target.get(selector='.taskDiv'):
                        pos = el.top if el.top != dragee_pos else el.top - 1
                        positions_elements[pos] = el
                        new_elements_positions.append(pos)

                    new_elements_positions.sort()

                    tasks_positions = {}
                    for i, pos in enumerate(new_elements_positions, 1):
                        el = positions_elements[pos]
                        target <= el
                        tasks_positions[el.__getattribute__('data-task-id')] = i

                    def set_new_positions(ev):
                        a = ajax.ajax()
                        a.open('POST', '/update_tasks_positions', True)
                        a.set_header('content-type', 'application/x-www-form-urlencoded')
                        a.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
                        a.send({'updates': dumps(tasks_positions)})

                    a = ajax.ajax()
                    a.open('PATCH', getApiLink('tasks', task_id) + '?format=json')
                    a.bind('complete', set_new_positions)
                    a.set_header('content-type', 'application/x-www-form-urlencoded')
                    a.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
                    a.send({'id': task_id, 'board_list': getApiLink('boardlists', target.data_list_id)})
                    
                tasks_container.bind('dragover', drag_over)
                tasks_container.bind('drop', on_drop)

                def addColours(task, task_div):
                    colour_container = DIV()
                    colour_container.class_name = 'colour_container'
                    task_div.append(colour_container)

                    colours = task.get('colours', [])
                    for colour_nr in colours:
                        colour_div = DIV()
                        colour_div.class_name = 'label-colour' + colour_nr
                        colour_container.append(colour_div)


                def appendTask(task, container):
                    task_div_params = {'class': 'taskDiv', 'data-task-id': task['id'], 'id': 'task_' + str(task['id']), 'draggable': True}
                    task_div = DIV(**task_div_params)
                    task_name = H3(task['name'], **{'data-task-id': task['id']})
                    task_name.class_name = 'task_name_header'

                    addColours(task, task_div)

                    task_div <= task_name
                    container <= task_div

                    def drag_start(ev):
                        ev.dataTransfer.setData('text', ev.target.id)
                        ev.dataTransfer.effectAllowed = 'move'
                    task_div.bind('dragstart', drag_start)

                    def taskDetails(event):
                        #Uwaga na niedziedziczone atrybuty przy dziedziczonych eventach!
                        task_id = event.target.__getattribute__('data-task-id')

                        def taskDetailsLoaded(req):
                            task_details = loads(req.text)

                            def usersLoaded(req):
                                users = loads(req.text)

                                container = DIV()
                                container <= H2('Edycja zadania')
                                form = FORM(method='PATCH', action='#')
                                input0 = INPUT(name='id', type='hidden', value=task_details['id'], id='id_field')
                                form <= input0

                                row1 = DIV()
                                row1.class_name = 'row'
                                cell11 = DIV()
                                cell11.class_name = 'large-6 columns'
                                label11 = LABEL('Nazwa')
                                input11 = INPUT(placeholder='Nazwa zadania', type='text', value=task_details['name'], name='name', id='name_field')
                                label11 <= input11
                                cell11 <= label11
                                error_panel1 = DIV(id='name_error')
                                error_panel1.class_name = 'panel error'
                                cell11 <= error_panel1
                                row1 <= cell11

                                row2 = DIV()
                                row2.class_name = 'row'
                                cell2 = DIV()
                                cell2.class_name = 'large-6 columns'
                                label2 = LABEL('Opis')
                                input2 = INPUT(placeholder='Opis zadania', name='description', id='description_field', type='text')
                                input2.value = task_details['description']
                                label2 <= input2
                                cell2 <= label2
                                row2 <= cell2

                                cell3 = DIV()
                                cell3.class_name = 'large-6 columns'
                                label3 = LABEL('Przypisane do')
                                input3 = SELECT(name='assignee', id='assignee_field')
                                input3 <= OPTION('---', value=None)
                                for user in users:
                                    input3 <= OPTION(user['username'], value=getApiLink('users', user['id']))
                                input3.value = task_details['assignee']
                                label3 <= input3
                                cell3 <= label3
                                row1 <= cell3

                                cell7 = DIV()
                                cell7.class_name = 'large-6 columns'
                                label7 = LABEL('Termin wykonania')
                                input7 = INPUT(name='deadline', id='deadline_field', placeholder='yyyy-mm-dd', type='text')
                                input7.value = task_details['deadline'] if task_details['deadline'] else ''
                                label7 <= input7
                                cell7 <= label7
                                error_panel7 = DIV(id='deadline_error')
                                error_panel7.class_name = 'panel error'
                                cell7 <= error_panel7
                                row2 <= cell7

                                row3 = DIV()
                                row3.class_name = 'row'
                                cell33 = DIV()
                                cell33.class_name = 'large-6 columns'
                                label33 = LABEL('Trudność')
                                input33 = SELECT(name='difficulty', id='difficulty_field')
                                input33 <= OPTION('---', value='None')
                                input33 <= OPTION('łatwe', value='easy')
                                input33 <= OPTION('średnie', value='intermediate')
                                input33 <= OPTION('trudne', value='hard')
                                if task_details['difficulty'] and task_details['difficulty'] in ('easy', 'intermediate', 'hard'):
                                    input33.value = task_details['difficulty']

                                label33 <= input33
                                cell33 <= label33

                                cell34 = DIV()
                                cell34.class_name = 'large-6 columns'
                                label34 = LABEL('')
                                label34 <= BR()
                                input34 = BUTTON('Archiwizuj', id='archive_task', data_task_id=task_details['id'])
                                input34.class_name = 'button tiny'
                                label34 <= input34
                                cell34 <= label34
                                row3 <= cell33
                                row3 <= cell34

                                input34.bind('click', archiveTask)

                                row6 = DIV()
                                row6.class_name = 'row'
                                cell6 = DIV()
                                cell6.class_name = 'large-12 columns'
                                cell6.id = 'comments-container'
                                cell6 <= H4('Komentarze')
                                def appendCommentToDom(author, when, content):
                                    length = len(cell6.get(selector='.comment'))
                                    colour = '' if length % 2 == 0 else ' callout'
                                    #colour = ''
                                    panel = DIV()
                                    panel.class_name = 'panel comment' + colour
                                    panel <= B('{0} dnia {1}'.format(author, when))
                                    panel <= P(content)
                                    cell6 <= panel

                                if len(task_details['comments']) == 0:
                                    panel = DIV()
                                    panel.class_name = 'panel'
                                    panel <= P('No comments')
                                    cell6 <= panel
                                else:
                                    i = 0
                                    for comment in task_details['comments']:
                                        author = [user['username'] for user in users if getApiLink('users', user['id']) == comment['author']].pop()
                                        when = comment['created_at']
                                        content = comment['content']
                                        appendCommentToDom(author, when, content)
                                row6 <= cell6

                                row5 = DIV()
                                row5.class_name = 'row'
                                cell5 = DIV()
                                cell5.class_name = 'large-12 columns'
                                label5 = LABEL('Skomentuj')
                                input5 = TEXTAREA(placeholder='Treść komentarza', name='comment', id='comment_field')
                                label5 <= input5
                                cell5 <= label5
                                comment_btn = A('Dodaj komentarz', href='#')
                                comment_btn.class_name = 'button tiny'
                                cell5 <= comment_btn
                                row5 <= cell5

                                def addComment(event):
                                    event.preventDefault()
                                    content = document['comment_field'].value
                                    author = document['body'].__getattribute__('data-username')
                                    author_id = document['body'].__getattribute__('data-userid')
                                    when = window.Date()
                                    if content:
                                        appendCommentToDom(author, when, content)
                                        data = {
                                            'author': getApiLink('users', author_id),
                                            'content': content,
                                            'task': getApiLink('tasks', task_details['id'])
                                        }
                                        a2 = ajax.ajax()
                                        a2.open('POST', '/api/comments2/?format=json')
                                        a2.set_header('content-type', 'application/x-www-form-urlencoded')
                                        a2.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
                                        a2.send(data)
                                        document['comment_field'].value = ''


                                comment_btn.bind('click', addComment)

                                row4 = DIV()
                                row4.class_name = 'row'
                                cell4 = DIV()
                                cell4.class_name = 'large-12 columns'
                                submit_btn = A('Zapisz zmiany', type='submit', href='#')
                                submit_btn.class_name = 'button tiny'
                                cell4 <= submit_btn
                                row4 <= cell4

                                form <= row1
                                form <= row2
                                form <= row3
                                form <= row4

                                form <= row6
                                form <= row5

                                container <= form

                                for i in range(1, 6):
                                    colour_name = 'colour{0}'.format(i)
                                    if str(i) in task_details['colours']:
                                        document[colour_name].class_name = 'colour-btn checked'
                                    else:
                                        document[colour_name].class_name = 'colour-btn'

                                #/api/tasks/
                                def on_submit(event):
                                    assignee = None if document['assignee_field'].value == 'None' \
                                        else document['assignee_field'].value
                                    deadline = '' if document['deadline_field'].value == '' \
                                        else document['deadline_field'].value + 'T01:01'
                                    difficulty = None if document['difficulty_field'].value == '---' \
                                        or document['difficulty_field'].value not in ('easy', 'intermediate', 'hard') \
                                        else document['difficulty_field'].value

                                    colours = []
                                    for checked_colour in document.get(selector='a.colour-btn.checked'):
                                        colours.append(checked_colour.id[-1])

                                    data = {
                                        'id': document['id_field'].value,
                                        'name': document['name_field'].value,
                                        'description': document['description_field'].value,
                                        'assignee': assignee,
                                        'deadline': deadline,
                                        'difficulty': difficulty,
                                        'colours': ','.join(colours)
                                    }

                                    def taskUpdated(req):
                                        data = loads(req.text)
                                        if 'id' in data: # zapisalo sie poprawnie
                                            document['task_' + str(data['id'])].clear()
                                            data['colours'] = data['colours'].split(',') if data['colours'] else []
                                            addColours(data, document['task_' + str(data['id'])])
                                            document['task_' + str(data['id'])] <= H3(data['name'], **{'data-task-id': data['id']})
                                            hide_modal()
                                        else:
                                            for field, errors in data.items():
                                                error_field_name = field + '_error'
                                                for error in errors:
                                                    document[error_field_name] <= error

                                    for error_field in document.get(selector='.panel.error'):
                                        error_field.clear()

                                    a = ajax.ajax()
                                    a.open('PATCH', '/api/tasks/' + str(data['id']) + '/?format=json')
                                    a.bind('complete', taskUpdated)
                                    a.set_header('content-type', 'application/x-www-form-urlencoded')
                                    a.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
                                    a.send(data)
                                    return False

                                submit_btn.bind('click', on_submit)

                                show_modal(container)

                            req = ajax.ajax()
                            req.open('GET', '/api/users/?format=json', True)
                            req.bind('complete', usersLoaded)
                            req.send()
                            

                        req = ajax.ajax()
                        req.open('GET', '/api/tasks/' + task_id + '/?format=json', True)
                        req.bind('complete', taskDetailsLoaded)
                        req.send()

                    task_div.bind('click', taskDetails)

                l['tasks'].sort(key=itemgetter('order_in_list', 'id'))
                for task in l['tasks']:
                    appendTask(task, tasks_container)

                document['listContainer'] <= column

                def saveTask(event):
                    value = event.target.value
                    lists_id = event.target.__getattribute__('data-lists-id')
                    if value:
                        def task_add_callback(req):
                            if req.status == 201:
                                new_task = loads(req.text)
                                boards_id = new_task['board_list'].split('/')[-2]
                                container = document['tasks_for_list_' + str(boards_id)]
                                appendTask(new_task, container)
                                event.target.value = ''
                            else:
                                alert('Dodanie zadania nie powiodło się')

                        req = ajax.ajax()
                        req.bind('complete', task_add_callback)
                        req.open('POST', '/tasks/?format=json', True)
                        req.set_header('content-type', 'application/x-www-form-urlencoded')
                        req.set_header('X-CSRFToken', document.get(name='csrfmiddlewaretoken')[0].value)
                        req.send({'lists_id': lists_id, 'description': '', 'name': value, 'comments': None})

                new_task_input.bind('blur', saveTask)

            column = DIV()
            column.class_name = 'large-3 columns listsColumns'
            new_input = INPUT(id='newColumnInput', placeholder='Nowa lista', type='text')
            column <= new_input
            document['listContainer'] <= column
            new_input.bind('blur', saveNewList)

            #console.log(document.get(selector='.newTaskInput')[0].focus())

        else:
            alert('Pobranie list nie powiodło się')
示例#32
0
 def update(self, one_state_change=False):
     return DIV()
示例#33
0
            return app

        elementOn = QUIZ_CONTENT[self.state["question"]]
        options = elementOn['options']
        question = elementOn['question']
        ans = elementOn['answer']

        def correctWrong():
            if "prev" in self.state:
                if self.state["prev"] == True:
                    return H3("Your answer is correct", Class="text-success")
                return H3("Your answer was wrong", Class="text-danger")
            return DIV()

        app = group(DIV(Class="container", style={"minWidth": "60vw"}), [
            H1(question + ":"),
            correctWrong(),
            group(DIV(Class="container"), [
                group(DIV(Class="row"), [
                    option1 := BUTTON(options[0],
                                      Class="col-sm btn btn-danger m-2"),
                    option2 := BUTTON(options[1],
                                      Class="col-sm btn btn-info m-2"),
                ]),
                group(DIV(Class="row"), [
                    option3 := BUTTON(options[2],
                                      Class="col-sm btn btn-warning m-2"),
                    option4 := BUTTON(options[3],
                                      Class="col-sm btn btn-success m-2"),
                ])
示例#34
0
##########################################################################################################################################
from browser import document, window, load
from browser.html import TABLE, TR, TD, SPAN, DIV, A, B, H3, SELECT, OPTION, BR, HR, INPUT, TH, BUTTON
import ready

col_flag = 0
col_level = 1
col_ie = 2
col_desc = 6
dtop = document['top']
doutput = document['output']
document.body <= DIV(id='dindex')
dindex = document['dindex']


def load_json():
    stem = get_stem()
    json = f'{stem}.json'
    with open(json, encoding='utf-8') as f:
        s = f.read()
    o = window.JSON.parse(s)
    return o


def get_stem():
    return window.location.pathname.split('/')[-1].replace('.html', '')


def get_protocol_name():
    stem = get_stem()
    d = {
示例#35
0
def update_character():
    char_tracker = {}
    for val in grind_table_state['total']:
        grind_table_state['total'][val] = 0
    for char in grind_table_state['checked']:
        update_per_character(char, char_tracker)

    # Get a list of all chosen artifacts so we know what to farm
    for elt in doc.get(selector=f'.saved_arti'):
        char = elt.id.split('-')[1]
        if char in grind_table_state['checked'] and char in grind_table_state[
                'arti_check']:
            add_value_set(char_tracker,
                          elt.id.split('-')[-1],
                          elt.id.split('-')[1])

    # adjust xp totals to units of their base type.
    grind_table_state['total']['mora'] += grind_table_state['total'][
        'xp'] // 5 + grind_table_state['total']['wep_xp'] // 10
    grind_table_state['total']['xp'] = round(
        grind_table_state['total']['xp'] / 20000, 2)
    grind_table_state['total']['wep_xp'] = round(
        grind_table_state['total']['wep_xp'] / 10000, 2)

    # Build up and display farm table
    data = {
        'any': {
            0: {},
            20: {},
            40: {},
            60: {}
        },
        'mon': {},
        'tue': {},
        'wed': {},
        'thu': {},
        'fri': {},
        'sat': {},
        'sun': {},
    }
    resin = {
        'stormterror': 60,
        'wolf_of_the_north': 60,
        'golden_house': 60,
        'azhdaha': 60,
        '60_boss': 60,
        '40_boss': 40,
        'anemo_hypostasis': 40,
        'cryo_regisvine': 40,
        'cryo_hypostasis': 40,
        'electro_hypostasis': 40,
        'geo_hypostasis': 40,
        'oceanid': 40,
        'pyro_regisvine': 40,
        'primo_geovishap': 40,
        'maguu_kenki': 40,
        'pyro_hypostasis': 40,
        'perpetual_mechanical_array': 40,
        'clear_pool_and_mountain_cavern': 20,
        'domain_of_guyun': 20,
        'hidden_palace_of_zhou_formula': 20,
        'midsummer_courtyard': 20,
        'valley_of_remembrance': 20,
        'peak_of_vindagnyr': 20,
        'court_of_flowing_sand': 20,
        'violet_court': 20,
        'momiji_dyed_court': 20,
        'ridge_watch': 20,
        'xp_leyline': 20,
        'mora_leyline': 20
    }
    arti_keys = [('arti', x) for x in char_tracker if x not in ingame_order]
    for section, item in [('base', 'xp'), ('base', 'wep_xp'),
                          ('base', 'mora')] + ingame_order + arti_keys:
        if item in char_tracker:
            for day in farming_data[item]['when']:
                for loc in farming_data[item]['where']:
                    if day == 'any':
                        cost = 0 if loc not in resin else resin[loc]
                        if loc not in data[day][cost]:
                            data[day][cost][loc] = []
                        data[day][cost][loc].append(item)
                    else:
                        if loc not in data[day]:
                            data[day][loc] = []
                        data[day][loc].append(item)

    d = SECTION(Class='grind')
    for day in ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']:
        d <= H2([strings[day]])
        t = TABLE(TR(
            TH(strings["location"]) + TH(strings["item_s"]) +
            TH(strings["character_s"])),
                  Class='borders body')
        empty = True
        for loc in sorted(data[day]):
            char_set = set()
            item_set = {}
            for x in data[day][loc]:
                if isinstance(strings[x], str) and grind_table_state['total'][
                        x] - grind_table_state['user'][x] > 0:
                    char_set.update(char_tracker[x])
                    item_set[x] = {
                        'text':
                        strings[x],
                        'count':
                        readable_number(grind_table_state['total'][x] -
                                        grind_table_state['user'][x])
                    }
                else:
                    for i in range(len(strings[x])):
                        if grind_table_state['total'][
                                f"{x}_{i}"] - grind_table_state['user'][
                                    f"{x}_{i}"] > 0:
                            char_set.update(char_tracker[x])
                            item_set[f"{x}_{i}"] = {
                                'text':
                                strings[x][i],
                                'count':
                                readable_number(
                                    grind_table_state['total'][f"{x}_{i}"] -
                                    grind_table_state['user'][f"{x}_{i}"])
                            }
            if item_set:
                empty = False
                v = (DIV(IMG(src=f"img/{x}.png",
                             alt=item_set[x]['text'],
                             title=item_set[x]['text'],
                             loading="lazy") +
                         DIV(item_set[x]['count'], Class='bottom-right'),
                         Class='container') for x in item_set)
                c = (IMG(src=f"img/{x}.png",
                         alt=strings[x],
                         title=strings[x],
                         loading="lazy") for x in sorted(char_set))
                t <= TR(TD(strings[loc], Class="location") + TD(v) + TD(c))
        if empty:
            t <= TR(
                TD(strings['nothing'], Class="location") +
                TD(strings['nothing']) + TD(strings['nothing']))
        d <= t
    if any([data['any'][x] for x in [0, 20, 40, 60]]):
        d <= H2([strings['any']])
        for cost in [0, 20, 40, 60]:
            if data['any'][cost]:
                d <= H3(f"{cost} {strings['resin']}")
                t = TABLE(TR(
                    TH(strings["location"]) + TH(strings["item_s"]) +
                    TH(strings["character_s"])),
                          Class='borders body')
                for loc in sorted(data['any'][cost]):
                    char_set = set()
                    item_set = {}
                    for x in data['any'][cost][loc]:
                        if isinstance(strings[x], str):
                            if x in grind_table_state['total']:
                                if 'xp' == x:
                                    val = int(grind_table_state['total'][x] -
                                              grind_table_state['user'][x] -
                                              grind_table_state['user']
                                              [f"{x}_sub_1"] / 4 -
                                              grind_table_state['user']
                                              [f"{x}_sub_0"] / 20 + .5)
                                elif 'wep_xp' == x:
                                    val = int(grind_table_state['total'][x] -
                                              grind_table_state['user'][x] -
                                              grind_table_state['user']
                                              [f"{x}_sub_1"] / 5 -
                                              grind_table_state['user']
                                              [f"{x}_sub_0"] / 25 + .5)
                                else:
                                    val = grind_table_state['total'][
                                        x] - grind_table_state['user'][x]

                                if val > 0:
                                    if x in ['xp', 'wep_xp', 'mora'
                                             ] and len(char_tracker[x]) > 5:
                                        char_set.add('many')
                                    else:
                                        char_set.update(char_tracker[x])
                                    item_set[x] = {
                                        'text': strings[x],
                                        'count': readable_number(val)
                                    }
                            else:
                                char_set.update(char_tracker[x])
                                item_set[x] = {'text': strings[x], 'count': ''}
                        else:
                            for i in range(len(strings[x])):
                                if grind_table_state['total'][
                                        f"{x}_{i}"] - grind_table_state[
                                            'user'][f"{x}_{i}"] > 0:
                                    char_set.update(char_tracker[x])
                                    item_set[f"{x}_{i}"] = {
                                        'text':
                                        strings[x][i],
                                        'count':
                                        readable_number(
                                            grind_table_state['total']
                                            [f"{x}_{i}"] -
                                            grind_table_state['user']
                                            [f"{x}_{i}"])
                                    }
                    if item_set:
                        v = (DIV(
                            IMG(src=f"img/{x}.png",
                                alt=item_set[x]['text'],
                                title=item_set[x]['text'],
                                loading="lazy") +
                            DIV(item_set[x]['count'], Class='bottom-right'),
                            Class='container') for x in item_set)
                        c = (IMG(src=f"img/{x}.png",
                                 alt=strings[x],
                                 title=strings[x],
                                 loading="lazy") for x in sorted(char_set))
                        t <= TR(
                            TD(strings[loc], Class="location") + TD(v) + TD(c))
                d <= t

    doc['daily'].text = ''
    doc['daily'] <= d
示例#36
0
def result():
    result_fildset = FIELDSET(Class='result')
    result_fildset <= LEGEND('Resultado')
    result_fildset <= DIV(id='result')

    document['grid'] <= result_fildset
示例#37
0
文件: app.py 项目: pbandierapaiva/nut
	def __init__(self):
		DIV.__init__(self, Class="modal fade")