import xmlrpc.client
import config
import tkinter as tk
from tkinter.filedialog import askopenfilename
import subprocess
import numpy as np
import time
proxy_cluster = xmlrpc.client.ServerProxy('http://localhost:'+str(config.CLUSTER))

# esto lo metemos en un for y vamos tratando uno a uno + tratamiento de errores
# proxy_server1 = xmlrpc.client.ServerProxy('http://localhost:9001')
# proxy_server2 = xmlrpc.client.ServerProxy('http://localhost:9002')
import os

m_list=[]
filename =None
price=None
#---in_csv: path del archivo
#---rowsize: numero de linias por archivo ó numero de nodos
def UploadAction(event=None):
    global filename
    filename = askopenfilename(initialdir='.')
    # Cut path to the file off
    filename = filename.split('/')[len(filename.split('/'))-1]
    print('Selected:', filename)
    label1['text'] = filename

def UploadAction2(min_max):

      global filename
      number_lines = sum(1 for row in (open(filename)))
      list_servers=proxy_cluster.get_servers()
      chunksize = round(number_lines/len(list_servers))
      since=0
      totaltime=0
      time_worker=0
      start_time = time.time()
      if min_max == "min":
            for server in list_servers:
                  minn,time_worker=xmlrpc.client.ServerProxy('http://localhost:'+str(server)).get_min(filename, since, chunksize, price)
                  totaltime=totaltime+float(time_worker)
                  m_list.append(minn)
                  since=since+chunksize
            x = np.array(m_list)
            y = x.astype(np.float64)
            min_value=min(y)
            label2['text'] = min_value
      elif min_max == "max":
            for server in list_servers:
                  maxx,time_worker=xmlrpc.client.ServerProxy('http://localhost:'+str(server)).get_max(filename, since, chunksize, price)
                  totaltime=totaltime+float(time_worker)
                  m_list.append(maxx)
                  since=since+chunksize
            x = np.array(m_list)
            y = x.astype(np.float64)
            max_value=max(y)
            label2['text'] = max_value
######elif --> more options"
      else:
            label2['text'] = "ERROR: Please, select min or max price"
      print("Total Time : "+str(time.time() - start_time)+" seconds in "+str(len(list_servers))+" worker/s")
      print("Time without connexions: "+str(totaltime)+" seconds in "+str(len(list_servers))+" worker/s")

def UploadAction3(price_input):
      global price
      price=price_input

      # Cut path to the file off
def UploadAction4(event=None):
     subprocess.call('start python xmlrpc_server.py', shell=True)
     label4['text'] = str(int(label4['text'])+1)

      # Cut path to the file off

subprocess.call('start python xmlrpc_cluster.py', shell=True)
root= tk.Tk(className='Tick prices')
root.geometry("500x500")

button1 = tk.Button(text='Select File', command=UploadAction, bg='blue', fg='white')
button1.pack(padx=2, pady=5)
label1 = tk.Label(text='Please choose a file')
label1.pack(padx=2, pady=2)
label2 = tk.Label()

button7 = tk.Button(text='Add worker', command=UploadAction4, bg='blue', fg='white')
button7.pack(padx=2, pady=5)
label4 = tk.Label( text='0')
label4.pack(padx=2, pady=2)

label6 = tk.Label(text='----------------Select price type-----------------')
label6.pack(padx=2, pady=2)
button3 = tk.Button(text='Ask', command=lambda:UploadAction3('Ask'), bg='brown', fg='white')
button3.pack(padx=2, pady=5)
button4 = tk.Button(text='Bid', command=lambda:UploadAction3('Bid'), bg='brown', fg='white')
button4.pack(padx=2, pady=5)
button5 = tk.Button(text='AskVolume', command=lambda:UploadAction3('AskVolume'), bg='brown', fg='white')
button5.pack(padx=2, pady=5)
button6 = tk.Button(text='BidVolume', command=lambda:UploadAction3('BidVolume'), bg='brown', fg='white')
button6.pack(padx=2, pady=5)

label3 = tk.Label(text='---------------------------------------------------------')
label3.pack(padx=2, pady=2)
button2 = tk.Button(text='Compute Low price', command=lambda:UploadAction2("min"), bg='red', fg='white')
button2.pack(padx=2, pady=5)
button8 = tk.Button(text='Compute High price', command=lambda:UploadAction2("max"), bg='green', fg='white')
button8.pack(padx=2, pady=5)
label2.pack(padx=2, pady=2)

root.mainloop()


from inventory_report.reports.colored_report import ColoredReport
from inventory_report.reports.simple_report import SimpleReport

def test_decorar_relatorio():
    products = [
        {
            "id": 1,
            "nome_do_produto": "Cafe",
            "nome_da_empresa": "Cafes Nature",
            "data_de_fabricacao": "2020-07-04",
            "data_de_validade": "2023-02-09",
            "numero_de_serie": "FR48",
            "instrucoes_de_armazenamento": "instrucao"
        },
        {
            "id": 2,
            "nome_do_produto": "Cafe2",
            "nome_da_empresa": "Cafes Nature",
            "data_de_fabricacao": "2010-07-04",
            "data_de_validade": "2023-02-09",
            "numero_de_serie": "FR48",
            "instrucoes_de_armazenamento": "instrucao"
        },
        {
            "id": 1,
            "nome_do_produto": "Cafe3",
            "nome_da_empresa": "Nature",
            "data_de_fabricacao": "2020-07-04",
            "data_de_validade": "2025-02-09",
            "numero_de_serie": "FR48",
            "instrucoes_de_armazenamento": "instrucao"
        }
    ]

    green_code = '[32m'
    blue_code = '[36m'
    red_code = '[31m'

    report = ColoredReport(SimpleReport).generate(products)

    green_phrases = [
        'Data de fabricação mais antiga',
        'Data de validade mais próxima',
        'Empresa com mais produtos'
    ]

    for phrase in green_phrases:
        phrase_start = report.find(phrase)
        phrase_color_code = report[phrase_start - len(green_code):phrase_start]
        assert phrase_color_code == green_code

    blue_dates = ["2010-07-04", "2025-02-09"]

    for date in blue_dates:
        date_start = report.find(date)
        date_color_code = report[date_start - len(blue_code):date_start]
        assert date_color_code == blue_code

    red_text = "Cafes Nature"

    text_start = report.find(red_text)
    text_color_code = report[text_start - len(red_code):text_start]

    assert text_color_code == red_code


# -*- coding: utf-8 -*-
import json
import math
import os
import pandas as pd
import pickle
import flask
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.plotly as py
import functools
import dash_table_experiments as dt

from apps import graph_tools, cpe_tools, chatbot_tools
# from apps import chatbot_tools
from dash.dependencies import Input, Output, State
from plotly import graph_objs as go
from flask_caching import Cache
from app import app, indicator, millify, df_to_table, sf_manager

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.production

# cache = Cache(app.server, config={
#     'CACHE_TYPE': 'filesystem',
#     'CACHE_DIR': '/data/users/Gusseppe/reto_IGV/dashboard/piloto1/cache'
# })
# returns pie chart that shows lead source repartition
TIMEOUT = 60
total_monto = 0
#@cache.memoize(timeout=TIMEOUT)

#Init chatboot
id_chatbot, chatbot = chatbot_tools.init_chatbot()
chatbot_tools.train_chatbot(chatbot)

@functools.lru_cache(maxsize=32)
def grafo_cpe(dimen_graph, statement, title):
    response, action, ruc = chatbot_tools.run_chatbot(id_chatbot, chatbot, statement)
    df = cpe_tools.logic_vinculacion(ruc, action)
    G = graph_tools.init_graph(df)
    fig = graph_tools.draw_graph(G, dimen_graph, title)

    return fig

@functools.lru_cache(maxsize=32)
def graph_cpe_detail(ruc, dimen_graph, title):
    action = 'detalle'
    df = cpe_tools.logic_vinculacion(ruc, action)
    G = graph_tools.init_graph(df)
    fig = graph_tools.draw_graph(G, dimen_graph, title)

    return fig

@functools.lru_cache(maxsize=32)
def draw_time_series(ruc):
    current_path = os.getcwd()
    df_path = os.path.join(current_path, 'df_time_series.csv')
    df = pd.read_csv(df_path)
    df_perfil = cpe_tools.mostrar_perfil_ruc(ruc)
    title = f"Comportamiento CPE de {df_perfil['nom_comercial'].head(1).values[0]}"

    fig = graph_tools.draw_time_series(df, title)

    return fig

@functools.lru_cache(maxsize=32)

def chatbot_cpe(statement):

    response, action, ruc = chatbot_tools.run_chatbot(id_chatbot, chatbot, statement)
#     print(f'chatbot_cpe {ruc}')
#     if cpe_tools.existe_vinculacion(ruc):
#         return response
#     else:
#         return f" Te conozco: cpe_tools.mostrar_ficha(ruc). Pero aun no tengo vinculaciones."
# # #     print(action)
# # #     print(ruc)
    return response

layout = [

    # top controls
    html.Div(
        [
            html.Div(
                dcc.Dropdown(
                    id="periodo_dropdown2",
                    options=[
                        {"label": "Mayo", "value": "mayo"},
                        {"label": "Junio", "value": "junio"},
                        {"label": "Julio", "value": "julio"},
                    ],
                    value="mayo",
                    clearable=False,
                ),
                className="two columns",
            ),
            html.Div(
                dcc.Dropdown(
                    id="dimension_graph",
                    options=[
                        {"label": "3D", "value": "3d"},
                        {"label": "2D", "value": "2d"},
#                         {"label": "Otros", "value": "converted"},
#                         {"label": "Otros", "value": "lost"},
                    ],
                    value="2d",
                    clearable=False,
                ),
                className="two columns",
            ),

            # add button
#             html.Div(
#                 html.Span(
#                     "Buscar por RUC",
#                     id="new_lead",
#                     n_clicks=0,
#                     className="button button--primary",
#                     style={
#                         "height": "34",
#                         "background": "#119DFF",
#                         "border": "1px solid #119DFF",
#                         "color": "white",
#                     },
#                 ),
#                 className="two columns",
#                 style={"float": "right"},
#             ),
        ],
        className="row",
        style={"marginBottom": "10"},
    ),

    # indicators row div
    html.Div(
        [
            indicator(
                "#00cc96", "Cantidad de CPE", "left_relac_indicator"
            ),
            indicator(
                "#119DFF", "Monto total CPE", "middle_relac_indicator"
            ),
            indicator(
                "#EF553B",
                "Mes CPE",
                "right_relac_indicator",
            ),
        ],
        className="row",
    ),
    ## Chatbot
    html.Div(
            [
            html.Div(
                [
                    dcc.Dropdown(
                        id="input_chatbot_dropdown",
                        options=[
                            {"label": "A quién le vende este RUC: ", "value": "A quien le vende"},
                            {"label": "A quién le compra este RUC: ", "value": "A quien le compra"},
                        ],
                        placeholder='Funciones',
                        value="",
#                         value=['vendedor', 'comprador'],
#                         multi=True,
                        #clearable=False,
                    ),
                ],className="four columns",
            ),
            html.Div(
                [
                    dcc.Input(
                        id="input_chatbot_input",
#                         placeholder="Preguntale al grafo: p.e, Quien le vende a este RUC: 10212132244",
                        placeholder="Hola!, busca a una empresa por RUC ",
                        type="text",
#                         list = ['este ruc te refieres?', 'asdasd'],
                        value="",
                        style={"width": "100%"},
                    ),
                            ],
#                 className="six columns",
                className="four columns",
                style={"marginBottom": "10"},
                # style={"paddingRight": "15"},
            ),
            #dropdown empresas
            html.Div(
                [
                    dcc.Dropdown(
                        id="input_nombre_empresa_dropdown",
                        options=cpe_tools.mostrar_empresas(),
                        placeholder='Empresas',
                        value="",
                    ),
                ],className="two columns",
            ),

            html.Div(
                [
                # submit button
                    html.Span(
                        "GO",
                        id="submit_chatboot",
                        n_clicks=0,
                        #className="btn btn-primary"
                        className="button button--primary add"
                    ),
#                     dcc.Input(
#                         id="output_chatbot",
#                         placeholder="Respuesta de Adaline: ",
#                         type="text",
#                         value="",
#                         disabled=True,
#                         style={"width": "100%"},
#                     ),
                ],
#                 className="six columns",
                className="two columns",
                # style={"paddingRight": "15"},
            ),
            html.Div(
                [
                    # html.Hr(),
                    dcc.Input(
                        id="output_chatbot",
                        placeholder="Adaline: ",
                        type="text",
                        value="",
                        disabled=True,
                        style={"width": "100%"},
                    ),
                ],
#                 className="six columns",
                className="twelve columns",
                # style={"paddingRight": "15"},
            ),
        ],
        className="row",
        style={"marginBottom": "10", "marginTop": "10"},
    ),

     # Grafo principal
    html.Div(
        [
#             html.Div(
#                 [
#                     html.P("Agrupacion por monto de CPE" ),
#                     dcc.Graph(
#                         id="monto_cpe",
#                         style={"height": "90%", "width": "98%"},
#                         config=dict(displayModeBar=False),
#                     ),
#                 ],
#                 className="four columns chart_div"
#             ),

            html.Div(
                [
#                     html.P("Agrupacion por cantidad de CPE"),

                    dcc.Graph(
                        id="main_graph",
#                         figure=grafo_3d_cpe(1,2),
                        style={"height": "200%", "width": "100%"},
                        config=dict(displayModeBar=True,
                                    showLink=False),
                    ),

                ],
                className="twelve columns",
            ),

        ],
        className="row",
        style={"marginBottom": "10", "marginTop": "10"},
    ),
    # Grafo detalle
    html.Div(
        [

            html.Div(
                [
                    #                     html.P("Agrupacion por cantidad de CPE"),

                    dcc.Graph(
                        id="node_details_graph",
                        style={"height": "200%", "width": "100%"},
                        config=dict(displayModeBar=True,
                                    showLink=False),
                    ),

                ],
                className="six columns",
            ),
            html.Div([
                html.Div([

                    dt.DataTable(
                        id='my-datatable2', rows=[{}],
                    ),
                ], className="six columns", id='my-datatable-div2',
                   style={"marginBottom": "10", "paddingLeft": "5"}),

                html.Div([

                    dt.DataTable(
                        id='table_detail_level_2', rows=[{}],
                    ),
                ], className="six columns", id='div_detail_level_2'),

            ]),

        ],
        className="row",
        style={"marginBottom": "10", "marginTop": "10"},
    ),

    # Time series
    html.Div(
        [

            html.Div(
                [
                    #                     html.P("Agrupacion por cantidad de CPE"),

                    dcc.Graph(
                        id="time_series_detail",
                        style={"height": "200%", "width": "100%"},
                        config=dict(displayModeBar=True,
                                    showLink=False),
                    ),

                ],
                className="twelve columns",
            ),

        ],
        className="row",
        style={"marginBottom": "10", "marginTop": "10"},
    ),

#     table div 1
#
#     html.Div([
#         html.Div([
#
# #                 id="relac_table2",
#
#                 dt.DataTable(
#                     id='my-datatable', rows=[{}],
#                 ),
#         ], className="twelve columns", id='my-datatable-div'),
#
#     ],
#         className="row", style={"marginBottom": "15", "marginTop": "5"},
#     ),

]

# updates left indicator based on df updates
@app.callback(
    Output("left_relac_indicator", "children"), [Input("dimension_graph", "value")]
)
def left_relac_indicator_callback(status):
    return millify(db.cpe_mayo_2018.count())
#     return converted_relac

# updates middle indicator based on df updates
@app.callback(
    Output("middle_relac_indicator", "children"), [Input("dimension_graph", "value")]
)
def middle_relac_indicator_callback(status):
    total_monto = 37e9

    return millify(total_monto)

# updates right indicator based on df updates
@app.callback(
    Output("right_relac_indicator", "children"), [Input("periodo_dropdown2", "value")]
)
def right_relac_indicator_callback(periodo):
    return periodo

# update pie chart figure based on dropdown's value and df updates
@app.callback(
    Output("main_graph", "figure"),
    [Input("submit_chatboot", "n_clicks"),
     Input("dimension_graph", "value")],
    [
        State("input_chatbot_dropdown", "value"),
        State("input_chatbot_input", "value"),
    ],
)
def grafo_cpe_callback(n_clicks, dimen_graph, in_drop, in_input):
    if n_clicks > 0:
        statement = str(in_drop) + ' ' + str(in_input)
        title = 'Red de vinculaciones CPE'
        return grafo_cpe(dimen_graph, statement, title)

    return None

@app.callback(
    Output("output_chatbot", "value"),
    [Input("submit_chatboot", "n_clicks")],
    [
        State("input_chatbot_dropdown", "value"),
        State("input_chatbot_input", "value")
    ],
)
def chatbot_cpe_callback(n_clicks, in_drop, in_input):
    if n_clicks > 0:
        statement = str(in_drop) + ' ' + str(in_input)
        return chatbot_cpe(statement)

    return "Preguntame algo :)"

# @app.callback(
#     Output('my-datatable-div', 'children'),
#     [Input("submit_chatboot", "n_clicks")],
#     [
#         State("input_chatbot_dropdown", "value"),
#         State("input_chatbot_input", "value")
#     ],
#
# )
# def show_df_search_callback(n_clicks, in_drop, in_input):
#     if n_clicks > 0:
#         statement = str(in_drop) + ' ' + str(in_input)
#         response, action, ruc = chatbot_tools.run_chatbot(id_chatbot, chatbot, statement)
#         df = cpe_tools.logic_vinculacion(ruc, action)
#
#         return  html.Div([dt.DataTable(
#                         #rows=[{}],
#                         rows=df.to_dict('records'),
#                         # optional - sets the order of columns
#                         columns=sorted(df.columns),
#                         # row_selectable=True,
#                         filterable=True,
#                         sortable=True,
#                         # selected_row_indices=list(df.index),
#                         id='my-datatable'
#         )], className="row")
#
#     #return None

@app.callback(
    Output('my-datatable-div2', 'children'),
    [Input('main_graph', 'clickData'), Input("submit_chatboot", "n_clicks")],

)
def show_df_detail_level_1_callback(clickData, n_clicks):
    if clickData is not None:
        ruc = clickData['points'][0]['text'].split('|')[0].split(':')[2].strip()
        df = cpe_tools.mostrar_perfil_ruc(ruc)

        return  html.Div(
            [
                # html.H6(f"Perfil de: {df['nom_comercial'].head(1).values[0]}"),
                dt.DataTable(
                        #rows=[{}],
                        rows=df.to_dict('records'),
                        # optional - sets the order of columns
                        columns=sorted(df.columns),
                        row_selectable=True,
                        # filterable=True,
                        sortable=True,
                        selected_row_indices=list(df.index),
                        id='my-datatable2'
        )], className="row")

    #return None

@app.callback(
    Output('node_details_graph', 'figure'),
    [Input('main_graph', 'clickData'),
    ],
    [
        State("dimension_graph", "value"),
    ],

)
def show_graph_detail_level_1_callback(clickData, dimen_graph):
    if clickData is not None:
        ruc = clickData['points'][0]['text'].split('|')[0].split(':')[2].strip()

        df_perfil = cpe_tools.mostrar_perfil_ruc(ruc)
        title = f"Redes de vinculaciones de {df_perfil['nom_comercial'].head(1).values[0]}"

        return graph_cpe_detail(ruc, dimen_graph, title)

@app.callback(
    Output('div_detail_level_2', 'children'),
    [Input('main_graph', 'clickData')],

)
def show_df_detail_level_2_callback(clickData):

    if clickData is not None:
        ruc = clickData['points'][0]['text'].split('|')[0].split(':')[2].strip()
        print(ruc)
        action = 'detalle'
        df = cpe_tools.logic_vinculacion(ruc, action)
        print(df.head())

        return  html.Div(
            [
                # html.H6(f"Tabla vinculaciones de {df['nom_comercial'].head(1).values[0]}"),
                dt.DataTable(
                    #rows=[{}],
                    rows=df.to_dict('records'),
                    # optional - sets the order of columns
                    columns=sorted(df.columns),
                    row_selectable=True,
                    # filterable=True,
                    sortable=True,
                    selected_row_indices=list(df.index),
                    id='table_detail_level_2'
                )], className="row")

    #return None

@app.callback(
    Output('input_chatbot_input', 'value'),
    [Input('input_nombre_empresa_dropdown', 'value')],

)
def fill_input_chatbot_callback(nombre_empresa):
    return nombre_empresa

@app.callback(
    Output('time_series_detail', 'figure'),
    [Input('main_graph', 'clickData'),
     ],
    [
        State("dimension_graph", "value"),
    ],

)
def show_graph_detail_level_1_callback(clickData, dimen_graph):
    if clickData is not None:
        ruc = clickData['points'][0]['text'].split('|')[0].split(':')[2].strip()

        return draw_time_series(ruc)


from tkinter import *

root = Tk()
root.geometry('150x150+700+250')

def menu():
    def soma():
        a = int(input_n1.get())
        b = int(input_n2.get())
        total = a + b
        resultado.set(str(total))

    def subtrai():
        a = int(input_n1.get())
        b = int(input_n2.get())
        total = a - b
        resultado.set(str(total))

    def multiplicacao():
        a = int(input_n1.get())
        b = int(input_n2.get())
        total = a * b
        resultado.set(str(total))

    def divisao():
        a = float(input_n1.get())
        b = float(input_n2.get())
        total = a / b
        resultado.set(str(total))

    n1 = StringVar()
    n2 = StringVar()
    resultado = StringVar()

    def limpar():
        resultado.set("")
        n1.set("")
        n2.set("")
        input_n1.focus()

    # janela
    L1 = Label(root, text='N1')
    L2 = Label(root, text='N2')
    input_n1 = Entry(root, textvariable=n1)
    input_n2 = Entry(root, textvariable=n2)
    som = Button(root, text='+', command=soma)
    sub = Button(root, text='-', command=subtrai)
    mult = Button(root, text='x', command=multiplicacao)
    div = Button(root, text='/', command=divisao)
    limpar = Button(root, text='limpar', command=limpar)
    res = Label(root, textvariable=resultado)

    L1.grid(row=0, column=0)
    L2.grid(row=1, column=0)
    som.place(relx=0.1, rely=0.5, relwidth=0.2, relheight=0.2)
    sub.place(relx=0.3, rely=0.5, relwidth=0.2, relheight=0.2)
    mult.place(relx=0.5, rely=0.5, relwidth=0.2, relheight=0.2)
    div.place(relx=0.7, rely=0.5, relwidth=0.2, relheight=0.2)
    input_n1.grid(row=0, column=1)
    input_n2.grid(row=1, column=1)
    res.grid()
    limpar.place(relx=0.4, rely=0.7, relwidth=0.3, relheight=0.2)

menu()
root.mainloop()


# utils.py

import numpy as np
#from astropy import units as u # May be necesary because of object?
from astropy.time import Time
#from astropy.coordinates import Angle, ICRS  # May be necssary because of object?
import de421
import jplephem
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# Object that stores info for recreating plots
class track_data(object):
    # Plot metadata
    objname=''
    dt=0.
    nmctrials=0.
    startdate=0.
    enddate=0.
    refID=0.
    nobs=0
    npriorobs=0
    npharoobs=0
    # Tracks and their 1+2 sigma limits
    datearr=0.
    sep=0.
    sep_1sig=0. # 2D array, second index indicates min/max
    sep_2sig=0.
    pa=0.
    pa_1sig=0.
    pa_2sig=0.
    # measured dates/positions (and where they would be if they were bg)
    obsdates=0.
    meas_sep=0.
    meas_sep_err=0.
    bg_sep=0.
    meas_pa=0.
    meas_pa_err=0.
    bg_pa=0.
    # pharo measured dates/positions (and where they would be if they were bg)
    pharo_obsdates=0.
    pharo_sep=0.
    pharo_sep_err=0.
    pharo_bg_sep=0.
    pharo_pa=0.
    pharo_pa_err=0.
    pharo_bg_pa=0.
    # prior dates/positions (and where they would be if they were bg)
    prior_obsdates=0.
    prior_sep=0.
    prior_sep_err=0.
    prior_bg_sep=0.
    prior_pa=0.
    prior_pa_err=0.
    prior_bg_pa=0.
    prior_cite=''

    # The class "constructor"/"initializer"
    def __init__(self,objname,dt,nmctrials,startdate,enddate,refID,datearr,sep,sep_1sig,sep_2sig,pa,pa_1sig,pa_2sig,obsdates,meas_sep,meas_sep_err,bg_sep,meas_pa,meas_pa_err,bg_pa,pharo_obsdates,pharo_sep,pharo_sep_err,pharo_bg_sep,pharo_pa,pharo_pa_err,pharo_bg_pa,prior_obsdates,prior_sep,prior_sep_err,prior_bg_sep,prior_pa,prior_pa_err,prior_bg_pa,prior_cite):
        self.objname=objname
        self.dt=dt
        self.nmctrials=nmctrials
        self.startdate=startdate
        self.enddate=enddate
        self.refID=refID
        self.nobs=obsdates.size
        self.npharoobs=pharo_obsdates.size
        self.npriorobs=prior_obsdates.size
        self.datearr=datearr
        self.sep=sep
        self.sep_1sig=sep_1sig
        self.sep_2sig=sep_2sig
        self.pa=pa
        self.pa_1sig=pa_1sig
        self.pa_2sig=pa_2sig
        self.obsdates=obsdates
        self.meas_sep=meas_sep
        self.meas_sep_err=meas_sep_err
        self.bg_sep=bg_sep
        self.meas_pa=meas_pa
        self.meas_pa_err=meas_pa_err
        self.bg_pa=bg_pa
        self.pharo_obsdates=pharo_obsdates
        self.pharo_sep=pharo_sep
        self.pharo_sep_err=pharo_sep_err
        self.pharo_bg_sep=pharo_bg_sep
        self.pharo_pa=pharo_pa
        self.pharo_pa_err=pharo_pa_err
        self.pharo_bg_pa=pharo_bg_pa
        self.prior_obsdates=prior_obsdates
        self.prior_sep=prior_sep
        self.prior_sep_err=prior_sep_err
        self.prior_bg_sep=prior_bg_sep
        self.prior_pa=prior_pa
        self.prior_pa_err=prior_pa_err
        self.prior_bg_pa=prior_bg_pa
        self.prior_cite=prior_cite

# gets the background position of star (equivalent to background_position.pro)
# But in millarcseconds!
def get_bg_pos(sep,pa,pm_ra,pm_dec,ra,dec,parallax,ref_epoch,final_epoch,PA_near_zero=False,parallax_offset=True):
    """
    Takes separation and pos ang of stars, the proper motion, reference epoch and final epoch
    and returns final separation [mas] and position angle [deg]
    INPUTS:
    sep             -- separation between stars, in milliarcseconds
    pa              -- postion angle in degrees E of N
    pm_ra           -- proper motion of star, in RA, in milliarcseconds
    pm_dec          -- proper motion of star, in DEC, in milliarcseconds
    ra              -- RA of star in degrees
    dec             -- DEC of star in degrees
    parallax        -- parallax of star (in milliarcseconds; 1000.0*1/dist_pc)
    ref_epoch       -- Epoch at which ALL sep, pa, ra, dec were measured [decimal date]
    final_epoch     -- Epoch at which to compute output sep/pa [decimal date]
    KEYWORD INPUTS:
    PA_near_zero    -- Output PAs in interval (-180,180) instead of (0,360)
    parallax_offset -- Consider effect of Earth's motion (parallax) [default TRUE]
    OUTPUTS:
    out_sep         -- separation at final_epoch, in milliarcseconds
    out_pa          -- position angle at final_epoch, in degrees
    """
    # Get initial x,y separations
    x0=sep*np.sin(np.radians(pa))
    y0=sep*np.cos(np.radians(pa))

    # Get adjustment from proper motion (pm values in milliarcseconds/yr)
    # (-1 since companion moves opposite direction to star)
    dx_pm = (final_epoch-ref_epoch)*pm_ra*-1.0
    dy_pm = (final_epoch-ref_epoch)*pm_dec*-1.0
    new_x = x0 + dx_pm
    new_y = y0 + dy_pm

    # Get adjustment from parallax (if keyword set)
    if parallax_offset:
        # Get offsets at ref and final epochs
        # (unlike parallax.pro, we use real parallax here so no need to adjust for it later)
        (ref_raoff,ref_decoff)=get_parallax_offset(ra,dec,parallax,ref_epoch)
        (out_raoff,out_decoff)=get_parallax_offset(ra,dec,parallax,final_epoch)
        # Apply offset: first subtract off reference epoch to get true position, then add parallax offset
        # (However, apply -1 factor due to background object moving in opposite direction)
        new_x = (new_x+ref_raoff)  - out_raoff
        new_y = (new_y+ref_decoff) - out_decoff

    # Compute new sep and pa
    out_sep=np.sqrt(new_x**2.0+new_y**2.0)
    out_pa=np.degrees(np.arctan2(new_x,new_y)) # in degrees now
    out_pa=np.mod(out_pa,360.0) # between 0 and 360deg
    if PA_near_zero:
        if out_pa >180:
            out_pa-=360.0 # now between -180 to +180
    return (out_sep,out_pa)

# gets the offset due to parallax of Earth (equivalent to parallax.pro)
def get_parallax_offset(ra,dec,parallax,epoch,ra_units='detector'):
    """
    Takes the star's ra, dec, parallax, and a given epoch.
    Returns the parallax shift in star's position, in arcseconds (sexagesimal seconds for raoff; decimal seconds for decoff)
    INPUTS:
    ra          -- RA position of star, in degrees
    dec         -- DEC position of star, in degrees
    parallax    -- parallax of star, in MILLIarcseconds (1000.0*1/distance_pc)
    epoch       -- epoch (decimal years) to compute parallax offset (scalar or monotonically increasing vector)
    ra_units    -- USE EITHER:
                   'time': raoff is in seconds of time in RA (need to multiply by 15 to get same units as decoff)
                   'detector': [default] 1 unit displacement same in both horizontal/vertical direction
                               (factor of cos(dec) applied to raoff; multiply by 15 to get same units)
    OUTPUTS:
    raoff       -- parallax shift in star's position, in milliarcseconds
    decoff      -- parallax shift in star's position, in milliarcseconds
    """
    # Convert from deg to rad
    ra_rad=np.radians(ra)
    dec_rad=np.radians(dec)

    # Use jplephem with de421 to determine position of Earth geocenter wrt SS Barycenter
    eph=jplephem.Ephemeris(de421)
    t=Time(epoch,format='jyear',scale='ut1')
    JD=t.jd
    barycenter = eph.position('earthmoon', JD)
    moonvector = eph.position('moon', JD)
    earthPos = (barycenter - moonvector * eph.earth_share) / 1.49597871e+8
    usex=np.float(earthPos[0])
    usey=np.float(earthPos[1])
    usez=np.float(earthPos[2])

    # Compute offsets (in milliarcseconds)
    delta_alpha = parallax * 1./np.cos(dec_rad) * (usex*np.sin(ra_rad) - usey*np.cos(ra_rad))
    delta_delta = parallax * (usex*np.cos(ra_rad)*np.sin(dec_rad) + usey*np.sin(ra_rad)* np.sin(dec_rad) - usez*np.cos(dec_rad))
    # Convert RA seconds as necessary
    if ra_units=='time':
        delta_alpha = delta_alpha / 15.0
    elif ra_units=='detector':
        delta_alpha = delta_alpha * np.cos(dec_rad)
    else:
        raise Exception('ra_units set to unhandled option: {}'.format(ra_units))

    # Set outputs
    raoff=delta_alpha
    decoff=delta_delta

    return (raoff,decoff)

# Returns the value corresponding to given confidence interval
# Assumes 1D array!
def get_ci(array,ci):
    array_sort=np.sort(array)
    ind_low=np.floor((0.5-ci/2.0)*array.size).astype(np.int)
    ind_high=np.ceil((0.5+ci/2.0)*array.size).astype(np.int)
    return (array_sort[ind_low],array_sort[ind_high])

# Function to create and save the plot (o=track_data object)
def make_plot(o,outfilename,titlestring,titleloc,no_prior=False,no_pharo=False,no_bg=False,for_poster=False):
    # "for_poster" makes plots slightly differently formatted and coloured
    if for_poster:
        myplotfonts={'size': 36}
        max_n_xtics=4
        max_n_ytics=4
        xlabel_fontsize=24
        ylabel_fontsize=24
        our_data_fmt='ko'
    else: # this is for paper
        myplotfonts={'size': 24}
        max_n_xtics=4
        max_n_ytics=6
        xlabel_fontsize=24
        ylabel_fontsize=24
        our_data_fmt='ko'
    matplotlib.rc('font',**myplotfonts)
    # Use thicker axes border
    matplotlib.rc('axes', linewidth=2.0)
    # Get a few important parameters
    nobs=o.obsdates.size # not used
    # Create figure
    fig = plt.figure()
    # sep subplot
    ax_sep = fig.add_subplot(2,1,1)
    # Make title label (on SEP SUBPLOT) -- only if not making plots for poster!
    if not for_poster:
        if titleloc=='left':
            ax_sep.text(0.03,0.95,titlestring,weight='bold',horizontalalignment='left',verticalalignment='top',transform=ax_sep.transAxes)
        elif titleloc=='center':
            ax_sep.text(0.50,0.95,titlestring,weight='bold',horizontalalignment='center',verticalalignment='top',transform=ax_sep.transAxes)
        elif titleloc=='right':
            ax_sep.text(0.97,0.95,titlestring,weight='bold',horizontalalignment='right',verticalalignment='top',transform=ax_sep.transAxes)
        elif titleloc=='none':
            pass # don't make a title!
        else:
            raise Exception('Invalid value for titleloc: {}'.format(titleloc))
    # Plot BG track and 68+95 confidence intervals (use zorder to place shaded stuff behind the rest)
    if not no_bg:
        ax_sep.plot(o.datearr,o.sep,'k-',linewidth=2)
        ax_sep.fill_between(o.datearr,o.sep_1sig[:,0],o.sep_1sig[:,1],color='0.5',zorder=-1)
        ax_sep.fill_between(o.datearr,o.sep_2sig[:,0],o.sep_2sig[:,1],color='0.8',zorder=-2)
    # Plot constant sep value (with errorbar)
    #ax_sep.axhline(y=np.mean(o.meas_sep),color='black',linestyle=':')
    ax_sep.axhline(y=o.meas_sep[o.refID],color='black',linestyle=':')
    ax_sep.axhline(y=o.meas_sep[o.refID]+o.meas_sep_err[o.refID],color='black',linestyle=':')
    ax_sep.axhline(y=o.meas_sep[o.refID]-o.meas_sep_err[o.refID],color='black',linestyle=':')
    # For each measurement, plot actual position (filled) and if they were bg (open)
    if not for_poster and not no_bg:
        ax_sep.plot(o.obsdates,o.bg_sep,'ko',ms=10,mew=2,mfc='None')
    ax_sep.errorbar(o.obsdates,o.meas_sep,yerr=o.meas_sep_err,fmt=our_data_fmt,ms=10)
    ax_sep.set_xlim([o.startdate,o.enddate])
    #ax_sep.set_ylim([2440,2530]) manual adjustment for a specific plot
    # Plot PHARO measurements, if they exist AND ``no_pharo'' is not set:
    if o.npharoobs > 0 and not no_pharo:
        if not no_bg:
            ax_sep.plot(o.pharo_obsdates,o.pharo_bg_sep,'k^',ms=10,mew=2,mfc='None')
        ax_sep.errorbar(o.pharo_obsdates,o.pharo_sep,yerr=o.pharo_sep_err,fmt='k^',ms=10)
    # Plot prior measurements, if they exist AND ``no_prior'' is not set:
    if o.npriorobs > 0 and not no_prior:
        if not no_bg:
            ax_sep.plot(o.prior_obsdates,o.prior_bg_sep,'ks',ms=10,mew=2,mfc='None')
        ax_sep.errorbar(o.prior_obsdates,o.prior_sep,yerr=o.prior_sep_err,fmt='ks',ms=10)
    # Format x axis tics (turn off labels, but keep tic marks)
    ax_sep.xaxis.set_major_locator(ticker.MaxNLocator(nbins=max_n_xtics,integer=True)) # sets xtics at nice locations
    ax_sep.xaxis.set_major_formatter(ticker.NullFormatter()) # do not show xtic labels
    ax_sep.xaxis.set_minor_locator(ticker.AutoMinorLocator(n=4))
    # Format y axis tics (prune edge for ganged plots)
    ax_sep.yaxis.set_major_locator(ticker.MaxNLocator(nbins=max_n_ytics,prune='both')) # set ytics at nice locations
    ax_sep.yaxis.set_major_formatter(ticker.ScalarFormatter(useOffset=False))
    ax_sep.yaxis.set_minor_locator(ticker.AutoMinorLocator(n=2))
    if not for_poster:
        ax_sep.set_ylabel('Sep [mas]',fontsize=ylabel_fontsize)
    # Increase length and thickness of tics
    ax_sep.tick_params('both',length=10,width=2.0,which='major')
    ax_sep.tick_params('both',length=5,width=2.0,which='minor')
    # PA subplot
    ax_pa=fig.add_subplot(2,1,2)
    # Plot BG track and 68+95 confidence intervals (use zorder to place shaded stuff behind the rest)
    if not no_bg:
        ax_pa.plot(o.datearr,o.pa,'k-',linewidth=2)
        ax_pa.fill_between(o.datearr,o.pa_1sig[:,0],o.pa_1sig[:,1],color='0.5',zorder=-1)
        ax_pa.fill_between(o.datearr,o.pa_2sig[:,0],o.pa_2sig[:,1],color='0.7',zorder=-2)
    # Plot constant PA value (with errorbar)
    #ax_pa.axhline(y=np.mean(o.meas_pa),color='black',linestyle=':')
    ax_pa.axhline(y=o.meas_pa[o.refID],color='black',linestyle=':')
    ax_pa.axhline(y=o.meas_pa[o.refID]+o.meas_pa_err[o.refID],color='black',linestyle=':')
    ax_pa.axhline(y=o.meas_pa[o.refID]-o.meas_pa_err[o.refID],color='black',linestyle=':')
    # For each measurement, plot actual position (filled) and if they were bg (open)
    if not for_poster and not no_bg:
        ax_pa.plot(o.obsdates,o.bg_pa,'ko',ms=10,mew=2,mfc='None')
    ax_pa.errorbar(o.obsdates,o.meas_pa,yerr=o.meas_pa_err,fmt=our_data_fmt,ms=10)
    ax_pa.set_xlim([o.startdate,o.enddate])
    # Plot PHARO measurements, if they exist AND ``no_pharo'' is not set:
    if o.npharoobs > 0 and not no_pharo:
        if not no_bg:
            ax_pa.plot(o.pharo_obsdates,o.pharo_bg_pa,'k^',ms=10,mew=2,mfc='None')
        ax_pa.errorbar(o.pharo_obsdates,o.pharo_pa,yerr=o.pharo_pa_err,fmt='k^',ms=10)
    # Plot prior measurements, if they exist AND ``no_prior'' is not set:
    if o.npriorobs > 0 and not no_prior:
        if not no_bg:
            ax_pa.plot(o.prior_obsdates,o.prior_bg_pa,'ks',ms=10,mew=2,mfc='None')
        ax_pa.errorbar(o.prior_obsdates,o.prior_pa,yerr=o.prior_pa_err,fmt='ks',ms=10)
    # Format x axis tics
    ax_pa.xaxis.set_major_locator(ticker.MaxNLocator(nbins=max_n_xtics,integer=True)) # sets xtics at nice locations
    ax_pa.xaxis.set_major_formatter(ticker.FormatStrFormatter('%4d')) # format for xtic labels
    ax_pa.xaxis.set_minor_locator(ticker.AutoMinorLocator(n=4))
    if not for_poster:
        ax_pa.set_xlabel('Date [yr]',fontsize=xlabel_fontsize)
    # Format y axis tics (prune edges for ganged plots)
    ax_pa.yaxis.set_major_locator(ticker.MaxNLocator(nbins=max_n_ytics,prune='both')) # set ytics at nice locations
    ax_pa.yaxis.set_major_formatter(ticker.ScalarFormatter(useOffset=False))
    ax_pa.yaxis.set_minor_locator(ticker.AutoMinorLocator(n=2))
    if not for_poster:
        ax_pa.set_ylabel('PA [deg]',fontsize=ylabel_fontsize)
    # Increase length and thickness of tics
    ax_pa.tick_params('both',length=10,width=2.0,which='major')
    ax_pa.tick_params('both',length=5,width=2.0,which='minor')
    # Adjust so that everything fits and plots are stacked
    fig.tight_layout()
    plt.subplots_adjust(hspace=0.001) # no horizontal space between figures
    fig.savefig(outfilename) # png for display
    fig.savefig(outfilename.replace('.png','.svg'),format='svg',dpi=1200) # for plotting

# Output the data used in making plot
def make_data_table(o,outfilename):
    f=open(outfilename,'w')
    # Write: Object name, obs-date, separation, error, PA, error, citation
    for ii in range(0,o.npriorobs):
        f.write('{} & {:7.2f} & ${:6.1f} \pm {:6.1f}$ & ${:5.1f} \pm {:5.1f}$ & {}\\\\\n'.format(o.objname,o.prior_obsdates[ii],o.prior_sep[ii],o.prior_sep_err[ii],o.prior_pa[ii],o.prior_pa_err[ii],o.prior_cite[ii]))
    for jj in range(0,o.nobs):
        if o.meas_pa_err[jj] < 0.1:
            f.write('{} & {:7.2f} & ${:6.1f} \pm {:6.1f}$ & ${:5.2f} \pm {:5.2f}$ & {}\\\\\n'.format(o.objname,o.obsdates[jj],o.meas_sep[jj],o.meas_sep_err[jj],o.meas_pa[jj],o.meas_pa_err[jj],'this work'))
        else:
            f.write('{} & {:7.2f} & ${:6.1f} \pm {:6.1f}$ & ${:5.1f} \pm {:5.1f}$ & {}\\\\\n'.format(o.objname,o.obsdates[jj],o.meas_sep[jj],o.meas_sep_err[jj],o.meas_pa[jj],o.meas_pa_err[jj],'this work'))
    f.close()


# https://codeforces.com/contest/1807/problem/D

def check(seq, req):
    z = sum(seq)
    pref = [0 for _ in range(len(seq) + 1)]
    pref[0] = 0
    for i in range(len(seq)):
        pref[i+1] = pref[i] + seq[i]
    for reqs in req:
        if (pref[reqs[1]] - pref[reqs[0]-1]) % 2 == reqs[2] * (reqs[1] - reqs[0] + 1) % 2:
            if z % 2 == 1:
                print("YES")
            else:
                print("NO")
        else:
            if z % 2 == 1:
                print("NO")
            else:
                print("YES")

for _ in range(int(input())):
    _, q = map(int, input().split())
    seq = tuple(map(int, input().split()))
    res = []
    for _ in range(q):
        res.append(tuple(map(int, input().split())))
    check(seq, res)


"""
Mathilde Jeannin, 2023
jeannin@lix.polytechnique.fr
"""
import numpy as np
import random
from MCTS import MCTS, Node

class Snake(Node):
    def __init__(self, board, terminal, size, loose):
        # terminal : simulation s'arrete si perdu (loose), ou manger pomme
        # loose = perdu (s'est mangé)
        self.board = board #tuple t.q. board[0] -> position corps (board[0][0] = tete serpent), board[1] = position pomme
        self.terminal = terminal
        self.size = size
        self.loose = loose
        # la pomme a ete mange au coup precedent

    def all_possible_children(self):
        if self.is_terminal:
            []
        moves = []
        for direction in np.array([[0,1],[0,-1], [-1,0],[-1,0]]):
            if not (self.board[0][1]-self.board[0][0]==direction).all() and not (self.board[0][0]+direction>np.array(self.size)).any() and not (self.board[0][0]+direction<np.array([0,0])).any():
                move = self.make_move(direction)
                moves.append(move)
        print(self.board)
        return moves

    def is_terminal(self):
        return self.terminal

    def reward(self):
        if not self.terminal:
            raise RuntimeError(f"reward called on nonterminal board {self.board}")
        if self.loose == None: ## n'a fait que des move autorisés sans ramasser de pomme donc pas terminal
            raise RuntimeError(f"reward called on nonterminal board {self.board}")
        if self.loose: ## s'est mangé
            return -10
        if not self.loose: ## a manger une pomme
            return 5
        return

    def make_move(self, direction):
        loose = None
        terminal = False
        # tup = ([self.board[0][0]+direction],self.board[1])
        body = np.array([self.board[0][0]+direction])
        apple = self.board[1]
        coord_prec = self.board[0][0]
        for coord in self.board[0][1:]:
            body = np.concatenate((body, [coord_prec]))
            coord_prec=coord
        for body_part in self.board[0][1:]: #nouvel emplacement tete dans nouvel emplacement corps
            if body_part[0]==body[0][0] and body_part[1]==body[0][1]:
                terminal = True
                loose = True
        if (body[0]==self.board[1]).all(): #manger une pomme
            apple = newapple(self.size, body)
            terminal = True
            loose = False
        return Snake(board=(body, apple), terminal=terminal, size=self.size, loose=loose)

def newapple(size, snake):
    find_position = False
    while not find_position:
        x = random.randint(1,size[0])
        y = random.randint(1,size[1])
        if x not in snake or y not in snake:
            find_position = True
    return np.array([x,y])

## recreer un arbre a chaque pomme mangee ?

def play_game():
    size = [50,50]
    head = np.array([random.randint(3,size[0]-3),random.randint(3,size[0]-3)])
    direction = np.array([[0,1],[0,-1],[1,0],[-1,0]])
    body = np.concatenate(([head], [head+random.choice(direction)]))
    two_players = False
    apple = newapple(size, body)
    tree = MCTS(two_players=two_players)
    snake = Snake((body,apple), False, size, False)
    while True:
        for _ in range(100):
            tree.do_rollout(snake)
        snake = tree.choose(snake)
        if snake.loose:
            break

if __name__=="__main__":
    play_game()


# TIE-02100 Johdatus ohjelmointiin
# TIE-02106 Introduction to Programming
# Task: ROT13, full

def read_message():
    syotteet = []
    syote = " "
    while syote is not "":
        syote = str(input())
        if syote == "":
            return syotteet
        syotteet.append(syote)

def encrypt(alphabet):
    alphabet_low = alphabet.lower()
    regular_chars = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
                     "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                     "w", "x", "y", "z"]
    if alphabet_low not in regular_chars:
        return alphabet
    encrypted_chars = ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
                       "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i",
                       "j", "k", "l", "m"]
    location = regular_chars.index(alphabet_low)
    alphabet_new = encrypted_chars[location]
    if alphabet == regular_chars[location]:

        return alphabet_new
    else:
        return alphabet_new.upper()

def row_encryption(string):
    new_string = ""
    for mark in string:
        new_string += encrypt(mark)
    return new_string

def main():
    print("Enter text rows to the message. Quit by entering an empty row.")
    msg = read_message()

    print("ROT13:")
    for rivi in msg:
        rivi = row_encryption(rivi)
        print(rivi)

main()

Ohjelmointi 1/Ohjelmointi 1/alle 7. krs/ROT13_final.py


import datetime
a = """Turing: DOJ: 22 Aug 2017 | Subjects: Math, English | Salary: 18 LPA in hand | Also takes Web lectures.
Dinho: DOJ: 1 Jan 2016 | Subjects: Sports, Health Science | Salary: 25 LPA in hand
Adele:  DOJ: 1 Mar 2015 | Subjects: English | Salary: 10 LPA in hand
Freddie: DOJ: 1 Aug 2017 | Subjects: Music, English | Salary: 20 LPA in hand | Also takes Web lectures.
Dalton: DOJ: 1 Mar 2017 | Subjects: Botany, Zoology | Salary: 9 LPA in hand | Also takes Web lectures.
Harish: DOJ: 1 Feb 2017 | Subjects: Math, Science | Salary: 18 LPA in hand
Trump: DOJ: 1 Aug 2017 | Subjects: Political Science, Business Administration, Foreign Affairs | Salary: 8 LPA in hand
Swaraj: DOJ: 1 Sept 2019 | Subjects: Foreign Affairs, Negotiations | Salary: 28 LPA in hand | Also takes Web lectures.
Socrates: DOJ: 1 June 2015 | Subjects: Philosophy, Moral Science | Salary: 11.5 LPA in hand | Also takes Web lectures."""
lines = a.split('\n')
months = {
    'Jan':1,
    'Feb':2,
    'Mar':3,
    'Apr':4,
    'May':5,
    'June':6,
    'July':7,
    'Aug':8,
    'Sept':9,
    'Oct':10,
    'Nov':11,
    'Dec':12
}
for line in lines:
    if not line:
        continue
    all_entities = line.split(' | ')
    nameAndDoj = all_entities[0].split(': ')
    name = nameAndDoj[0]
    Doj = nameAndDoj[2]
    dArr = Doj.split(' ')
    dArr[1] = months[dArr[1]]
    date = datetime.date(int(dArr[2]), dArr[1], int(dArr[0]))
    subjects = all_entities[1]
    subjects = subjects.split(': ')[1]
    salary = all_entities[2]
    salary = salary.split(': ')[1]
    if len(all_entities) > 3:
        web_lecture_capability = 'yes'
    else:
        web_lecture_capability = 'no'
    # print('{} {} {} {} {}'.format(name, date, subjects, salary, web_lecture_capability))
    print('{} {} {}'.format(subjects, name, salary))


import asyncio
import time
from contextlib import asynccontextmanager

@asynccontextmanager
async def normalize_timing(min_seconds: float):
    """Wrap code with this context to ensure that the code takes at least the
    provided `min_seconds` to execute. This is primarily helpful to prevent
    timing based login scraping.

    :param float min_seconds: The minimum number of seconds this code is allowed
        to take to execute.
    """
    start = time.perf_counter()

    try:
        yield

    finally:
        end = time.perf_counter()
        elapsed = end - start

        # Sleep to ensure short code execution time is hidden
        if elapsed < min_seconds:
            await asyncio.sleep(min_seconds - elapsed)


from eval_utils import process_results, load_score_t5
from multitask_info import target2source_all, target2source_roe, target2source_llm, target2source_taskshop, target2source_taskweb

if __name__ == "__main__":

    # list of all target tasks and random seeds
    task_list = ["anli_r1", "anli_r2", "anli_r3", "cb", "copa", "hellaswag", "rte", "story_cloze", "wic", "winogrande", "wsc"]
    seed_list = [15, 30, 42]

    # T5-3B zero-shot evaluation results with all tasks except target task
    process_results(task_list, load_score_t5, multitask_dict=target2source_all, result_name="T5-XL all", seed_list=seed_list)

    # T5-3B zero-shot evaluation results with Retrieval-of-Experts (RoE)
    process_results(task_list, load_score_t5, multitask_dict=target2source_roe, result_name="T5-XL RoE", seed_list=seed_list)

    # T5-3B zero-shot evaluation results with LLM similarity scores (LLM)
    process_results(task_list ,load_score_t5 , multitask_dict=target2source_llm, result_name="T5-XL LLM", seed_list=seed_list)

    # T5-3B zero-shot evaluation results with TaskShop
    process_results(task_list, load_score_t5, multitask_dict=target2source_taskshop, result_name="T5-XL TaskShop", seed_list=seed_list)

    # T5-3B zero-shot evaluation results with TaskWeb
    process_results(task_list, load_score_t5, multitask_dict=target2source_taskweb, result_name="T5-XL TaskWeb", seed_list=seed_list)


from tkinter import *
from tkinter import ttk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from data_loader import adddata_fe, getheaders_fe
import customplot
from tkinter import messagebox

font_1 = ("Times", 20, "bold")
font_2 = ("Times", 15)
font_3 = ("Times", 10)

###############################################
################ Global Variables ##############

datasets_global_var = list()
plots_global_var = dict()
plots_global_var_keys = list()
options_datasets = list()
merged_list = list()

options_plottypes = ['Line Plot','Scatter Plot','Histogram','Bar Plot']
options_color = ['blue','red','green','orange','cyan','black','purple']
options_plotids = list()
options_axis = list()
options_markers = ['red x', 'red .', 'blue x', 'blue .', 'green x', 'green .']

###############################################
#options_datasets = ['NONE','0','yhadhfasfigaushiuyq3e324eui32y489234g1','2','2','3']
#options_plottypes = ['NONE','Line Plot','Scatter Plot','Histogram','Bar Plot']
#options_axis = ['NONE','ColA','ColB','ColC']
#options_color = ['NONE','Blue','Red','Green','Orange','Violet','Black']
#options_plotids = ['NONE','Plot Name 1','Plot Name 2','Plot Name 3','Plot Name 4']
#options_markers = ['NONE','Red Cross','Red Dot','Blue Cross','Blue Dot','Green Cross','Green Dot']
root = Tk()

#####################################################################
#################### Variables in global scope #######################
clicked_option_data = StringVar()

clicked_option_plottype = StringVar()

clicked_option_xaxis = StringVar()

clicked_option_yaxis = StringVar()

clicked_option_color = StringVar()

clicked_option_plotid = StringVar()
clicked_option_plotid_m = StringVar()

clicked_option_marker = StringVar()

label_x_str = StringVar()
label_x_str.set('NONE')

label_y_str = StringVar()
label_y_str.set('NONE')

title_str = StringVar()
title_str.set('NONE')

clicked_option_marker_2 = StringVar()
clicked_option_marker_2.set('.')

marker_value = IntVar()
marker_value.set(0)

annot_value = IntVar()
annot_value.set(0)

scaling_x_m = DoubleVar()
scaling_x_m.set(1.0)

scaling_x_b = DoubleVar()
scaling_x_b.set(0.0)

scaling_y_m = DoubleVar()
scaling_y_m.set(1.0)

scaling_y_b = DoubleVar()
scaling_y_b.set(0.0)

global_listbox_index = 0

# create frame style
style1 = ttk.Style()
style1.configure('new.TFrame', background="#132020")

style2 = ttk.Style()
style2.configure('outer.TFrame', background="#091010")

style3 = ttk.Style()
style3.configure('sidebar.TFrame', background="#263f3f")

#style4 = ttk.Style()
#style4.configure('new.TEntry', insertbackground="black", foreground = "red",fieldbackground="black")

style5 = ttk.Style()
style5.configure("new.TCheckbutton", background="#263f3f",foreground = "#FFFFFF")
style5.configure("new.TMenubutton", background="#132020",foreground = "#FFFFFF")
style5.configure("side.TMenubutton", background="#263f3f",foreground = "#FFFFFF")

#####################################################################
root.title("tk.DataViz")
root.configure(background='#091010')
mainframe = ttk.Frame(root, padding="5",style='outer.TFrame')
mainframe.grid(column=0, row=0)
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

#################### Main frame ########################

lbl_title = Label(mainframe, text = "tk.DataViZ", font = font_1,bg = "#091010",fg = "#FFFFFF")
lbl_title.grid(row = 0, column = 0)

dataloader_frame = ttk.Frame(mainframe, padding="5",borderwidth = '5',relief = 'sunken',style='new.TFrame')
dataloader_frame.grid(row = 0, column = 1, pady = 10, padx = 10)

optionsel_frame = ttk.Frame(mainframe, padding="5",borderwidth = '5',relief = 'sunken',style='new.TFrame')
optionsel_frame.grid(row = 0, column = 2,pady = 10, padx = 10)

plot_frame = ttk.Frame(mainframe, padding="5",borderwidth = '5',relief = 'sunken',style='new.TFrame')
plot_frame.grid(row = 1, column = 0,pady = 10, padx = 10,columnspan = 2)

sidebar_frame = ttk.Frame(mainframe, padding="5",borderwidth = '5',relief = 'sunken',style='new.TFrame')
sidebar_frame.grid(row = 1, column = 2,pady = 10, padx = 10)

mainframe.columnconfigure(0, weight=2)
mainframe.columnconfigure(1, weight=1)
mainframe.columnconfigure(2, weight=3)

mainframe.rowconfigure(0, weight = 1)
mainframe.rowconfigure(1, weight = 3)
########################################################################

#################### data loader frame ########################
lb2 = Label(dataloader_frame, text = "Add The Dataset (CSV)", font = font_2,bg = "#132020",fg = "#FFFFFF")
lb2.grid(row = 0, column = 0)

def adddata_fi():
    global datasets_global_var, options_datasets,drop_down_data
    datasets_global_var, options_datasets = adddata_fe(datasets_global_var, options_datasets)
    drop_down_data = ttk.OptionMenu(dataloader_frame, clicked_option_data, 'NONE', style = "new.TMenubutton",*options_datasets)
    drop_down_data.config(width=20)
    drop_down_data.grid(row=0, column=2, pady=10)
    drop_down_data['menu'].configure(background="#132020",foreground = "#FFFFFF")

btn_adddata = Button(dataloader_frame, text = 'ADD',command = adddata_fi,background = 'green',foreground = '#FFFFFF',width = 10)
btn_adddata.grid(row = 1, column = 0)

lb2 = Label(dataloader_frame, text = "Dataset:-", font = font_2,bg = "#132020",fg = "#FFFFFF")
lb2.grid(row = 0, column = 1, pady = 10, padx = 20)

drop_down_data = ttk.OptionMenu(dataloader_frame, clicked_option_data, 'NONE',style = "new.TMenubutton",*options_datasets)
drop_down_data.config(width = 20)
drop_down_data.grid(row = 0, column = 2, pady = 10)
drop_down_data['menu'].configure(background="#132020",foreground = "#FFFFFF")

def proceed_fi():
    global options_axis,datasets_global_var
    ind_dataset = options_datasets.index(clicked_option_data.get())
    options_axis = getheaders_fe(ind_dataset,datasets_global_var)

    drop_down_xaxis = ttk.OptionMenu(optionsel_frame, clicked_option_xaxis, 'NONE', style = "new.TMenubutton",*options_axis)
    drop_down_xaxis.config(width=12)
    drop_down_xaxis.grid(row=0, column=3, padx=(3, 20))
    drop_down_xaxis['menu'].configure(background="#132020",foreground = "#FFFFFF")

    drop_down_yaxis = ttk.OptionMenu(optionsel_frame, clicked_option_yaxis, 'NONE', style = "new.TMenubutton",*options_axis)
    drop_down_yaxis.config(width=12)
    drop_down_yaxis.grid(row=0, column=5, padx=(3, 20))
    drop_down_yaxis['menu'].configure(background="#132020",foreground = "#FFFFFF")

btn_proceed = Button(dataloader_frame, text = 'Proceed',command = proceed_fi,background = 'green',foreground = '#FFFFFF',width = 10)
btn_proceed.grid(row = 1, column = 1, columnspan = 2)
###############################################################

#################### Option Selector frame ########################

# Row 0
lb3 = Label(optionsel_frame, text = "Plot Type:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb3.grid(row = 0, column = 0)

drop_down_plottype = ttk.OptionMenu(optionsel_frame, clicked_option_plottype, 'NONE', style = "new.TMenubutton",*options_plottypes)
drop_down_plottype.config(width = 12)
drop_down_plottype.grid(row = 0, column = 1, padx = (3,20))
drop_down_plottype['menu'].configure(background="#132020",foreground = "#FFFFFF")

lb4 = Label(optionsel_frame, text = "X-Axis:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb4.grid(row = 0, column = 2)

drop_down_xaxis = ttk.OptionMenu(optionsel_frame, clicked_option_xaxis, 'NONE', style = "new.TMenubutton",*options_axis)
drop_down_xaxis.config(width = 12)
drop_down_xaxis.grid(row = 0, column = 3, padx = (3,20))
drop_down_xaxis['menu'].configure(background="#132020",foreground = "#FFFFFF")

lb5 = Label(optionsel_frame, text = "Y-Axis:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb5.grid(row = 0, column = 4,sticky = 'W')

drop_down_yaxis = ttk.OptionMenu(optionsel_frame, clicked_option_yaxis, 'NONE',style = "new.TMenubutton",*options_axis)
drop_down_yaxis.config(width = 12)
drop_down_yaxis.grid(row = 0, column = 5, padx = (3,20))
drop_down_yaxis['menu'].configure(background="#132020",foreground = "#FFFFFF")

lb6 = Label(optionsel_frame, text = "Color:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb6.grid(row = 0, column = 6)

drop_down_color = ttk.OptionMenu(optionsel_frame, clicked_option_color, 'NONE',style = "new.TMenubutton",*options_color)
drop_down_color.config(width = 12)
drop_down_color.grid(row = 0, column = 7, padx = (3,20))
drop_down_color['menu'].configure(background="#132020",foreground = "#FFFFFF")

# Row 1

lb7 = Label(optionsel_frame, text = "Label X:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb7.grid(row = 1, column = 0,sticky = 'W')

label_x_w = Entry(optionsel_frame,textvariable = label_x_str, font=font_3,background = "#091010",foreground = '#FFFFFF')
label_x_w.grid(row = 1, column = 1,sticky = 'W', padx = (3,20))

lb8 = Label(optionsel_frame, text = "Label y:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb8.grid(row = 1, column = 2,sticky = 'W')

label_y_w = Entry(optionsel_frame,textvariable = label_y_str, font=font_3,background = "#091010",foreground = '#FFFFFF')
label_y_w.grid(row = 1, column = 3,sticky = 'W', padx = (3,20))

lb9 = Label(optionsel_frame, text = "Title of Plot:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb9.grid(row = 1, column = 4,sticky = 'W')

title_w = Entry(optionsel_frame,textvariable = title_str, font=font_3,background = "#091010",foreground = '#FFFFFF')
title_w.grid(row = 1, column = 5,sticky = 'W', padx = (3,20))

lb9_11 = Label(optionsel_frame, text = "Marker:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb9_11.grid(row = 1, column = 6,sticky = 'W')

options_markers_2 = ['.','x','+','o','^','v','s','*']

drop_down_markers_2 = ttk.OptionMenu(optionsel_frame, clicked_option_marker_2, '.', style = "new.TMenubutton",*options_markers_2)
drop_down_markers_2.config(width = 12)
drop_down_markers_2.grid(row = 1, column = 7,sticky = 'W', pady = (3,20))
drop_down_markers_2['menu'].configure(background="#132020",foreground = "#FFFFFF")
# Row 2

def addplot_fi():
    global plots_global_var,options_plotids,global_listbox_index,plots_global_var_keys

    plot_t_new = title_str.get()
    if plot_t_new == 'NONE':
        messagebox.showwarning("showwarning", "You can't set the plot title as NONE. Please try any valid title")
        return 0

    if plot_t_new in plots_global_var_keys:
        messagebox.showwarning("showwarning", "Title already exists. Please try any other title.")
        return 0

    new_plot = customplot.customplot(
        clicked_option_color.get(),
        datasets_global_var[options_datasets.index(clicked_option_data.get())][clicked_option_xaxis.get()],
        datasets_global_var[options_datasets.index(clicked_option_data.get())][clicked_option_yaxis.get()],
        label_x_str.get(),
        label_y_str.get(),
        title_str.get(),
        clicked_option_plottype.get(),
        plot_frame,
        scaling_x_m.get(),
        scaling_y_m.get(),
        scaling_x_b.get(),
        scaling_y_b.get(),
        clicked_option_marker_2.get()
    )
    plots_global_var[title_str.get()] = new_plot
    options_plotids.append(title_str.get())
    plots_global_var_keys.append(title_str.get())

    drop_down_plotids = ttk.OptionMenu(sidebar_frame_1, clicked_option_plotid, 'NONE', style = "side.TMenubutton",*options_plotids)
    drop_down_plotids.config(width=20)
    drop_down_plotids.grid(row=0, column=1, pady=(3, 20), padx=(5, 5))
    drop_down_plotids['menu'].configure(background="#263f3f",foreground = "#FFFFFF")

    drop_down_plotids_m = ttk.OptionMenu(sidebar_frame_1, clicked_option_plotid_m, 'NONE', style = "side.TMenubutton",*options_plotids)
    drop_down_plotids_m.config(width = 20)
    drop_down_plotids_m.grid(row = 0, column = 2, pady = (3,20),padx = (5,5),columnspan = 2)
    drop_down_plotids_m['menu'].configure(background="#263f3f",foreground = "#FFFFFF")

    string_listbox = str(global_listbox_index) + ".    " +title_str.get() + "      " + clicked_option_xaxis.get() + "     " + clicked_option_yaxis.get() + "    " + clicked_option_color.get()

    listbox_1.insert(global_listbox_index,string_listbox)
    global_listbox_index = global_listbox_index + 1

def updateplot_fi():
    curr_plot = plots_global_var[clicked_option_plotid.get()]
    curr_plot.updatedata(
        clicked_option_color.get(),
        datasets_global_var[options_datasets.index(clicked_option_data.get())][clicked_option_xaxis.get()],
        datasets_global_var[options_datasets.index(clicked_option_data.get())][clicked_option_yaxis.get()],
        label_x_str.get(),
        label_y_str.get(),
        title_str.get(),
        clicked_option_plottype.get(),
        scaling_x_m.get(),
        scaling_y_m.get(),
        scaling_x_b.get(),
        scaling_y_b.get(),
        clicked_option_marker_2.get()
    )
    index_of_plot_in_listbox = plots_global_var_keys.index(title_str.get())
    listbox_1.delete(index_of_plot_in_listbox)
    string_listbox = str(index_of_plot_in_listbox) + ".    " +title_str.get() + "      " + clicked_option_xaxis.get() + "     " + clicked_option_yaxis.get() + "    " + clicked_option_color.get()
    listbox_1.insert(index_of_plot_in_listbox,string_listbox)

lb_x_m = Label(optionsel_frame, text = "X scaling factor:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb_x_m.grid(row = 2, column = 0,sticky = 'W')

en_x_m = Entry(optionsel_frame,textvariable = scaling_x_m, font=font_3,background = "#091010",foreground = '#FFFFFF')
en_x_m.grid(row = 2, column = 1,sticky = 'W', padx = (3,20))

lb_x_b = Label(optionsel_frame, text = "X Bias:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb_x_b.grid(row = 2, column = 2,sticky = 'W')

en_x_b = Entry(optionsel_frame,textvariable = scaling_x_b, font=font_3,background = "#091010",foreground = '#FFFFFF')
en_x_b.grid(row = 2, column = 3,sticky = 'W', padx = (3,20))

lb_y_m = Label(optionsel_frame, text = "Y scaling factor:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb_y_m.grid(row = 2, column = 4,sticky = 'W')

en_y_m = Entry(optionsel_frame,textvariable = scaling_y_m, font=font_3,background = "#091010",foreground = '#FFFFFF')
en_y_m.grid(row = 2, column = 5,sticky = 'W', padx = (3,20))

lb_y_b = Label(optionsel_frame, text = "Y Bias:", font = font_3,bg = "#132020",fg = "#FFFFFF")
lb_y_b.grid(row = 2, column = 6,sticky = 'W')

en_y_b = Entry(optionsel_frame,textvariable = scaling_y_b, font=font_3,background = "#091010",foreground = '#FFFFFF')
en_y_b.grid(row = 2, column = 7,sticky = 'W', padx = (3,20))

btn_add_plot = Button(optionsel_frame, text = 'Add New Plot',command = addplot_fi,background = 'blue',foreground = '#FFFFFF',width = 15)
btn_add_plot.grid(row = 3, column = 0, columnspan = 4,pady=(15,3))

btn_update_plot = Button(optionsel_frame, text = 'Update Existing Plot',command = updateplot_fi,background = 'red',foreground = '#FFFFFF',width = 15)
btn_update_plot.grid(row = 3, column = 4, columnspan = 4,pady=(15,3))

###############################################################

#################### Plot frame ########################

fig = Figure(figsize=(7, 6), dpi=100)
plot1 = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig,master = plot_frame)
canvas.draw()
canvas.get_tk_widget().grid(row = 0, column = 0)

#toolbarFrame = ttk.Frame(master=plot_frame)
#toolbarFrame.grid(row=2,column=0)
#toolbar = NavigationToolbar2Tk(canvas, toolbarFrame)
#toolbar.update()

###############################################################

#################### Sidebar frame ########################

sidebar_frame_1 = ttk.Frame(sidebar_frame, padding="5",borderwidth = '5',relief = 'sunken',style='sidebar.TFrame')
sidebar_frame_1.grid(row = 0, column = 0,pady = 10, padx = 10)

sidebar_frame_2 = ttk.Frame(sidebar_frame, padding="5",borderwidth = '5',relief = 'sunken',style='sidebar.TFrame')
sidebar_frame_2.grid(row = 1, column = 0,pady = 10, padx = 10)

sidebar_frame_3 = ttk.Frame(sidebar_frame, padding="5",borderwidth = '5',relief = 'sunken',style='sidebar.TFrame')
sidebar_frame_3.grid(row = 2, column = 0,pady = 10, padx = 10)

lb10 = Label(sidebar_frame_1, text = "Select Plot to show:", font = font_3,bg = "#263f3f",fg = "#FFFFFF")
lb10.grid(row = 0, column = 0,sticky = 'W', pady = (3,20))

drop_down_plotids = ttk.OptionMenu(sidebar_frame_1, clicked_option_plotid, 'NONE', style = "side.TMenubutton",*options_plotids)
drop_down_plotids.config(width = 20)
drop_down_plotids.grid(row = 0, column = 1, pady = (3,20),padx = (5,5))
drop_down_plotids['menu'].configure(background="#263f3f",foreground = "#FFFFFF")

drop_down_plotids_m = ttk.OptionMenu(sidebar_frame_1, clicked_option_plotid_m, 'NONE', style = "side.TMenubutton",*options_plotids)
drop_down_plotids_m.config(width = 20)
drop_down_plotids_m.grid(row = 0, column = 2, pady = (3,20),padx = (5,5), columnspan = 2)
drop_down_plotids_m['menu'].configure(background="#263f3f",foreground = "#FFFFFF")

def change_subplotopts(aa):
    options_cursubplots = [i for i in range(clicked_option_totsubplots.get())]
    drop_down_cursubplot = ttk.OptionMenu(sidebar_frame_1, clicked_option_cursubplots, 0, style = "side.TMenubutton",*options_cursubplots)
    drop_down_cursubplot.config(width=20)
    drop_down_cursubplot.grid(row=1, column=3, pady=(3, 20), padx=(5, 5))
    drop_down_cursubplot['menu'].configure(background="#263f3f",foreground = "#FFFFFF")

lb20 = Label(sidebar_frame_1, text = "Total Subplots:", font = font_3,bg = "#263f3f",fg = "#FFFFFF")
lb20.grid(row = 1, column = 0,sticky = 'W', pady = (3,20))

lb21 = Label(sidebar_frame_1, text = "Current Subplot:", font = font_3,bg = "#263f3f",fg = "#FFFFFF")
lb21.grid(row = 1, column = 2,sticky = 'W', pady = (3,20))

options_totsubplots = [1,2,3,4,6,8,9]
clicked_option_totsubplots = IntVar()
clicked_option_totsubplots.set(1)

drop_down_totsuplots = ttk.OptionMenu(sidebar_frame_1, clicked_option_totsubplots, 1,command=change_subplotopts, style = "side.TMenubutton",*options_totsubplots)
drop_down_totsuplots.config(width = 20)
drop_down_totsuplots.grid(row = 1, column = 1, pady = (3,20),padx = (5,5))
drop_down_totsuplots['menu'].configure(background="#263f3f",foreground = "#FFFFFF")

options_cursubplots = [i for i in range(clicked_option_totsubplots.get())]
clicked_option_cursubplots = IntVar()
clicked_option_cursubplots.set(0)

drop_down_cursubplot = ttk.OptionMenu(sidebar_frame_1, clicked_option_cursubplots, 0, style = "side.TMenubutton",*options_cursubplots)
drop_down_cursubplot.config(width = 20)
drop_down_cursubplot.grid(row = 1, column = 3, pady = (3,20),padx = (5,5))
drop_down_cursubplot['menu'].configure(background="#263f3f",foreground = "#FFFFFF")

def showplot_fi():
    curr_plot = plots_global_var[clicked_option_plotid.get()]
    global merged_list
    merged_list.insert(clicked_option_cursubplots.get(),[curr_plot])
    #print(curr_plot.getdata())
    ################################## Universal Marker #####################
    try:
        marker_fi()
        annote_fi()
    except:
        log_showplot_fi = 1
    #print(merged_list)
    try:
        curr_plot.plotdata(merged_list,clicked_option_totsubplots.get())
    except:
        messagebox.showerror("showerror", "Please clear the plot before displaying another plot")
    response = curr_plot.getdata()
    clicked_option_color.set(response['color'])
    clicked_option_xaxis.set(response['dataX'])
    clicked_option_yaxis.set(response['dataY'])
    label_x_str.set(response['x_name'])
    label_y_str.set(response['y_name'])
    title_str.set(response['title'])
    clicked_option_plottype.set(response['plot_type'])
    scaling_x_m.set(response['x_m'])
    scaling_y_m.set(response['y_m'])
    scaling_x_b.set(response['x_b'])
    scaling_y_b.set(response['y_b'])
    clicked_option_marker_2.set(response['Marker_2'])

def mergeplot_fi():
    global merged_list
    curr_plot = plots_global_var[clicked_option_plotid.get()]
    merged_list[clicked_option_cursubplots.get()].append(plots_global_var[clicked_option_plotid_m.get()])
    try:
        curr_plot.plotdata(merged_list,clicked_option_totsubplots.get())
    except:
        messagebox.showerror("showerror", "Please clear the plot before displaying another plot")

def popout_fi():

    #fig = Figure(figsize=(7, 6), dpi=100)
    #plot1 = fig.add_subplot(111)
    #canvas = FigureCanvasTkAgg(fig, master=plot_frame_p)
    #canvas.draw()
    #canvas.get_tk_widget().grid(row=0, column=0)

    try:
        curr_plot2 = plots_global_var[clicked_option_plotid.get()]

        newWindow = Toplevel(root)
        newWindow.title("New Window")
        plot_frame_p = ttk.Frame(newWindow, padding="5", borderwidth='5', relief='sunken',style='new.TFrame')
        plot_frame_p.grid(row=1, column=0, pady=10, padx=10, columnspan=2)

        curr_plot2.updateFrame(plot_frame_p)
        curr_plot2.plotdata(merged_list,clicked_option_totsubplots.get())
        curr_plot2.reset_frame(plot_frame,merged_list,clicked_option_totsubplots.get())
    except:
        messagebox.showwarning("showwarning", "Please plot some data before popping up")

    #clear_plotsection()

def clear_plotsection():
    global  merged_list
    merged_list = list()
    fig = Figure(figsize=(7, 6), dpi=100)
    plot1 = fig.add_subplot(111)
    canvas = FigureCanvasTkAgg(fig, master=plot_frame)
    canvas.draw()
    canvas.get_tk_widget().grid(row=0, column=0)

btn_show_plot = Button(sidebar_frame_1, text = 'Show Plot',command = showplot_fi,background = 'green',foreground = '#FFFFFF',width = 10)
btn_show_plot.grid(row = 2, column = 0, pady=(15,3))

btn_merge_plot = Button(sidebar_frame_1, text = 'Merge Plot',command = mergeplot_fi,background = 'blue',foreground = '#FFFFFF',width = 10)
btn_merge_plot.grid(row = 2, column = 1, pady=(15,3))

btn_pop_out = Button(sidebar_frame_1, text = 'Pop Out',command = popout_fi,background = 'purple',foreground = '#FFFFFF',width = 10)
btn_pop_out.grid(row = 2, column = 2, pady=(15,3))

btn_clear_plot = Button(sidebar_frame_1, text = 'Clear Plot',command = clear_plotsection,background = 'red',foreground = '#FFFFFF',width = 10)
btn_clear_plot.grid(row = 2, column = 3, pady=(15,3))

lb11 = Label(sidebar_frame_2, text = "Marker:", font = font_3,bg = "#263f3f",fg = "#FFFFFF")
lb11.grid(row = 0, column = 0,sticky = 'W', pady = (3,20))

def change_marker_fi(choice):
    curr_plot = plots_global_var[clicked_option_plotid.get()]
    if marker_value.get()==1:
        (mc, mt) = choice.split(" ")
        status = curr_plot.setmarker(True,mc,mt)
        print(status)
        print(mc,mt)
    if marker_value.get()==0:
        (mc, mt) = clicked_option_marker.get().split(" ")
        curr_plot.setmarker(False, mc, mt)

drop_down_markers = ttk.OptionMenu(sidebar_frame_2, clicked_option_marker, 'NONE', style = "side.TMenubutton",*options_markers, command = change_marker_fi)
drop_down_markers.config(width = 15)
drop_down_markers.grid(row = 0, column = 1, pady = (3,20),padx = (5,5))
drop_down_markers['menu'].configure(background="#263f3f",foreground = "#FFFFFF")

def marker_fi():

    curr_plot = plots_global_var[clicked_option_plotid.get()]
    if marker_value.get()==1:
        (mc, mt) = clicked_option_marker.get().split(" ")
        status = curr_plot.setmarker(True,mc,mt)
        print(status)
        print(mc,mt)
    if marker_value.get()==0:
        (mc, mt) = clicked_option_marker.get().split(" ")
        curr_plot.setmarker(False, mc, mt)

C1 = ttk.Checkbutton(sidebar_frame_2, text = "ON", variable = marker_value,
                 onvalue = 1, offvalue = 0,command = marker_fi,style = 'new.TCheckbutton')
C1.grid(row = 0, column = 2, pady = (3,20),padx = (2,5))

def annote_fi():
    curr_plot = plots_global_var[clicked_option_plotid.get()]
    if annot_value.get() == 1:
        curr_plot.setannot(True)
    if annot_value.get() == 0:
        curr_plot.setannot(False)

lb12 = Label(sidebar_frame_2, text = "Annotations :", font = font_3,bg = "#263f3f",fg = "#FFFFFF")
lb12.grid(row = 1, column = 0,sticky = 'W', pady = (3,20))

C2 = ttk.Checkbutton(sidebar_frame_2, text = "ON", variable = annot_value,
                 onvalue = 1, offvalue = 0, command = annote_fi,style = 'new.TCheckbutton')
C2.grid(row = 1, column = 1, pady = (3,20),padx = (2,5))

def savepdf_fi():
    curr_plot = plots_global_var[clicked_option_plotid.get()]
    curr_plot.createpdf()

btn_save_pdf_1 = Button(sidebar_frame_2, text = 'Save PDF',command = savepdf_fi,background = 'green',foreground = '#FFFFFF',width = 15)
btn_save_pdf_1.grid(row = 1, column = 2, pady = (3,20),padx = (2,5))

listbox_1 = Listbox(sidebar_frame_3,width = 70,background = "#091010",foreground = '#FFFFFF')
listbox_1.grid(row = 0, column = 0, pady = (3,3), padx = (3,3))

###############################################################

root.mainloop()


import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import os

img_path = r"D:\Documents\cut"

def cut_center(image):
    print(f'裁剪之前的图片尺寸{image.shape}')
    # img.shape[0]：图像的垂直尺寸（高度）
    # img.shape[1]：图像的水平尺寸（宽度）
    cut_width_left = 300
    cut_width_right = 300
    origin_width = image.shape[1]
    origin_high = image.shape[0]
    # 裁剪坐标为[y0:y1, x0:x1]
    central_line_part = image[0:origin_high, origin_width//2-cut_width_left:origin_width//2+cut_width_right]
    return central_line_part

def get_images(img_path):
    images = []
    files = os.listdir(img_path)
    n = len(files)
    for _ in range(5):
        ind = np.random.randint(0, n)
        img_dir = os.path.join(img_path, files[ind])
        print(img_dir)
        img = cv.imread(img_dir)
        img = cut_center(img)
        images.append(img)
    return images
images = get_images(img_path)

plt.subplot(141), plt.imshow(images[0]), plt.title('img1')
plt.xticks([]), plt.yticks([])

plt.subplot(142), plt.imshow(images[1]), plt.title('img2')
plt.xticks([]), plt.yticks([])

plt.subplot(143), plt.imshow(images[2]), plt.title('img3')
plt.xticks([]), plt.yticks([])

plt.subplot(144), plt.imshow(images[3]), plt.title('img4')
plt.xticks([]), plt.yticks([])

plt.tight_layout()
plt.show()


import requests
import json
import os
from threading import Thread, Lock
from queue import Queue

class Spider():

    def __init__(self, mid, name):
        self.mid = mid
        self.name = name
        self.download_api = "http://211.152.148.26/amobile.music.tc.qq.com/"
        self.api = ["https://u.y.qq.com/cgi-bin/musicu.fcg?-=getUCGI38350760984660526&g_tk=1125629726&loginUin=1791670972&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0&data=%7B%22comm%22%3A%7B%22ct%22%3A24%2C%22cv%22%3A0%7D%2C%22singer%22%3A%7B%22method%22%3A%22get_singer_detail_info%22%2C%22param%22%3A%7B%22sort%22%3A5%2C%22singermid%22%3A%22","","%22%2C%22sin%22%3A","偏移量","%2C%22num%22%3A60%7D%2C%22module%22%3A%22music.web_singer_info_svr%22%7D%7D"]
        self.headers = {
            "Origin": "https://y.qq.com",
            "Referer": "https://y.qq.com/n/yqq/singer/%s.html" % self.mid,
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36"
        }
        self.music_api = ["http://u.y.qq.com/cgi-bin/musicu.fcg?-=getplaysongvkey2546320457778981&g_tk=1312345255&loginUin=1791670972&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0&data=%7B%22req%22%3A%7B%22module%22%3A%22CDN.SrfCdnDispatchServer%22%2C%22method%22%3A%22GetCdnDispatch%22%2C%22param%22%3A%7B%22guid%22%3A%226543954968%22%2C%22calltype%22%3A0%2C%22userip%22%3A%22%22%7D%7D%2C%22req_0%22%3A%7B%22module%22%3A%22vkey.GetVkeyServer%22%2C%22method%22%3A%22CgiGetVkey%22%2C%22param%22%3A%7B%22guid%22%3A%226543954968%22%2C%22songmid%22%3A%5B%22",'',"%22%5D%2C%22songtype%22%3A%5B0%5D%2C%22uin%22%3A%221791670972%22%2C%22loginflag%22%3A1%2C%22platform%22%3A%2220%22%7D%7D%2C%22comm%22%3A%7B%22uin%22%3A1791670972%2C%22format%22%3A%22json%22%2C%22ct%22%3A24%2C%22cv%22%3A0%7D%7D"]
        self.head = {
            'User-Agent':"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36"
            }

    def get_musics(self):
        self.api[1] = self.mid
        index = 0
        res = []
        while 1:
            self.api[3] = str(index * 60)
            index += 1
            print("已提取%d页" % index)
            url = "".join(self.api)
            response = requests.get(url, headers=self.headers)
            data = json.loads(response.text)
            # print(data)
            res.extend(data['singer']['data']['songlist'])
            if len(data['singer']['data']['songlist']) <= 55:
                break
        return res

    def del_with_data(self, data):
        res = []
        for i in data:
            singer = []
            for j in i['singer']:
                singer.append(j['name'])
            res.append({"name": i['name'], "singers": ",".join(singer), "mid": i['file']['media_mid']})
        return res

    def get_vkey(self, mid):
        self.music_api[1] = mid
        data_url = ''.join(self.music_api)
        try:
            data = json.loads(requests.get(data_url, timeout=10).text)
        except:
            # print("网络错误")
            # time.sleep(2)
            return 0
        vkey = data['req']['data']['vkey']
        return vkey

    def download(self, queue, num):
        while 1:
            mid, filename = queue.get()
            vkey = self.get_vkey(mid)
            # 判断vkey
            if not vkey:
                print("vkey获取失败", filename)
                queue.task_done()
                continue
            # 拼接URL
            mmid = "C400" + mid + ".m4a"
            # print(vkey)
            download_url = self.download_api + mmid + '?' + 'guid=6543954968&vkey=' + vkey + "&uin=1224&fromtag=6"
            # print(download_url)
            # 验证歌曲名称有效性
            try:
                data = requests.get(download_url, headers=self.head, timeout=10).content
            except:
                print("连接超时")
                queue.task_done()
                # time.sleep(1)
                continue

            size = len(data)
            if size < 1024:
                print(filename, "未知原因")
                num.put(1)
                queue.task_done()
                continue
            try:
                with open(os.path.join(self.name, "%s.m4a" % filename), 'wb+') as f:
                    f.write(data)
            except:
                print("歌曲名称含有非法字符：%s" % filename)
                # continue
            else:
                print("已下载：%s    %dk " % (filename, (size / 1024)))
                num.put(1)
            finally:
                # 释放队列元素
                queue.task_done()

    def run(self):
        print("提取歌曲数据")
        data = self.del_with_data(self.get_musics())
        total = len(data)
        print("数据提取完毕，共%d首歌曲" % total)
        total = len(data)
        print("开始下载")
        tasks = Queue()
        num = Queue()
        for i in range(32):
            t = Thread(target=self.download, args=(tasks, num))
            t.daemon = True
            t.start()
        if not os.path.exists(self.name):
            os.makedirs(self.name)
        # 创建任务
        for i in data:
            # print(i['mid'])
            tasks.put((i['mid'], i['name']))
        tasks.join()
        down_successfully = num.qsize()
        print("成功下载%d首" % down_successfully)
        print("%d首下载失败" % (total - down_successfully))

a = Spider("0025NhlN2yWrP4", "周杰伦")
a.run()


import os
if "nb_premier.txt" not in os.listdir():
    file = open("nb_premier.txt","w")
    file.close()
    nb_pr = [["2"]]
else :
    file = open("nb_premier.txt","r")
    c1 = file.read().split('\n')
    c = []
    for i in c1:
        c.append(i.split(':'))
    file.close()
    if c == [[""]] :
        nb_pr = [["2"]]
    else :
        nb_pr = c
print(nb_pr)
if nb_pr[-1] == ['']:
    del nb_pr[-1]
for i in range(int(nb_pr[-1][-1])+1,100000000000000000000):
    pr = 1
    for m in nb_pr:
        for j in m :
            if i%int(j) == 0 :
                pr = 0
    if pr == 1 :
        print(i,end='\r')
        if len(nb_pr[-1])%100 == 0 :
            nb_pr.append([str(i)])
        else :
            k = nb_pr[-1]
            k.append(str(i))
            nb_pr[-1] = k
        file = open("nb_premier.txt","w")
        for n in nb_pr:
            file.write(":".join(n))
            file.write('\n')
        file.close()
print(nb_pr)


from package_cleaning.erov import erov
#from erov import erov
import numpy as np
from package_cleaning.sumthr import sumthr
#from sumthr import sumthr

def launch_sumthr(x, p, med):
    # clean rows and columns separately
    print('in:')
    print(x.shape)
    x = np.transpose(x)
    p = np.transpose(p)
    print('proc:')
    print(x.shape)

    nt, nf = x.shape
    p1 = np.copy(p)
    p2 = np.copy(p)

    # columns  - VERTICAL
    M = [256]
    # M = [2, 8, 16, 128, 256]
    nm = len(M)
    thr = np.zeros(nm)
    for i in range(nm):
        thr[i] = 10./(1.5^(np.log2(M[i])))

    for i in range(nt):
        op, sx, mx = erov(x[i, ...])
        y = p2[i, ...]
        xx=((x[i, ...]) - mx) / sx
        for j in range(nm):
            out = sumthr(xx, M[j], thr[j], y)
            p2[i, ...]=out

    # rows  - HORIZONTAL
    # M = [1, 2, 4, 8, 64]
    M = [64]
    nm = len(M)
    thr = np.zeros(nm)
    for i in range(nm):
        thr[i] = 10./(1.5^(np.log2(M[i])))

    for i in range(nf):
        op, sx, mx = erov(x[..., i])
        y = p1[..., i]
        xx=((x[..., i]) - mx) / sx
        for j in range(nm):
            out = sumthr(xx, M[j], thr[j], y)
            p1[..., i] = out

    p = p1 * p2
    w = np.where(p == 0)[0]
    if w:
        x[w] = med

    x = np.transpose(x)
    p = np.transpose(p)

    print('out:')
    print(x.shape)
    print(p.shape)
    return p


#! /usr/bin/env python3

from lark import Lark

grammar =r"""
    variable : /[^()\n\s\.0-9][^()\n\s\.]*/

    expression : variable
        | abstraction
        | application

    abstraction : "(" "\\" variable "." expression ")"

    application : "(" expression expression ")"

    %import common.WS
    %ignore WS

 """

parser = Lark(grammar,start='expression')

def parse_file(path):
    with open(path,"r") as source_file:
        source = source_file.read()
    return parser.parse(source)

def parse_string(source):
    return parser.parse(source)

def test_file(path):
    tree = parse_file(path)
    print(tree.pretty())

def test_string(source):
    tree = parse_string(source)
    print(tree.pretty())

def interpreter():
    while(True):
        try :
            line = input("Lambda >> ")
        except (EOFError,KeyboardInterrupt) :
            break
        print("-> \n",end="")
        test_string(line)

if __name__ == '__main__':
    import sys
    if (len(sys.argv)>1):
        for path in sys.argv[1:]:
            test_file(path)
    else :
        interpreter()


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        # 双指针
        n = len(nums)
        nums.sort()
        res = float('inf')
        for i in range(n - 2):
            left, right = i + 1, n - 1
            while left < right:
                sumNum = nums[i] + nums[left] + nums[right]
                diff = abs(sumNum - target)
                if diff < abs(res - target):
                    res = sumNum

                if sumNum > target:
                    right -= 1
                elif sumNum < target:
                    left += 1
                else:
                    return target
        return res

src/链表/16.最接近的三数之和/16.最接近的三数之和.py

16.最接近的三数之和.py