예제 #1
0
    def __prompt(self, position, to_call):
        msg = 'Bet/Raise ({} to call):'.format(to_call)
        chips = self.__players[position].chips
        op_chips = lambda i: self.__players[i].chips * (1 - self.__folds[i]
                                                        ) * (i != position)
        m = max(range(self.__n_players), key=op_chips)
        max_chips = self.__players[m].chips
        chips2ai = self.__bets[m] - self.__bets[position] + max_chips
        bet = None
        layout = lambda dt: [[sg.Text(dt)][sg.Slider(
            (to_call + 1, min(chips2ai, chips)),
            orientation='h',
            relief='flat',
            border_width=0,
            background_color='#fff',
            size=(50, 15))], [sg.CButton('Ok', size=(50, 1))]] if dt else [[
                sg.Slider((to_call + 1, min(chips2ai, chips)),
                          orientation='h',
                          relief='flat',
                          border_width=0,
                          background_color='#fff',
                          size=(50, 15))
            ], [sg.CButton('Ok', size=(50, 1))]]
        dt = ''
        while True:
            try:
                window = sg.Window(title=msg,
                                   icon=absPath('resources/poker.icns'),
                                   keep_on_top=True,
                                   size=(500, 100),
                                   disable_close=True,
                                   layout=layout(dt))
                _, values = window.Read()
                bet = values[0]
                bet = int(bet)
                if bet > chips:
                    raise ValueError
                if chips2ai <= to_call:  # forbid raising
                    if bet < to_call:  # fail to call
                        raise ValueError
                    elif bet == to_call:  # call
                        break
                    else:
                        dt = 'No need to raise'
                else:  # bet only in [to_call, chips2ai]
                    if bet < to_call:  # fail to call
                        raise ValueError
                    elif to_call <= bet <= chips2ai:  # call or raise
                        break
                    else:
                        sg.PopupOK('Error!!!!!')
                        quit()
            except ValueError:
                dt = 'You can\'t bet "{}"'.format(bet)
            except TypeError:
                pass
        if bet == 0 and to_call > 0:
            self.__folds[position] = True

        return bet
예제 #2
0
def comparar(palabra):
    """Chequea si la palabra se encuentra en wiktionary, si se encuentra en pattern.es, y la agrega al diccionario de
        palabras, generando un reporte en caso de ser necesario, y pidiendole al usuario que ingrese una definición en
        caso de esta no ser provista por wiktionary."""
    tipo_wiktionary, definicion = wiki(palabra)
    tipo_pattern = pattern(palabra)
    if tipo_wiktionary == tipo_pattern:
        agregar(tipo_wiktionary, palabra, definicion)
    elif tipo_wiktionary != 'NoExiste':
        reporte(palabra, 1)
        agregar(tipo_wiktionary, palabra, definicion)
    else:
        if tipo_pattern == 'Verbo' or tipo_pattern == 'Adjetivo':
            layout = [[Sg.Multiline('', size=(30, 5))],
                      [Sg.CButton('Aceptar'),
                       Sg.CButton('Cerrar')]]
            window = Sg.Window('Definición').Layout(layout)
            event, values = window.Read()
            reporte(palabra, 2)
            if values[0] != '':
                agregar(tipo_pattern, palabra, values[0][:-2])
            else:
                Sg.PopupError(
                    'La palabra no se pudo agregar \n intente nuevamente')
        else:
            Sg.PopupError(
                'La palabra ingresada no existe \n Intente con otra palabra')
            reporte(palabra, 3)
예제 #3
0
def add_book_win():
    add_book_layout = [[sg.Text("Add a Book")],
                       [sg.Text("Title", size=[5, 1]),
                        sg.InputText()],
                       [sg.Text("Author", size=[5, 1]),
                        sg.InputText()],
                       [sg.Text("Pages", size=[5, 1]),
                        sg.InputText()],
                       [
                           sg.Text("Type", size=[5, 1]),
                           sg.Radio('Library',
                                    "GROUP1",
                                    default=True,
                                    key="Library"),
                           sg.Radio('Personal', "GROUP1", key="Personal")
                       ],
                       [
                           sg.Text("Month", size=[5, 1]),
                           sg.InputText(size=[20, 1]),
                           sg.Text("Day", size=[5, 1]),
                           sg.InputText(size=[20, 1]),
                           sg.Text("Year", size=[5, 1]),
                           sg.InputText(size=[20, 1])
                       ], [sg.CButton("Submit"),
                           sg.CButton("Cancel")]]

    return sg.Window("Add a Book", add_book_layout)
예제 #4
0
def import_osm_UI(dest_path, skip_check=False):
    """
    Temporary UI dialogue that manage import of osm file
    Note: Does NOT handle OSM to DB conversion
    :return osm_file_path
    """
    if not skip_check:
        layout = [[sg.Text('\nHave you downloaded your data from OSM?', font=("Helvetica", 12))],
                  [sg.Text('Press YES to proceed, press NO to open OSM', font=("Helvetica", 8), size=(50, 1), text_color="red")],
                  [sg.Text('')],
                  [sg.CButton('Yes'), sg.Button("No", )],
                  [sg.Text('')]]
        window9 = sg.Window('Sample GUI', grab_anywhere=False).Layout(layout)
        # diplays the form, collects the information and returns the data collected
        button9, values9 = window9.Read()

        if button9 is None:
            return None

        while button9 == "No":
            webbrowser.open_new("https://www.openstreetmap.org")
            button9, values = window9.Read()
            if button9 == "Yes":
                break
            if button9 is None:
                return None

    # flags for checking for valid input
    inputFlag = None
    osm_filepath = ""

    while inputFlag is not True:
        layout = [[sg.Text('\nOSM File Name')],
                  [sg.Text('*Please choose a valid OSM file', text_color='red', font=("Helvetica", 8))] if inputFlag is False else [],
                  [sg.Input(default_text=osm_filepath, change_submits=True, key='filepath_input', do_not_clear=True), sg.FileBrowse(file_types=(("OSM Files", "*.osm"),), initial_folder=dest_path)],
                  [sg.Text('\n', text_color='grey')],
                  [sg.Text('', font=("Helvetica", 4))],
                  [sg.CButton('Submit')]]

        window8 = sg.Window('Create Database', grab_anywhere=False).Layout(layout)
        while True:
            button8, values = window8.Read()
            osm_filepath = values['filepath_input']
            if button8 is None:
                return None
            elif button8 == 'filepath_input':
                window8.BringToFront()
            elif button8 == 'Submit':
                inputFlag = True if osm_filepath != "" and osm_filepath[-4:] == '.osm' else False
                if inputFlag is True:
                    break
                else:
                    sg.PopupError("Please choose a valid OSM file")

    return osm_filepath
예제 #5
0
def select_highway_UI():
    """
    Temporary UI dialogue for selecting highway values
    :return: list of highway values selected
    """
    highway_options = ['<select>',  # (do not remove) placeholder so the options list will never be empty
                       'motorway',
                       'trunk',
                       'tertiary',
                       'unclassified',
                       'residential',
                       'service']

    defaults = ['primary', 'secondary']

    highway_selected = defaults.copy()
    button_ex = ''

    highway_options.sort()
    highway_selected.sort()

    # Note about this section: make sure that neither of the Listboxes ever becomes empty
    while button_ex != "Yes":
        layout = [[sg.Column([[sg.Text('Highway Value Options')], [sg.Listbox(key='options', values=highway_options, size=(30, 6), select_mode='multiple', bind_return_key=True)]]),
                   sg.Column([[sg.Text('\n')],[sg.Button('>')], [sg.Button('<')]]),
                   sg.Column([[sg.Text('Highway Value Selected')], [sg.Listbox(key='selected', values=highway_selected, size=(30, 6), select_mode='multiple', bind_return_key=True)]])],
                  [sg.Text('', key='warning', text_color='red', size=(50, 1))],
                  [sg.CButton('Submit')]]
        window10 = sg.Window('Analysis Parameters - Highway Values', grab_anywhere=False).Layout(layout)
        button10, values = window10.Read()
        while True:
            #print(values['options'], values['selected'])
            if button10 is None:
                return None
            elif button10 == 'Submit':
                if len(highway_selected) > 0:
                    button_ex = "Yes"    # prevent the highway values selection UI from activating again
                break
            else:
                if button10 == '>' or button10 == 'options':
                    highway_selected.extend(values['options'])
                    if '<select>' in values['options']:
                        highway_selected.remove('<select>')
                    highway_options = [op for op in highway_options if op == '<select>' or op not in values['options']]
                elif button10 == '<' or button10 == 'selected':
                    if len(values['selected']) == len(highway_selected):
                        window10.FindElement('warning').Update('At least 1 highway value must be selected')
                    else:
                        highway_options.extend(values['selected'])
                        highway_selected = [op for op in highway_selected if op not in values['selected']]
                highway_options.sort()
                highway_selected.sort()
                window10.FindElement('selected').Update(values=highway_selected)
                window10.FindElement('options').Update(values=highway_options)

                button10, values = window10.Read()
                window10.FindElement('warning').Update('')

        # print(highway_selected)
        return highway_selected
예제 #6
0
    def __welcome(self):
        # welcome page
        window_title = 'Texas Hold \'em'

        layout = [[
            sg.Text(window_title,
                    justification='center',
                    font=('Palatino', 50),
                    size=(19, 1))
        ], [sg.Image(absPath('resources/cover.png'), pad=((70, 0), (0, 10)))],
                  [
                      sg.Frame(layout=[[
                          sg.Button('Start',
                                    bind_return_key=True,
                                    size=(15, 1)),
                          sg.Button('Help', size=(15, 1)),
                          sg.Button('Quit', size=(15, 1))
                      ]],
                               title='',
                               border_width=0)
                  ]]

        window = sg.Window(window_title,
                           icon=absPath('resources/poker.icns'),
                           size=(564, 270),
                           layout=layout,
                           disable_close=True).Finalize()
        self.__current_location = window.CurrentLocation()
        self.__current_size = window.Size

        window.Disable()
        if self.__hv is None:
            with absOpen('hv.json', 'r') as f:
                self.__hv = json.load(f)
        window.Enable()

        while True:
            event, values = window.Read()
            if event == 'Start':
                self.__current_location = window.CurrentLocation()
                self.__current_size = window.Size
                window.Close()
                break
            elif event == 'Help':
                sg.Window(
                    'Help',
                    keep_on_top=True,
                    location=self.__current_location,
                    icon=absPath('resources/poker.icns'),
                    layout=[[sg.Text('All rights reserved Allen Wang @ 2019')],
                            [sg.CButton('OK', size=(35, 1))]]).Read()
            elif event == 'Quit':
                self.__current_location = window.CurrentLocation()
                self.__current_size = window.Size
                window.Close()
                quit()
예제 #7
0
 def __init__(self, theme):
     sg.theme(theme)
     self.__layout = [
         [sg.Text('Quantas senhas quer gerar:'), sg.Input(size=(5, 1), key='Input', default_text=3)],
         [sg.Text('De quantos caracteres:'), sg.Input(size=(5, 1), key='Input2', default_text=10)],
         [sg.Checkbox('Maiúsculas', default=True, key='Maiusc'), sg.Checkbox('Minúsculas', default=True, key='Minusc')],
         [sg.Checkbox('Números   ', default=True, key='Numeri'), sg.Checkbox('Caracteres Espec.', default=True, key='CarEsp')],
         [sg.Button('Ok', size=(5, 1)),sg.CButton('Cancel')],
         [sg.Output(size=(31, 10))],
     ]
예제 #8
0
def gui(win2_active):
    while True:
        ev1, vals1 = win1.Read(timeout=100)
        if ev1 is None or ev1 == 'Exit':
            exit()

        if not win2_active and ev1 == 'vMix':
            webbrowser.open(url, new=new)

        if not win2_active and ev1 == 'Remote':
            win2_active = True
            layout2 = [[sg.Text('Remote Control')],
                       [sg.T(' ' * 10),
                        sg.RealtimeButton('Up')],
                       [
                           sg.RealtimeButton('Left'),
                           sg.T(' ' * 15),
                           sg.RealtimeButton('Right')
                       ], [sg.T(' ' * 10),
                           sg.RealtimeButton('Down', )], [sg.T('')],
                       [sg.CButton('Close', button_color=('black', 'orange'))]]

            win2 = sg.Window('Remote Control', layout2, auto_size_text=True)

            manual(win2)

            if win2_active is True:
                ev2, vals2 = win2.Read(timeout=100)
                if ev2 is None or ev2 == 'Close':
                    print('exit')
                    win2_active = False
                    client1.publish("ui", "exit'123'123'123")
                    win2.Close()

        if not win2_active and ev1 == 'Aimbot':
            opencv()

        ret, frame = cap.read()
        # d = frame.flatten()
        # data = d.tostring()
        # clientsocket.send(data)
        cv2.imshow('frame', frame)
예제 #9
0
                [psg.Text('Data Preview: ')],
                [
                    psg.Table(key='sgtable', values = [['','','','','','','','']], #placeholders until we learn how to dynamically create columns in PySimpleGUI
                                        headings=listHeadings, 
                                        auto_size_columns=True,
                                        alternating_row_color='#add8e6',
                                        num_rows=3)
                ]
]

layout = [
            [psg.Frame('Connection Manager', frame_connect)],
            [psg.Frame('Qualify Contract', frame_qualify)],
            [psg.Frame('Tick Data', frame_tick)],
            [psg.Frame('OHLC Data', frame_OHLC)],
            [psg.CButton('Exit')]
]
def main(ib):
    win_ibkr_allinone = psg.Window('IBRK Utilities', layout=layout)
    while True:  # Event Loop
        event, values = win_ibkr_allinone.Read()
        if event in (None, 'Exit'):
            win_ibkr_allinone.Close()
            break
        if event == '_BT_CONN_':
            logging.info("Connect clicked.")
            try:
                logging.info("Trying to connect.")
                ib.connect(
                    str(win_ibkr_allinone['_IB_IP_'].Get()),
                    int(win_ibkr_allinone['_IB_PORT_'].Get()),
예제 #10
0
def calculate_shortest_path(newNet, root_path):
    """
    Temporary UI dialogue boxes, allows options of 1. from CSV or 2. from 2 points
    Creates ShortestPathRD (from rubelMain) object to calculate shortest path

    :param newNet: NetworkCreation object (with network created)
    :param root_path: filepath of output folder
    :return:
    """
    frame_layout = [[sg.Radio('From CSV', 'path_cal', default=True)],
                    [sg.Radio('From 2 points', 'path_cal')]]
    layout = [[sg.Text("Network generation completed", pad=(2, 8))],
              [sg.Frame(' Compute Shortest Path ', frame_layout, font=14, title_color='dim grey', title_location='nw', pad=(8, 15))],
              [sg.CButton('Submit')]]
    window11 = sg.Window('Network Created', grab_anywhere=False).Layout(layout)
    button2, values = window11.Read()
    if button2 is None:
        return None
    elif button2 == 'Submit':
        path_input = 'CSV' if values[0] is True else '2pts'
    if path_input == '2pts':
        while True:
            frame_layout = [[sg.Text("Start point: [0 to n]", size=(23, 1), pad=(2, 8)), sg.Input(key='start_pt', size=(5,1))],
                            [sg.Text("End point: [0 to n]", size=(23, 1), pad=(2, 8)), sg.Input(key='end_pt', size=(5,1))]]
            layout = [[sg.Frame(' Enter Start and End Points ', frame_layout, font=14, title_color='dim grey', title_location='nw', pad=(8,15))],
                      [sg.CButton('Submit')]]
            window12 = sg.Window('Calculate Shortest Path - Input', grab_anywhere=False).Layout(layout)
            button2, values = window12.Read()

            if button2 is None:
                return None
            else:
                try:
                    path_pts = [values['start_pt'], values['end_pt']]
                    layout = [[sg.Text('Calculating shortest path...')]]
                    window3 = sg.Window('Loading')
                    window3.Layout(layout).Read(timeout=10)
                    time.sleep(2)  # placeholder
                    window3.Close()
                    if True:  # actual checking was stripped for this pureUI demo
                        frame_layout = [[sg.Checkbox('  Shapefiles', key='create_shp', pad=(25,2), tooltip='Create shapefiles for shortest path')],
                                        [sg.Checkbox('  CSV File', key='create_csv', pad=(25,2), tooltip='Create CSV file containing all intersection nodes and final distance')],
                                        [sg.Text('      '), sg.CButton('Next')]]
                        layout = [[sg.Text('From point %s to point %s' % (path_pts[0], path_pts[1]))],
                                  [sg.Text(" the shortest path is", pad=(0, 3)), sg.Text('123.4 km', text_color='red')],
                                  [sg.Frame(' Save Results ', frame_layout, font=14, title_color='dim grey', title_location='nw', pad=(8, 15))]]
                        window13 = sg.Window('Calculation complete', grab_anywhere=False).Layout(layout)
                        button2, values = window13.Read()

                        if button2 is None:
                            return None
                        elif button2 == 'Next':
                            createPathShapeFile = values['create_shp']
                            createCSVFile = values['create_csv']
                        else:
                            createPathShapeFile = False
                            createCSVFile = False

                        if createCSVFile or createPathShapeFile:
                            # dest_fold = create_folder(root_path, 'Output files2')
                            if createPathShapeFile:
                                layout = [[sg.Text('Creating shapefiles for shortest path...')]]
                                window4 = sg.Window('Loading')
                                window4.Layout(layout).Read(timeout=10)
                                time.sleep(2)
                                window4.Close()
                            if createCSVFile:
                                pass

                        recal_text = '\n' + ('Shapefiles ' if createPathShapeFile else '') +\
                                     ('and ' if createCSVFile and createPathShapeFile else '') + \
                                     ('CSV file ' if createCSVFile else '') + ('have ' if createPathShapeFile and createCSVFile else ('has ' if createCSVFile or createPathShapeFile else '')) +\
                                      'been created\n\n' if createPathShapeFile or createCSVFile else ''
                        recalculate = sg.PopupYesNo(recal_text + 'Calculate new path?\n')
                        if recalculate == 'No':
                            break
                        elif recalculate is None:
                            return None
                except ValueError:
                    sg.PopupError('Please enter valid\nstart and end points\n')
    elif path_input == 'CSV':
        while True:
            input_csv = sg.PopupGetFile('Select input CSV File', file_types=(("CSV Files", "*.csv"),), initial_folder=root_path)
            if input_csv is None:
                return None
            try:
                #dest_folder = create_folder(root_path, 'Shortest Path CSV')
                num_start = 10  # placeholder
                break
            except FileNotFoundError:
                sg.PopupError('Invalid file path')
        layout = [[sg.Text('Calculating shortest paths from CSV...\n(This may take a while)')],
                  [sg.ProgressBar(num_start, orientation='h', size=(20, 20), key='progress')]]
        window2 = sg.Window('Loading, Please wait...').Layout(layout)
        progress_bar = window2.FindElement('progress')
        mod_ref = 1 if num_start < 30 else (5 if num_start < 100 else num_start//10)
        for i in range(num_start):
            time.sleep(2)
            if i % (mod_ref) == 0:
                button, values = window2.Read(10)
                if values is None:
                    return None
                progress_bar.UpdateBar(i)
        window2.Close()
        sg.PopupOK("Shortest paths from CSV successful\nOutput CSV created")
    else:
        return None
예제 #11
0
def menu():
    """Pantalla principal del juego, menú con opciones para jugar, configurar el juego o salir"""
    try:
        config = open(
            os.path.join('configuracion', 'archivos', 'configuracion.json'),
            'r')
    except FileNotFoundError:
        crear_configuracion.crear()
        config = open(
            os.path.join('configuracion', 'archivos', 'configuracion.json'),
            'r')
    datos = json.load(config)
    config.close()
    cambiar_estilo(datos['estilo'])

    layout = [
        [
            Sg.Image(filename=os.path.join('imagenes', 'logo.png'),
                     size=(500, 500),
                     pad=(50, 0))
        ],
        [
            Sg.Button(image_filename=os.path.join('imagenes',
                                                  'boton_jugar.png'),
                      image_subsample=1,
                      border_width=0,
                      pad=(200, 0),
                      key='JUGAR')
        ],
        [
            Sg.Button('', border_width=0, pad=(230, 0)),
            Sg.Button(image_filename=os.path.join('imagenes', 'reporte.png'),
                      image_subsample=19,
                      border_width=0,
                      key='REPORTE',
                      pad=(10, 0)),
            Sg.Button(image_filename=os.path.join('imagenes',
                                                  'boton_configuracion.png'),
                      image_subsample=20,
                      border_width=0,
                      key='CONFIGURACIÓN',
                      pad=(10, 5)),
            Sg.CButton(button_text='',
                       image_filename=os.path.join('imagenes',
                                                   'boton_salir.png'),
                       image_subsample=20,
                       border_width=0,
                       key='SALIR',
                       pad=(10, 5))
        ]
    ]

    window = Sg.Window('Menú', grab_anywhere=False,
                       size=(670, 650)).Layout(layout)

    seguir = False
    while True:
        event, values = window.Read()
        if event is None or event == 'Quit':
            break
        elif event == 'JUGAR':
            window.Disappear()
            sopa_de_letras.sopa()
            Sg.SetOptions(auto_size_buttons=True)
            window.Reappear()
        elif event == 'CONFIGURACIÓN':
            seguir = configuracion.configuracion()
            break
        elif event == 'REPORTE':
            reporte()

    window.Close()
    return seguir
예제 #12
0
        (str(datetime.now())).split(' ')[0]).split('-')[0]

layout = [
    [sg.Text("Načíst údaje ze Superfaktura")],
    [sg.Text("DPH za období", auto_size_text=True)],
    [
        sg.InputText(key="ctvrtleti", size=(10, 1)),
        sg.Text("čtvrletí", size=(10, 1))
    ],
    [sg.InputText(key="rok", size=(10, 1)),
     sg.Text("Rok", size=(10, 1))],
    [
        sg.In(DatumDnes, key="DatumZpracovani", size=(10, 1)),
        sg.Text("Datum zpracování ve formátu DD.MM.YYYY", size=(35, 1))
    ],
    [sg.CButton("Run")]  #close button
]

window = sg.Window('Přiznání k DPH').Layout(layout)
Button, Values = window.Read()  # tohle musí být aby se okno objevilo

if Button == None or len(Values.get("rok")) == 0 or len(
        Values.get("ctvrtleti")) == 0:
    NoData()
    exit(0)
else:
    Rok = Values.get("rok")
    Quarter = Values.get("ctvrtleti")
    DatumDnes = Values.get("DatumZpracovani")

# Najdi aktuální kvartál z data
예제 #13
0
import time

# Demonstrates a notification window that's partially transparent
# The window slowly fades-in
# Includes a small red-X button to close the window
# Base 64 encoded button is in-lined to avoid reading a file
# Free online encoder - https://www.base64-image.de/
red_x = "R0lGODlhEAAQAPeQAIsAAI0AAI4AAI8AAJIAAJUAAJQCApkAAJoAAJ4AAJkJCaAAAKYAAKcAAKcCAKcDA6cGAKgAAKsAAKsCAKwAAK0AAK8AAK4CAK8DAqUJAKULAKwLALAAALEAALIAALMAALMDALQAALUAALYAALcEALoAALsAALsCALwAAL8AALkJAL4NAL8NAKoTAKwbAbEQALMVAL0QAL0RAKsREaodHbkQELMsALg2ALk3ALs+ALE2FbgpKbA1Nbc1Nb44N8AAAMIWAMsvAMUgDMcxAKVABb9NBbVJErFYEq1iMrtoMr5kP8BKAMFLAMxKANBBANFCANJFANFEB9JKAMFcANFZANZcANpfAMJUEMZVEc5hAM5pAMluBdRsANR8AM9YOrdERMpIQs1UVMR5WNt8X8VgYMdlZcxtYtx4YNF/btp9eraNf9qXXNCCZsyLeNSLd8SSecySf82kd9qqc9uBgdyBgd+EhN6JgtSIiNuJieGHhOGLg+GKhOKamty1ste4sNO+ueenp+inp+HHrebGrefKuOPTzejWzera1O7b1vLb2/bl4vTu7fbw7ffx7vnz8f///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAJAALAAAAAAQABAAAAjUACEJHEiwYEEABniQKfNFgQCDkATQwAMokEU+PQgUFDAjjR09e/LUmUNnh8aBCcCgUeRmzBkzie6EeQBAoAAMXuA8ciRGCaJHfXzUMCAQgYooWN48anTokR8dQk4sELggBhQrU9Q8evSHiJQgLCIIfMDCSZUjhbYuQkLFCRAMAiOQGGLE0CNBcZYmaRIDLqQFGF60eTRoSxc5jwjhACFWIAgMLtgUocJFy5orL0IQRHAiQgsbRZYswbEhBIiCCH6EiJAhAwQMKU5DjHCi9gnZEHMTDAgAOw=="

sg.change_look_and_feel('Topanga')
sg.set_options(border_width=0, margins=(0, 0))

layout = [
    [
        sg.Text('Notification' + ' ' * 14),
        sg.CButton('', image_data=red_x, button_color=('#282923', '#282923'))
    ],
    [sg.Text('You have 6 new emails')],
]

window = sg.Window('',
                   layout,
                   no_titlebar=True,
                   grab_anywhere=True,
                   keep_on_top=True,
                   alpha_channel=0,
                   finalize=True)

# Classy fade-in
for i in range(1, 75, 2):
    window.AlphaChannel = float(i) / 100
예제 #14
0
    [sg.Input(key='_vidfile_'), sg.FileBrowse()],
    [sg.Text('All video in folder')],
    [sg.Input(key='_folderpath_'),
     sg.FolderBrowse()],
    [sg.Text('Save results to')],
    [sg.Input(key='_resultspath_'),
     sg.FolderBrowse()],
    [sg.Text('Matches')],
    [
        sg.Slider(range=(1, 10),
                  orientation='h',
                  size=(34, 20),
                  default_value=1,
                  key=('_matchesn_'))
    ],
    [sg.CButton('Ok'), sg.CButton('Cancel')],
])
event, values = window.read()
print(values['_imgfile_'])
imagefile = values['_imgfile_']
videofile = values['_vidfile_']
videodir = values['_folderpath_']
resultPath = values['_resultspath_']
matchesnumber = int(values['_matchesn_'])
print(imagefile + ' ' + videofile)


def get_filename_datetime():
    # Use current date to get a text file name.
    return "Frame Search results-" + str(date.today()) + ".txt"
예제 #15
0
    def __config(self):
        # config page
        window_title = 'Game Config'

        # initial values
        n_players = self.__n_players
        buy_in = self.__buy_in

        layout = lambda n_players: [
            [
                sg.Frame(layout=[[
                    sg.Text('Game Config',
                            font=('Palatino', 50),
                            justification='center',
                            size=(19, 1))
                ],
                                 [
                                     sg.Text('Number of player:', size=(16, 1)
                                             ),
                                     sg.Spin(list(range(2, 10)),
                                             initial_value=n_players,
                                             size=(3, 20),
                                             change_submits=True),
                                     sg.Text('Buy-in:',
                                             size=(17, 1),
                                             justification='right'),
                                     sg.InputText(str(buy_in), size=(5, 20))
                                 ]],
                         title='',
                         border_width=0)
            ],
            [
                sg.Frame(layout=[[
                    sg.Text('Name of player {}:'.format(i + 1), size=(16, 1)),
                    sg.InputText('Player {}'.format(i + 1), size=(30, 20))
                ] for i in range(n_players)],
                         title='',
                         border_width=0)
            ],
            [
                sg.Frame(layout=[[
                    sg.Button('Submit', bind_return_key=True, size=(15, 1)),
                    sg.Button('Reset', size=(15, 1)),
                    sg.Button('Quit', size=(15, 1))
                ]],
                         title='',
                         border_width=0)
            ],
        ]

        window = sg.Window(window_title,
                           icon=absPath('resources/poker.icns'),
                           size=(564, 270 + 40 * (n_players - 2)),
                           disable_close=True,
                           location=self.__current_location,
                           layout=layout(n_players)).Finalize()
        while True:
            try:
                event, values = window.Read()
                new_n_players = int(values[0])
                if not (1 < new_n_players < 10):
                    raise ValueError
                if new_n_players != n_players:
                    n_players = new_n_players
                    self.__current_location = window.CurrentLocation()
                    window.Close()
                    window = sg.Window(window_title,
                                       icon=absPath('resources/poker.icns'),
                                       size=(564, 270 + 40 * (n_players - 2)),
                                       disable_close=True,
                                       location=self.__current_location,
                                       layout=layout(n_players)).Finalize()
                if event == 'Submit':
                    buy_in = int(values[1])
                    assert len(values) == 2 + n_players
                    player_names = values[-n_players:]
                    assert n_players == len(player_names)
                    self.__current_location = window.CurrentLocation()
                    window.Close()
                    break
                elif event == 'Reset':
                    n_players = self.__n_players
                    self.__current_location = window.CurrentLocation()
                    window.Close()
                    window = sg.Window(window_title,
                                       icon=absPath('resources/poker.icns'),
                                       size=(564, 270 + 40 * (n_players - 2)),
                                       disable_close=True,
                                       location=self.__current_location,
                                       layout=layout(n_players)).Finalize()
                elif event == 'Quit':
                    quit()
            except ValueError:
                sg.Window('Error',
                          icon=absPath('resources/poker.icns'),
                          keep_on_top=True,
                          layout=[[sg.Text('Invalid value entry')],
                                  [sg.CButton('OK', size=(20, 1))]]).Read()
                self.__current_location = window.CurrentLocation()
                window.Close()
                window = sg.Window(window_title,
                                   icon=absPath('resources/poker.icns'),
                                   size=(564, 270 + 40 * (n_players - 2)),
                                   disable_close=True,
                                   location=self.__current_location,
                                   layout=layout(n_players)).Finalize()
            except AssertionError:
                pass
            except TypeError:
                quit()

        self.__n_players = n_players
        self.__buy_in = buy_in
        self.__players = [Player(buy_in, name) for name in player_names]
예제 #16
0
    def __finishGame(self):
        msg = []
        if max(len(p.cards) for p in self.__players) > 5:
            hval = [value(p.cards, self.__hv) for p in self.__players]
            nwin = 0
            maxv = 0
            for i, v in enumerate(hval):
                if self.__folds[i]: continue
                if v[0] > maxv:
                    maxv = v[0]
                    nwin = 1
                elif v[0] == maxv:
                    nwin += 1
            for i in range(self.__n_players):
                player = self.__players[i]
                if self.__folds[i]:
                    symbol = ' -'
                elif hval[i][0] == maxv:
                    player.chips += self.__pot // nwin
                    symbol = ' \u2605'
                else:
                    symbol = ''
                msg.append('[{}] Hand: {} ({}). Chips: {}'.format(
                    self.__players[i].name, ' '.join(hval[i][1]),
                    handTypeLong(hval[i][1]),
                    str(player.chips) + symbol))
        else:
            for i in range(self.__n_players):
                player = self.__players[i]
                if not self.__folds[i]: player.chips += self.__pot
                msg.append('[{}] Chips: {}'.format(
                    self.__players[i].name,
                    str(player.chips) +
                    (' -' if self.__folds[i] else ' \u2605')))

        window_title = 'Game {}'.format(self.__n_game)
        self.__window.TKroot.title('Texas Hold \'em - ' + window_title)
        self.__window.FindElement('_TT_').Update(window_title)
        mask = []
        mask = [-1 if self.__folds[i] else 1 for i in range(self.__n_players)]
        fig = self.__tf.plot(self.__players,
                             community_cards=self.__community_cards,
                             mask=mask)
        _ = drawFigure(self.__window.FindElement('_CANVAS_').TKCanvas, fig)
        self.__current_location = self.__window.CurrentLocation()
        self.__current_size = self.__window.Size

        self.__print('Results of game {}:'.format(self.__n_game))
        for m in msg:
            self.__print(m)

        result_size = (600, 55 + 25 * self.__n_players)
        result_location = [
            c + s // 2 - s_ // 2 for c, s, s_ in zip(
                self.__current_location, self.__current_size, result_size)
        ]

        sg.Window(
            'Results',
            keep_on_top=True,
            icon=absPath('resources/poker.icns'),
            disable_close=True,
            size=result_size,
            location=result_location,
            layout=[[sg.Text('\n'.join(msg))],
                    [sg.CButton('OK', size=(60, 1),
                                bind_return_key=True)]]).Read()

        if len([p.chips for p in self.__players if p.chips]) > 1:
            self.__n_game += 1
            self.__players = np.roll(self.__players, -1).tolist()
            self.__tf.sb = (self.__tf.sb + 1) % self.__n_players
            self.__newGame()
        else:  # game over for good
            quit()
예제 #17
0
def configuracion():
    """Interfaz de la pantalla de configuración, guarda las nuevas configuraciones, en caso de que no se haya modificado
        algún item, se deja el valor guardado anteriormente."""

    with open(os.path.join('configuracion', 'archivos', 'configuracion.json'), 'r') as ar_config:
        dato = json.load(ar_config)

    palabras_max = tamanio_ventana()
    fonts = fuentes()
    text0 = Sg.InputText('')
    text1 = Sg.InputText('')

    Sg.SetOptions(element_padding=(10, 15), auto_size_buttons=True, auto_size_text=True, )

    layout = [[Sg.Text('Agregar Palabra'), text0, Sg.Button('Agregar')],
              [Sg.Text('Eliminar Palabra'), text1, Sg.Button('Eliminar')],
              [Sg.Frame(layout=[[Sg.Text('Colores con los que se representarán las palabras a encontrar en la Sopa de '
                                         'Letras')], [Sg.ColorChooserButton('Adjetivos', pad=(50, 0), key='ColorAdj'),
                                                      Sg.ColorChooserButton('Sustantivos', pad=(50, 0), key='ColorSus'),
                                                      Sg.ColorChooserButton('Verbos', pad=(50, 0), key='ColorVer')],
                                [Sg.Text('Ayuda'), Sg.Radio('Si', 'ayuda', key='ayudaS',
                                                            default=dato['tipo_Ayuda'] != "Palabras por tipo"),
                                 Sg.Radio('No', 'ayuda', key='ayudaN',
                                          default=dato['tipo_Ayuda'] == "Palabras por tipo"),
                                 Sg.Text('Tipo de Ayuda'), Sg.InputCombo(('', 'Definiciones', 'Lista de Palabras'),
                                                                         key='TipoAyuda')],
                                [Sg.Text('Orientación de las palabras'),
                                 Sg.Radio('Horizontal', 'pos', key='OHor', default=dato['orientacion'] == 'H'),
                                 Sg.Radio('Vertical', 'pos', key='OVer', default=dato['orientacion'] == 'V')],
                                [Sg.Text('Cantidad de'), Sg.Text('Adjetivos'),
                                 Sg.InputText(default_text=str(dato["cantidad_Adj_Sus_Ver"][0]), size=(5, 4),
                                              key='CantAdj'), Sg.Text('Sustantivos'),
                                 Sg.InputText(default_text=str(dato["cantidad_Adj_Sus_Ver"][1]), size=(5, 4),
                                              key='CantSus'), Sg.Text('Verbos'),
                                 Sg.InputText(default_text=str(dato["cantidad_Adj_Sus_Ver"][2]), size=(5, 4),
                                              key='CantVer')],
                                [Sg.Text('    Máximo ' + str(palabras_max) + ' palabras en total', pad=(0, 0),
                                         font=(any, 8, 'bold', 'italic'))],
                                [Sg.Text('Tipografía del reporte'), Sg.InputCombo(fonts, size=(30, 20), key='font')],
                                [Sg.Text('Oficina'), Sg.InputCombo(cargar_oficinas(), key='Oficina')],
                                [Sg.Text('Letras'), Sg.Radio('MAYUSCULA', 'M/m', key='M', default='M' == dato['M/m']),
                                 Sg.Radio('minúscula', 'M/m', key='m', default='m' == dato['M/m'])]],
                        title='Configuración', title_location='n', pad=(30, 10))],
              [Sg.Button('', pad=(200, 0), border_width=0), Sg.Button('Aceptar'), Sg.CButton('Cancelar')]]

    ventana_config = Sg.Window('Configuracion', size=(650, 650)).Layout(layout)

    seguir = True

    while seguir:
        event, values = ventana_config.Read()
        if event is None or event == 'Quit':
            break
        try:
            if event == 'Agregar':
                agregar_palabras.agregar_palabra(values[0])
                text0.Update('')
                raise
            if event == 'Eliminar':
                eliminar_palabra.eliminar(values[1])
                text1.Update('')
                raise
            if event == 'Aceptar':
                # Verifico que se hayan seleccionado colores para representar los distintos tipos de palabras y
                # si no quedan los seleccionados por defecto.
                if values['ColorAdj'] != '' and values['ColorAdj'] != 'None':
                    dato['colores'][0] = values['ColorAdj']
                if values['ColorSus'] != '' and values['ColorSus'] != 'None':
                    try:
                        if values['ColorAdj'] != values['ColorSus']:
                            dato['colores'][1] = values['ColorSus']
                        else:
                            raise
                    except:
                        Sg.PopupError('El color seleccionado ya ha sido seleccionado para otro tipo de palabra \n Puede'
                                      ' elegir otro color o dejar el color anterior')
                        raise
                if values['ColorVer'] != '' and values['ColorVer'] != 'None':
                    try:
                        if values['ColorAdj'] != values['ColorVer'] and values['ColorSus'] != values['ColorVer']:
                            dato['colores'][2] = values['ColorVer']
                        else:
                            raise
                    except:
                        Sg.PopupError('El color seleccionado ya ha sido seleccionado para otro tipo de palabra \n Puede'
                                      ' elegir otro color o dejar el color anterior')
                        raise

                # Si quiere ayuda y se seleccionó un tipo de ayuda se modifica, si no por defecto habrá ayuda y será el
                # listado de palabras a buscar
                if values['ayudaS']:
                    if values['TipoAyuda'] != '':
                        dato['tipo_Ayuda'] = values['TipoAyuda']
                    else:
                        dato['tipo_Ayuda'] = 'Lista de Palabras'
                elif values['ayudaN']:
                    dato['tipo_Ayuda'] = 'Palabras por tipo'

                # Orientación de las palabras
                if values['OHor']:
                    dato['orientacion'] = 'H'
                elif values['OVer']:
                    dato['orientacion'] = 'V'

                # Cantidad de Adjetivos, Verbos y Sustantivos a usar en la Sopa de Letras
                pt = 0
                if values['CantAdj'] != '':
                    pt += int(values['CantAdj'])
                else:
                    pt += int(dato['cantidad_Adj_Sus_Ver'][0])
                if values['CantSus'] != '':
                    pt += int(values['CantSus'])
                else:
                    pt += int(dato['cantidad_Adj_Sus_Ver'][1])
                if values['CantVer'] != '':
                    pt += int(values['CantVer'])
                else:
                    pt += int(dato['cantidad_Adj_Sus_Ver'][2])
                try:
                    if 0 < pt <= int(palabras_max):
                        if values['CantAdj'] != '':
                            dato['cantidad_Adj_Sus_Ver'][0] = int(values['CantAdj'])
                        if values['CantSus'] != '':
                            dato['cantidad_Adj_Sus_Ver'][1] = int(values['CantSus'])
                        if values['CantVer'] != '':
                            dato['cantidad_Adj_Sus_Ver'][2] = int(values['CantVer'])
                    else:
                        if pt == 0:
                            Sg.PopupError('Debe haber mínimo una palabra para hacer la sopa de letras \n Por favor '
                                          'cambie algún valor a mayor que 0')
                        elif pt > palabras_max:
                            Sg.PopupError('Demasiadas palabras intente nuevamente con menos cantidad', keep_on_top=True)
                        raise
                except:
                    raise

                # Si las palabras van a ir en Mayúscula o Minúscula
                if values['M']:
                    dato['M/m'] = 'M'
                elif values['m']:
                    dato['M/m'] = 'm'

                # tipografía del reporte
                if values['font'] != '@MS Gothic':
                    dato['tipografia'] = values['font']

                # estilo(Change_Look_And_Feel)
                dato['estilo'] = cambiar_aspecto(values['Oficina'])
        except:
            seguir = True
        else:
            with open(os.path.join('configuracion', 'archivos', 'configuracion.json'), 'w') as ar_config:
                json.dump(dato, ar_config)
            break

    ventana_config.Close()
    return True
예제 #18
0
                         ],
                         [
                             sg.B('Add',
                                  key='aaddkey',
                                  pad=(5, 30),
                                  button_color=sg.TRANSPARENT_BUTTON,
                                  image_filename='images\\okcancel.png',
                                  font=('Roboto', 11),
                                  image_size=(100, 36),
                                  image_subsample=1,
                                  border_width=False),
                             sg.CButton('Close',
                                        key='acancelkey',
                                        pad=(5, 5),
                                        button_color=sg.TRANSPARENT_BUTTON,
                                        image_filename='images\\okcancel.png',
                                        font=('Roboto', 11),
                                        image_size=(100, 36),
                                        image_subsample=1,
                                        border_width=False)
                         ]]

# ------------------------------- ADD WINDOW LAYOUT ENDS ------------------------------------------#

# ------------------------------- MAIN WINDOW CREATION ------------------------------------------- #

in_mainwin = sg.Window('Capital Management',
                       layout_mainwin,
                       border_depth=True,
                       grab_anywhere=False,
                       font=("Roboto", 12),
예제 #19
0
                sg.CalendarButton('End Date', target='_EndDate_'),
                sg.Text('Pick Dates')
            ],
            [
                sg.Input(default_text="1000", key='_tickCount_', tooltip='Number of ticks to fetch at a time', size=(4,1), disabled=True),
                sg.Combo(listWhatToShows, key='_whatToShow_', auto_size_text=True),
                sg.Checkbox('RTH?', key='_useRTH_'),
                sg.Checkbox('Size Only Ticks?', key='_ignoreSize_')

            ],
            [
                sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'), 
                sg.InputText(str_default_path, key='_targetFolder_'), 
                sg.FolderBrowse(target='_targetFolder_')
            ],
            [sg.Button('Fetch'), sg.Button('Download'), sg.CButton('Close', key='_CloseWindow_')],
            [sg.Text('Data gathered: '), sg.Text('',key='_TickCount_')]
        ]


def utc2local (utc):
    #NOTE converts UTC time to LOCAL
    epoch = time.mktime(utc.timetuple())
    offset = datetime.fromtimestamp (epoch) - datetime.utcfromtimestamp (epoch)
    return (utc + offset).replace(tzinfo=None)

def local2utc(local):
    #NOTE converts LOCAL time to UTC
    epoch = time.mktime(local.timetuple())
    offset = datetime.fromtimestamp (epoch) - datetime.utcfromtimestamp (epoch)
    return (local - offset).replace(tzinfo=None)