import random
import sys
from tkinter.messagebox import QUESTION
import inquirer

words = open("words.txt", "r")
words_two = words.read()
word_bank = words_two.split()
hell = []
str = ' '
WRONG = []
past_guesses = []
difficulty = [
    inquirer.List('mode',
    message = "Choose Your Difficulty",
    choices = ['Hell','Hard','Medium','Soft']
    )
]

play_again = [
    inquirer.List('play',
    message= "Wanna Go Again?",
    choices = ['Yeah!','Nah...']
    )
]

def choose_difficulty():
    answers = inquirer.prompt(difficulty)
    if 'Hard' in answers.values():
        guess_me = random.choice(word_bank)
        while len(guess_me) < 8:
            guess_me = random.choice(word_bank)
        print("Hard Mode Selected")
        return board_maker(guess_me)
    if 'Medium' in answers.values():
            guess_me = random.choice(word_bank)
            while len(guess_me) < 6 or len(guess_me) > 8:
                guess_me = random.choice(word_bank)
            print("Medium Mode Selected")
            return board_maker(guess_me)
    if 'Soft' in answers.values():
            guess_me = random.choice(word_bank)
            while len(guess_me) > 6:
                guess_me = random.choice(word_bank)
            print("Soft Mode Selected")
            return board_maker(guess_me)
    if 'Hell' in answers.values():
            guess_me = random.choice(word_bank)
            breaker = list(guess_me)
            new_board = "_" * len(breaker)
            scoreboard = list(new_board)
            hell.append("hell")
            print("Heaven or Hell Let's Rock")
            return play_game(scoreboard, breaker)

def board_maker(guess_me):
    breaker = list(guess_me)
    new_board = "_" * len(breaker)
    scoreboard = list(new_board)
    return play_game(scoreboard, breaker)

def play_game(scoreboard, breaker):
    if len(WRONG) == 8:
        print(f"\nLOSER!\nThe Word Was: {''.join(breaker)}\n")
        mulligan = inquirer.prompt(play_again)
        if 'Nah...' in mulligan.values():
            sys.exit(0)
        else:
            WRONG.clear()
            hell.clear()
            past_guesses.clear()
            choose_difficulty()
    if scoreboard == breaker:
        print(f"'\n',{''.join(breaker)}\nYOU WIN!")
        mulligan = inquirer.prompt(play_again)
        if 'Nah...' in mulligan.values():
            sys.exit(0)
        else:
            WRONG.clear()
            hell.clear()
            past_guesses.clear()
            choose_difficulty()

    else:
        print(f"{str.join(scoreboard)} \n GUESS ME!")
        guess = input("Pick A Letter: ").lower()
        if not guess.isalpha():
            print("Letters only!")
            play_game(scoreboard, breaker)
        elif len(guess) > 1:
            print("One at a time buddy.")
            play_game(scoreboard, breaker)
        elif guess in past_guesses:
            print("You Already Tried That...")
            play_game(scoreboard, breaker)
        elif guess in breaker:
            print("good guess!")
            past_guesses.append(guess)
            for correct in range(len(breaker)):
                if breaker[correct] == guess:
                    scoreboard[correct] = breaker[correct]
            play_game(scoreboard, breaker)
        elif guess not in breaker:
            past_guesses.append(guess)
            WRONG.append("X")
            print("\nwrong, dumbass\n","X" * len(WRONG),"\n",f'{8 - len(WRONG)} {"guess" if 8 - len(WRONG) == 1 else "guesses"} left!')
            if "hell" in hell and len(WRONG) != 8:
                past_guesses.clear()
                hell_game()
            play_game(scoreboard, breaker)

def hell_game():
    guess_me = random.choice(word_bank)
    breaker = list(guess_me)
    new_board = "_" * len(breaker)
    scoreboard = list(new_board)
    print("\nThe Hell Continues")
    return play_game(scoreboard, breaker)

if __name__ == "__main__":
    choose_difficulty()


import datetime
import os
import win32com.client

###### O Path nao pode conter acentuacao ou cedilha

path = ''

###### Caso queira salvar em uma das pastas do usuario logado como desktop, documentos etc...

# path = os.path.expanduser('~/Desktop/arquivos')

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

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

######## Caso Tenha mais de um arquivo PST ########

#email = outlook.Folders['guilherme@cairotecnologia.com.br']
#inbox = email.Folders[0]
############################################

inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
first = messages.GetFirst()

######## Aqui seria para criar uma pasta dentro do path pra organizar pelo Ano dos anexos ########
#if not os.path.exists(path+"/Certificado "+str(first.ReceivedTime.date().year)):
#    os.mkdir(path+"/Certificado "+str(first.ReceivedTime.date().year))

#path = path+"/Certificado "+str(first.ReceivedTime.date().year)

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

#attachments = first.Attachments

#attachment = attachments.Item(1)

for attachment in first.Attachments:
    attachment.SaveAsFile(os.path.join(path, str(attachment)))


import os
import sys
from math import exp, log, sqrt

from iris_validation import clipper
from iris_validation.utils import ATOMIC_NUMBERS, MC_ATOM_NAMES, norm_cdf

class ReflectionsHandler(object):
    def __init__(self, f_reflections=None, xmap=None, minimol=None):
        self.f_reflections = f_reflections
        self.xmap = xmap
        self.minimol = minimol

        self.hkl = clipper.HKL_info()

        self.grid = None
        self.spacegroup = None
        self.cell = None
        self.resolution = None
        self.resolution_limit = None

        if f_reflections is None:
            if xmap is None:
                print('ERROR: either a reflections file path or an xmap object must be passed as an argument')
                raise Exception('ArgumentError')
            try:
                self.grid = xmap.grid
            except AttributeError:
                self.grid = None
            self.spacegroup = xmap.spacegroup
            self.cell = xmap.cell
        else:
            extension = f_reflections.split('.')[-1].lower()
            if extension != 'mtz':
                if extension == 'cif':
                    print('ERROR: mmCIF format is not currently supported for reflections data.')
                else:
                    print('ERROR: reflections file has unrecognised extension:' + extension)
                raise Exception('ExtensionError')
            self._load_hkl_data()
            self._calculate_structure_factors()
            self._generate_xmap()
            self._calculate_map_stats()

    def _load_hkl_data(self):
        mtzin = clipper.CCP4MTZfile()
        mtzin.open_read(self.f_reflections)
        mtzin.import_hkl_info(self.hkl)

        if clipper.mode == 0:
            mtz_labels_and_types = [ tuple(str(line).strip().split(' ')) for line in mtzin.column_labels() ]
        elif clipper.mode == 1:
            mtz_labels_and_types = [ tuple(str(line).strip().split(' ')) for line in mtzin.column_labels ]
        mtz_column_labels, mtz_column_types = zip(*mtz_labels_and_types)
        mtz_column_label_suffixes = set([ label.split('/')[-1] for label in mtz_column_labels ])
        # Need a better way to choose the right headers, but I'm not familiar enough with reflections data to know what labels are common
        import_complete = False
        for suffix_pair in ( ('F', 'SIGF'),
                             ('FP', 'SIGFP'),
                             ('FP_ALL', 'SIGFP_ALL') ):
            if len(mtz_column_label_suffixes & set(suffix_pair)) == 2:
                try:
                    self.f_sigf = clipper.HKL_data_F_sigF_float(self.hkl)
                    mtzin.import_hkl_data(self.f_sigf, '/*/*/[' + ','.join(suffix_pair) + ']')
                    import_complete = True
                    break
                except Exception as e:
                    print('ERROR: failed to import HKL data from reflections file')
                    raise(e)
        if not import_complete:
            print('ERROR: reflections file does not contain the required columns')
            raise Exception('ColumnError')
        mtzin.close_read()

        if clipper.mode == 0:
            spacegroup = self.hkl.spacegroup()
            cell = self.hkl.cell()
            resolution = self.hkl.resolution()
        elif clipper.mode == 1:
            spacegroup = self.hkl.spacegroup
            cell = self.hkl.cell
            resolution = self.hkl.resolution

        self.spacegroup = spacegroup
        self.cell = cell
        self.resolution = resolution
        self.resolution_limit = self.resolution.limit()

    def _calculate_structure_factors(self, bulk_solvent=True):
        #self.crystal = clipper.MTZcrystal()
        #self.f_phi = clipper.HKL_data_F_phi_float(self.hkl, self.crystal)
        self.f_phi = clipper.HKL_data_F_phi_float(self.hkl)
        atoms = self.minimol.atom_list()
        sf_calc = clipper.SFcalc_obs_bulk_float if bulk_solvent else clipper.SFcalc_obs_base_float
        sf_calc(self.f_phi, self.f_sigf, atoms)

    def _generate_xmap(self):
        self.grid = clipper.Grid_sampling(self.spacegroup, self.cell, self.resolution)
        self.xmap = clipper.Xmap_float(self.spacegroup, self.cell, self.grid)
        try:
            self.xmap.fft_from(self.f_phi)
        except AttributeError:
            self.xmap.fft_from_float(self.f_phi)

    def _calculate_map_stats(self):
        map_stats = clipper.Map_stats(self.xmap)
        self.map_mean = map_stats.mean()
        self.map_std = map_stats.std_dev()

    def get_density_at_point(self, xyz):
        if clipper.mode == 0:
            cell = self.xmap.cell()
            grid = self.xmap.grid_sampling()
        elif clipper.mode == 1:
            cell = self.xmap.cell
            grid = self.xmap.grid_sampling
        co = clipper.Coord_orth(*xyz)
        co_cf_cg = co.coord_frac(cell).coord_grid(grid)
        density = self.xmap.get_data(co_cf_cg)
        return density

    def get_density_at_atom(self, mmol_atom):
        if clipper.mode == 0:
            co = mmol_atom.coord_orth()
            xyz = (co.x(), co.y(), co.z())
        elif clipper.mode == 1:
            xyz = mmol_atom.coord
        return self.get_density_at_point(xyz)

    def get_density_scores_at_residue(self, metrics_residue):
        all_atom_scores, mainchain_atom_scores, sidechain_atom_scores = [ ], [ ], [ ]
        for atom_id, atom in enumerate(metrics_residue.minimol_residue):
            is_mainchain = str(atom.name()).strip() in MC_ATOM_NAMES
            if clipper.mode == 0:
                element = str(atom.element()).strip()
            elif clipper.mode == 1:
                element = atom.element.strip()
            atomic_number = ATOMIC_NUMBERS[element]
            density = self.get_density_at_atom(atom)
            atom_score = None
            density_norm = density / atomic_number
            atom_score = -log(norm_cdf((density_norm - self.map_mean) / self.map_std))
            all_atom_scores.append(atom_score)
            if is_mainchain:
                mainchain_atom_scores.append(atom_score)
            else:
                sidechain_atom_scores.append(atom_score)
        all_score, mainchain_score, sidechain_score = None, None, None
        if len(all_atom_scores) > 0:
            all_score = sum(all_atom_scores) / len(all_atom_scores)
        if metrics_residue.is_aa:
            if len(mainchain_atom_scores) > 0:
                mainchain_score = sum(mainchain_atom_scores) / len(mainchain_atom_scores)
            if len(sidechain_atom_scores) > 0:
                sidechain_score = sum(sidechain_atom_scores) / len(sidechain_atom_scores)
        return all_score, mainchain_score, sidechain_score


# -*- coding: utf-8 -*-
""" Application Factory

This is the entry point to the entire application.
"""

import os
import json
from flask import Flask, render_template, jsonify, flash, redirect, url_for

def create_app(test_config=None):
    """Create an instance of Wallowa Wildlife Checklists"""
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        # This secret will be overriden with the instance config.
        SECRET_KEY='dev',
        # Store the database in the instance folder.
        DATABASE=os.path.join(app.instance_path, 'wallowawildlife.sqlite'),
        # Read in the client_id for google login.
        CLIENT_ID=json.loads(
            open('wallowawildlife/client_secrets.json', 'r')
            .read())['web']['client_id']
    )

    if test_config is None:
        # Load the instance config.
        app.config.from_pyfile('config.py', silent=True)
    else:
        # Otherwise, load the test config.
        app.config.update(test_config)

    # Make the instance folder if it doesn't exist.
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # Make the database available.
    from wallowawildlife.db import get_db

    @app.route('/')
    def index():
        """Handle the index route"""
        db = get_db()
        types = db.execute('SELECT * FROM creature_type').fetchall()
        return render_template('front_page.html', types=types)

    @app.route('/wildlife/<int:creature_id>/JSON')
    def wildlifeCreatureJSON(creature_id):
        """Create JSON endpoint"""
        db = get_db()
        c = db.execute('SELECT * FROM creature WHERE id = ?',
                       (creature_id,)).fetchone()
        if c:
            json_creature = {'id': c['id'],
                             'name_common': c['name_common'],
                             'name_latin': c['name_latin'],
                             'photo_url': c['photo_url'],
                             'photo_attr': c['photo_attr'],
                             'wiki_url': c['wiki_url'],
                             'type': c['type_id']}
            return jsonify(json_creature)
        else:
            return redirect(url_for('index'))

    @app.route('/wildlife/<url_text>/JSON')
    def wildlifeTypeJSON(url_text):
        """Create JSON endpoint"""
        db = get_db()
        creatures = db.execute('SELECT * FROM creature \
                                WHERE type_id = ?',
                               (url_text,)).fetchall()
        if creatures:
            json_creatures = [{'id': c['id'],
                               'name_common': c['name_common'],
                               'name_latin': c['name_latin'],
                               'photo_url': c['photo_url'],
                               'photo_attr': c['photo_attr'],
                               'wiki_url': c['wiki_url'],
                               'type': c['type_id']} for c in creatures]
            return jsonify(json_creatures)
        else:
            return redirect(url_for('index'))

    @app.route('/wildlife/JSON')
    def wildlifeJSON():
        """Create JSON endpoint"""
        db = get_db()
        creatures = db.execute('SELECT * FROM creature').fetchall()
        json_creatures = [{'id': c['id'],
                           'name_common': c['name_common'],
                           'name_latin': c['name_latin'],
                           'photo_url': c['photo_url'],
                           'photo_attr': c['photo_attr'],
                           'wiki_url': c['wiki_url'],
                           'type': c['type_id']} for c in creatures]

        return jsonify(json_creatures)

    @app.errorhandler(404)
    def page_not_found(e):
        """Redirect from all unhandled URLs to the index route"""
        return redirect(url_for('index'))

    # Register cli db commands.
    from . import db
    db.init_app(app)

    # Apply blueprints.
    from . import auth
    app.register_blueprint(auth.bp)

    from . import lists
    app.register_blueprint(lists.bp)
    app.add_url_rule('/', endpoint='index')

    return app


#!/usr/bin/env python3
"""
Advent of Code 2022 - Elf Rucksack Reorganization

A given rucksack always has the same number of items in each of its two compartments

Lowercase item types a through z have priorities 1 through 26.
Uppercase item types A through Z have priorities 27 through 52.

Find the item type that appears in both compartments of each rucksack.
What is the sum of the priorities of those item types?

"""
import argparse
from typing import List

def get_priority(letter: str) -> int:
    """Assigns the priority to each item passed in

    Args:
        letter: single alphabetical letter in upper or lower case

    Returns: conversion of character to expected int
    """
    # ord "a" = 97
    # ord "A" = 65
    if letter.isupper() is False:
        return ord(letter) - 96
    return ord(letter) - 38

def compare_comparts(compartment1: str, compartment2: str) -> str:
    """Returns the priority of item in common between compartments

    Args:
        compartment1: string of letters representing items
        compartment2: string of letters representing items

    Returns: string of single letter shared between compartment[1|2]
    """
    item_in_common = list(set(compartment1).intersection(compartment2))
    return get_priority(item_in_common[0])

def elf_grouping(rucksacks: list, group_size: int) -> list:
    """Returns list of elf groups of specified size

    Args:
        rucksacks: list of all the rucksacks in camp
        group_size: number of elves in a rucksack priority group

    Returns: list of organised elf groups by group_size
    """
    return [rucksacks[x:x+group_size] for x in range(0, len(rucksacks), group_size)]

def fetch_badge(group_of_bags: List[list]) -> int:
    """Returns the priority of item in common for an elf grouping

    Args:
        group_of_bags: A list containing the list of elf rucksacks in a group

    Returns: the shared badge priority for the group of elves
    """
    badge = list(set.intersection(*map(set, group_of_bags)))
    return get_priority(badge[0])

# pylint: disable=R0914
def main() -> None:
    """Main function to generate total score of elven rock, paper, scissors
    """
    parser = argparse.ArgumentParser("Input list to work out the elf game outcomes")
    parser.add_argument("--input_list", help="Input rucksack list as txt file", type=str)
    parser.parse_args()
    args = parser.parse_args()

    rucksacks = []
    input_file = args.input_list
    with open (input_file, encoding="utf-8") as file:
        rucksack_in = file.read()
        rucksacks = rucksack_in.splitlines()

    item_dups = []
    for rucksack in rucksacks:
        rucksack_objs = list(rucksack)
        rucksack_size = len(rucksack_objs)
        compartment_size = int(rucksack_size / 2)
        comp1 = slice(0, compartment_size)
        comp2 = slice(compartment_size, int(len(rucksack_objs)))
        item_dups.append(compare_comparts(rucksack_objs[comp1], rucksack_objs[comp2]))
    sum_of_priorities = sum(item_dups)
    print(f"Sum of priorities in duplicates: {sum_of_priorities}\n")
    rucksack_list = [ list(x) for x in rucksacks ]
    rucksack_groups = elf_grouping(rucksack_list, 3)
    badge_priorities = [ fetch_badge(x) for x in rucksack_groups ]
    sum_badge_priors = sum(badge_priorities)
    print(f"Sum of badge priorities: {sum_badge_priors}\n")

if __name__ == main():
    main()


import base64
import sys

from github import Github

ACCESS_TOKEN = ''
REPO_NAME = ''
ACCESS_TOKEN = sys.argv[1]
REPO_NAME = sys.argv[2]

g = Github(ACCESS_TOKEN)
repo = g.get_repo(REPO_NAME)

contents = repo.get_contents("/README.md")
contents_bkp = repo.get_contents("/docs/README.md")
base = contents.content
base = base.replace('\n', '')
text = base64.b64decode(base).decode('utf-8')

base_bkp = contents_bkp.content
base_bkp = base_bkp.replace('\n', '')
text_bkp = base64.b64decode(base_bkp).decode('utf-8')
if text != text_bkp:
    repo.update_file(contents_bkp.path,
                     "docs(README): synchronize README files", text,
                     contents_bkp.sha)
else:
    pass


import sys
from faucetpay import faucetpay

sys.path.append("./dbfolder")
from mysqlfunc import mysqldb
faucet=faucetpay()

class payuser:
    def sendreward(campaignid,userid):
        get_user_email=mysqldb().get_user_Wallet(userid)
        ref=mysqldb().get_user_ref(userid)
        get_user_referral=mysqldb().get_user_Wallet(ref)
        info=mysqldb().campaignid_to_info(campaignid)
        cpc=info[5]
        adbudget=info[6]
        if adbudget-cpc>0 and not mysqldb().is_completed_already(userid,campaignid):
            mysqldb().add_ad_completion(userid,campaignid)
            total_reward=cpc*100000000
            mysqldb().decrease_ad_budget(campaignid)
            user_reward=faucet.send_trx_to_user(get_user_email,total_reward/2)
            aff_reward=faucet.send_trx_to_user(get_user_referral,total_reward/10)
            mysqldb().add_transaction(userid,campaignid,0,total_reward/2,user_reward['payout_id'])
            mysqldb().add_transaction(ref,userid,1,total_reward/10,aff_reward['payout_id'])
            return True
        else:
            return False


from math import sqrt
import sys

def Input(line):
    is_error = True
    while is_error:
        is_error = False
        try:
            coeff = int(line)
        except ValueError:
            try:
                coeff = float(line)
            except ValueError:
                is_error = True
                line = input("Некорректный ввод, повторите попытку: ")
    return coeff

def A_Input(arg):
    try:
        coeff = int(arg)
    except ValueError:
        try:
            coeff = float(arg)
        except ValueError:
            coeff = "e"
    return coeff

print("|Аникин Филипп Автандилович, ИУ5-53Б|\n")
A_incorrect = True
if len(sys.argv)>1:
    print("<Режим принятия аргументов из КС>")
    if len(sys.argv) == 4:
        A = A_Input(sys.argv[1])
        B = A_Input(sys.argv[2])
        C = A_Input(sys.argv[3])
        A_incorrect = False
        if A == "e" or B == "e" or C == "e":
            print("*Некорректные аргументы, переход на ручной ввод*")
            A_incorrect = True
    else:
        print("*Некорректное количество аргументов, переход на ручной ввод*")
        A_incorrect = True

if A_incorrect == True:
    print("<Введите коэффициенты биквадратного уравнения>")
    line = input("A = ")
    A = Input(line)
    line = input("B = ")
    B = Input(line)
    line = input("C = ")
    C = Input(line)

print("======================================================")
print("A = ", A, "; B = ", B, "; C = ", C, sep='')

D = B*B - 4*A*C
if D-int(D) == 0:
    D = int(D)
print("Дискриминант =",D)

print("------------------------------------------------------")
if A != 0:
    if D >= 0:
        B = -B
        A = A + A
        D = sqrt(D)
        Q1 = (B+D)/A
        Q2 = (B-D)/A
        if D == 0:
            Q2 = -1
        D = -1

        if Q1 > 0:
            D = 1
            Q1 = sqrt(Q1)
            if Q1-int(Q1) == 0:
                Q1 = int(Q1)
            print("X", D, " = ", Q1, ", X", D+1, " = ", -Q1, sep='')
            D = D + 2
        elif Q1 == 0:
            D = 1
            Q1 = int(Q1)
            print("X", D, " = ", Q1, sep='')
            D = D + 1

        if Q2 >= 0:
            Q2 = sqrt(Q2)
            if Q2-int(Q2) == 0:
                Q2 = int(Q2)
            if D == -1:
                D = 1
            print("X", D, " = ", Q2, ", X", D+1, " = ", -Q2, sep='')
        elif Q2 == 0:
            if D == -1:
                D = 1
            Q2 = int(Q2)
            print("X", D, " = ", Q2, sep='')

        if D == -1:
            print("Действительных корней нет")
    else:
        print("Действительных корней нет")
else:
    if B!= 0:
        Q = -C/B
        if Q >= 0:
            Q = sqrt(Q)
            if Q-int(Q) == 0:
                Q = int(Q)
            print("X1 = ", -Q, ", X2 = ", Q, sep='')
        else:
            print("Действительных корней нет")
    else:
        if C != 0:
            print("Действительных корней нет")
        else:
            print("Решение - любое число")
print("======================================================")


import sys
import os
import re
from dijkstra import calculate_path

# MAPA:
'''
Consiste de dos conjuntos <E,C>. E es un conjunto de esquinas {e1,e2,e3, ….} y C las calles que conectan dichas esquinas.
C es un conjunto de ternas ordenadas {<e1,e2,c>,<e3,e4,c>, <e2,e1,c>} que expresa la dirección y el largo de las calles (c = distancia entre e1 y e2).
'''

# 1 - Representar esquinas y calles como un grafo dirigido y ponderado mediante listas de adyacencia.

class Vertex:
    def __init__(self,key):
        self.key = key
    color = None
    parent = None
    distance = 'infinite'
    f = None

class Graph:
    # vertices_list = [v1,v2,v3,...,vn]
    # edges_list = [(v1,v2),(v2,v3),...,(vi,vj)]
    def __init__(self,vertices_list,edges_list):
        # {'e1': memory_element_e1, 'e2': memory_element_e2....}
        self.vertices_list = vertices_list
        # [['e1','e2',100],['e3','e4',150],...]
        self.edges_list = edges_list

        self.adj_list = [[] for _ in range(len(self.vertices_list))]

        for i in range(len(edges_list)):
            vertex_u = self.vertices_list[edges_list[i][0]]
            vertex_v = self.vertices_list[edges_list[i][1]]
            weight_u_v = int(edges_list[i][2])
            self.adj_list[vertex_u.key - 1].append((vertex_v,weight_u_v))

    def draw_graph(self):
        for i in range(len(self.adj_list)):
            print('|',i+1,'|-->',end="")
            for vertex in self.adj_list[i]:
                print('|',vertex[0].key,'(w:',vertex[1],')|',end="")
            print()

def create_map(local_path):
    try:
        with open(local_path) as file:
            # Read the vertices line
            vertices_line = file.readline().strip()
            # Extract the vertices from the first line
            vertices = vertices_line.split("=")[1].strip().strip("{}").split(",")

            # Read the edges line
            edges_line = file.readline().strip()
            # Extract the vertices from the second line
            edges_string = edges_line.split("=")[1].strip().strip("{}")
            # Regex edges expression
            edges_string_regexed = re.findall(r'<(.*?)>', edges_string)

        edges_list = []
        for edge in edges_string_regexed:
            edges_list.append(edge.split(","))
        # Ordeno vertices
        sorted_vertices = sorted(vertices)
        # Creo dict de objetos vertex
        vertices_objects_dict = instantiate_vertex_objects(sorted_vertices)

        # Creo mapa
        uber_map = Graph(vertices_objects_dict,edges_list)
        write_to_disk(uber_map,'map')

        # Creo diccionario para los elementos del mapa
        map_elements = {}
        write_to_disk(map_elements,'map_elements')

        path_matrix = calculate_path(uber_map)
        write_to_disk(path_matrix,'path_matrix')

        print("Map created successfully")

    except FileNotFoundError:
        print('Error: No such file or directory.')

def instantiate_vertex_objects(elements_list):
    dict_vertices = {}

    for i in range(len(elements_list)):
        dict_vertices[elements_list[i]] = Vertex(int(elements_list[i][1:]))

    return dict_vertices

# Functions for writing to and reading from disk

def write_to_disk(data, objectType):
    import pickle
    file_name = objectType + '_serialized.bin'
    with open(file_name,'wb') as file:
        pickle.dump(data,file)

def read_from_disk(local_path):
    import pickle
    with open(local_path,'br') as file:
        data = pickle.load(file)
    return data

# Los elementos fijos y moviles seran guardados en un diccionario de python

def load_fix_element(name,address):
    # Asi como leo el mapa deberia tambien guardar en disco el diccionario de elementos?
    uber_map = read_from_disk('map_serialized.bin')
    map_elements = read_from_disk('map_elements_serialized.bin')
    # Valido que no exista el elemento en el mapa
    if (check_name_validity(name,'fixed')):
        if (name not in map_elements):
            parsed_address = parse_address_input(address)
            if (check_element_address(uber_map,parsed_address)):
                map_elements[name] = {'address': parsed_address}
                write_to_disk(map_elements,'map_elements')
                print(f"Fixed element {name} loaded with address: {address}")
            else:
                print('Not a valid address in map')
        else:
            print('The element already exists in map.')
    else:
        print('Not a valid name for a fixed map element')

def load_movil_element(name,address,amount):

    uber_map = read_from_disk('map_serialized.bin')
    map_elements = read_from_disk('map_elements_serialized.bin')

    if (check_name_validity(name,'movil')):
        if (name not in map_elements):
            parsed_address = parse_address_input(address)
            if (check_element_address(uber_map,parsed_address)):
                if (amount >= 0):
                    map_elements[name] = {'address': parsed_address, 'amount': amount}
                    write_to_disk(map_elements,'map_elements')
                    print(f"Movil element {name} with amount {amount} loaded with address {address} ")
                else:
                    print('The amount must be at least 0')
            else:
                print('Not a valid address in map')
        else:
            print('The element already exists in map.')
    else:
        print('Not a valid name for a movil map element')

def get_address(map,name):
    address = map[name]['address']
    return address

def at_same_location(map,name1,name2):
    if get_address(map,name1) == get_address(map,name2):
        return True
    else:
        return False

def check_name_validity(name,type):
    if (type == 'fixed'):
        pattern = r'[HATSEKI]\d+'
        valid_name = re.match(pattern,name)
    if (type == 'movil'):
        pattern = r'[PC]\d+'
        valid_name = re.match(pattern,name)

    if valid_name:
        return True
    else:
        return False

def parse_address_input(address_input):
    pattern = r"<(\w+),(\d+)>"
    matches = re.findall(pattern, address_input)
    result = [(match[0], int(match[1])) for match in matches]
    return result

def check_element_address(map,address):
    # Address in form [('ex',d1),('ey',d2)]
    vertex_u = map.vertices_list[address[0][0]]
    vertex_v = map.vertices_list[address[1][0]]

    for element in map.adj_list[vertex_u.key - 1]:
        vertex = element[0]
        if (vertex == vertex_v):
            return True

    for element in map.adj_list[vertex_v.key - 1]:
        vertex = element[0]
        if (vertex == vertex_u):
            return True

    print("There is no street connecting these corners.")
    return False

# Creacion de viaje

def create_trip(person,location):

    uber_map = read_from_disk('map_serialized.bin')
    map_elements = read_from_disk('map_elements_serialized.bin')

    #Determinar si la persona esta en el mapa
    if (person in map_elements):
        pair_vertex = (map_elements[person]['address'][0][0],map_elements[person]['address'][1][0])
        person_vertex = person_vertex_ref(map_elements,person,pair_vertex) #Toma el vertice referente a la persona

        #filtro los vehiculos
        map_cars = {clave: valor for clave, valor in map_elements.items() if clave.startswith('C')} #Extraigo el diccionario de autos
        map_cars_key = list(map_cars.keys())

        #A los vehiculos restantes les obtengo su vertice referencia
        cars_ref = [] #Almacenara tuplas (vehiculos,vertices)
        for car in map_cars_key:
            car_vertexpair = (map_elements[car]['address'][0][0],map_elements[car]['address'][1][0])
            cars_ref.append([car,car_vertex_ref(map_elements,car,car_vertexpair)])

        path_matrix = read_from_disk('path_matrix_serialized.bin') #Leo de memoria la matriz de caminos
        #Veo las distancias de los caminos correspondientes a la referencia de los autos
        valueperson_to_ref = calcule_ref(map_elements[person],person_vertex)
        for v in cars_ref:
            car_vertexpair = (map_elements[v[0]]['address'][0][0],map_elements[v[0]]['address'][1][0])
            valuecar_to_ref = calcule_ref(map_elements[v[0]], car_vertex_ref(map_elements,v[0],car_vertexpair))
            v.append(path_matrix[person_vertex-1][v[1]-1][0] + valuecar_to_ref + valueperson_to_ref)
        cars_ref = sorted(cars_ref, key=lambda x: x[2])

        payment = False
        #Devolucion de autos más cercanos
        #Calculo del costo
        for i in range(0,len(cars_ref)):
            costo = (cars_ref[i][2] + map_elements[cars_ref[i][0]]['amount'])/4
            if costo >= map_elements[person]['amount'] and i==0:
                print('No posee suficiente dinero para un viaje')
                break
            elif costo >= map_elements[person]['amount']:
                break
            elif i+1 == 4:
                break
            else:
                payment = True
                print(f"{i+1}.Auto {cars_ref[i][0]}: distancia {cars_ref[i][2]}, costo: {costo}")

        if payment:
            minpath = []

            if len(location)>3:
                destiny_address = parse_address_input(location)
                if check_element_address(uber_map,destiny_address):
                    virtual_location = 'destiny'
                    map_elements[virtual_location] = {'address':destiny_address}
                    write_to_disk(map_elements,'map_elemets')
                    location = virtual_location
            pair_vertex = (map_elements[location]['address'][0][0],map_elements[location]['address'][1][0])
            location_vertex = person_vertex_ref(map_elements,location,pair_vertex)

            minpath.append(location_vertex)
            nextVertex = path_matrix[person_vertex-1][location_vertex-1][1]
            while nextVertex != None:
                minpath.append(nextVertex.key)
                nextVertex = path_matrix[person_vertex-1][nextVertex.key-1][1]
            print('Recorrido más corto para llegar a destino a través de las esquinas:')
            print(minpath)

            travel_accepted = input("Desea aceptar el viaje? si/no: ")
            if (travel_accepted == 'si'):
                # Devolver lista de los 3 autos para elegir
                cars_available = []
                for i in range(len(cars_ref)):
                    if i < 3:
                        cars_available.append(cars_ref[i][0])
                    else:
                        break
                selected_car = input(f"Que auto desea elegir:  {cars_available}")
                if selected_car == cars_available[0]:
                    print(f"Ha seleccionado el auto {cars_available[0]}")
                if selected_car == cars_available[1]:
                    print(f"Ha seleccionado el auto {cars_available[1]}")
                if selected_car == cars_available[2]:
                    print(f"Ha seleccionado el auto {cars_available[2]}")
            else:
                return

    else:
        print(f"Error. Person {person} not in map.")

def calcule_ref(element,reference):
    uber_map = read_from_disk('map_serialized.bin')

    if uber_map.vertices_list[element['address'][0][0]].key == reference:
        return  element['address'][0][1]
    elif uber_map.vertices_list[element['address'][1][0]].key == reference:
        return element['address'][1][1]

def person_vertex_ref(map_elements,person,pair_vertex):
    #Tomo el mapa de memoria
    uber_map = read_from_disk('map_serialized.bin')
    #uber_map.draw_graph()
    #Toma los pares de vertices referentes a la persona
    vertex1 = uber_map.vertices_list[pair_vertex[0]]
    vertex2 = uber_map.vertices_list[pair_vertex[1]]

    sense = ''
    for v in uber_map.adj_list[vertex1.key-1]:
        if v[0] == vertex2:
            sense = '12'
    for v in uber_map.adj_list[vertex2.key-1]:
        if v[0] == vertex1 and sense == '':
            sense = '21'
        elif v[0] == vertex1 and sense == '12':
            sense = 'd'

    #Si la calle es doble sentido, busco el camino mas corto
    if sense == 'd':
        if map_elements[person]['address'][0][1] <= map_elements[person]['address'][1][1]:
            return vertex1.key
        else:
            return vertex2.key
    #Si el sentido es de 1 hacia 2 devolvera el vertice 1
    elif sense == '12':
        return vertex1.key
    else:
        #Caso contrario devuelve el vertice 2
        return vertex2.key
    #print(vertex1.key, vertex2.key)
    #print(sense)

def car_vertex_ref(map_elements,car,pair_vertex):
    #Tomo el mapa de memoria
    uber_map = read_from_disk('map_serialized.bin')

    #Toma los pares de vertices referentes a la persona
    vertex1 = uber_map.vertices_list[pair_vertex[0]]
    vertex2 = uber_map.vertices_list[pair_vertex[1]]

    sense = ''
    for v in uber_map.adj_list[vertex1.key-1]:
        if v[0] == vertex2:
            sense = '12'
    for v in uber_map.adj_list[vertex2.key-1]:
        if v[0] == vertex1 and sense == '':
            sense = '21'
        elif v[0] == vertex1 and sense == '12':
            sense = 'd'

    #Si la calle es doble sentido, busco el camino mas corto
    if sense == 'd':
        if map_elements[car]['address'][0][1] <= map_elements[car]['address'][1][1]:
            return vertex1.key
        else:
            return vertex2.key
    #Si el sentido es de 1 hacia 2 devolvera el vertice 2
    elif sense == '12':
        return vertex2.key
    else:
        #Caso contrario devuelve el vertice 1
        return vertex1.key


class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        dict = {}
        res = []
        lista = []

        #哈哈！这个是我自己写的hash table计算单词出现的频率 牛逼吧
        #但是性能没下面的好嘻嘻

        '''
        for i in words:
            dict[i]=len([x for x in words if x == i])
        '''

        #用collections里面的Counter函数专门用来统计每个元素出现的频率

        from collections import Counter
        dict = (Counter(words))

        ''' 关于Counter这个函数：

        from collections import Counter
        listb = ["i","love","leetcode","i","love","coding"]
        a = (Counter(listb))
        print(a)
        >>>Counter({'i': 2, 'love': 2, 'leetcode': 1, 'coding': 1})

        print(dict(a))
        >>>{'i': 2, 'love': 2, 'leetcode': 1, 'coding': 1}
        '''

        lst = list(dict.items())
        #返回一个list,里面是元组（键和值）
        for i in lst:
            lista.append((i[1]*(-1),i[0]))
        #将键和值在元组里换位置，把值（频率）放在前面*（-1），键（单词）放在后面
        heapq.heapify(lista)
        #堆化 化成小堆，因为乘了负1，所以在最上面的绝对值最大，频率最大
        for _ in range(k):
            element = heapq.heappop(lista)
            res.append(element[1])
        return res


import lightgbm as lgb
from sklearn.linear_model import LogisticRegression
import pandas as pd
import numpy as np

#读取数据
file_dir='E:\\GDBT_LR\\loan\\'
train_data='gbdt_train.csv'
test_data='gdbt_test.csv'
train=pd.read_csv(file_dir+train_data)
test=pd.read_csv(file_dir+test_data)
#删除无用参数
del train['Unnamed: 0']
del test['Unnamed: 0']

#取数据集
data=train[data_list]
test_data=test[data_list]

#构造训练集和测试集
feature=[x for x in data_list if x!='loan_status']
X_train=data[feature]
y_train=data['loan_status']
X_test=test_data[feature]
y_test=test_data['loan_status']

# 构造lgb分类器
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)

params = {
    'task': 'train',
    'boosting_type': 'gbdt',
    'objective': 'binary',
    'metric': {'binary_logloss'},
    'num_leaves': 64,
    'num_trees': 100,
    'learning_rate': 0.01,
    'feature_fraction': 0.9,
    'bagging_fraction': 0.8,
    'bagging_freq': 5,
    'verbose': 0
}

# 设置叶子节点
num_leaf = 64

print('Start training...')
# train
gbm = lgb.train(params,
                lgb_train,
                num_boost_round=100,
                valid_sets=lgb_train)

print('Save model...')
# save model to file
gbm.save_model('model.txt')

print('Start predicting...')
# predict and get data on leaves, training data
y_pred = gbm.predict(X_train, pred_leaf=True)
print(np.array(y_pred).shape)
print(y_pred[0])

#样本个数行，树个数*叶子树列矩阵
transformed_training_matrix = np.zeros([len(y_pred), len(y_pred[0]) * num_leaf],
                                       dtype=np.int64)  # N * num_tress * num_leafs
#将转换矩阵按叶子树划分，将叶子预测的节点位置添加标记，标记位置为temp数组，在大矩阵中，在相应位置处的元素加一
for i in range(0, len(y_pred)):
    temp = np.arange(len(y_pred[0])) * num_leaf + np.array(y_pred[i])
    transformed_training_matrix[i][temp] += 1

#预测集做同样的处理
y_pred = gbm.predict(X_test, pred_leaf=True)
print('Writing transformed testing data')
transformed_testing_matrix = np.zeros([len(y_pred), len(y_pred[0]) * num_leaf], dtype=np.int64)
for i in range(0, len(y_pred)):
    temp = np.arange(len(y_pred[0])) * num_leaf + np.array(y_pred[i])
    transformed_testing_matrix[i][temp] += 1

lm = LogisticRegression(penalty='l2',C=0.05) # logestic model construction
lm.fit(transformed_training_matrix,y_train)  # fitting the data
y_pred_test = lm.predict_proba(transformed_testing_matrix)   # Give the probabilty on each label

print(y_pred_test)

NE = (-1) / len(y_pred_test) * sum(((1+y_test)/2 * np.log(y_pred_test[:,1]) +  (1-y_test)/2 * np.log(1 - y_pred_test[:,1])))
print("Normalized Cross Entropy " + str(NE))

#以阀值为0.5看查全率与查准率
def get_pcr(y_tar,y_pre):
    id_list=[]
    for i in range(len(y_tar)):
        if y_tar[i]==1:
            id_list.append(i)
    right_n=0
    for i in id_list:
        if y_pre[i][0]<y_pre[i][1]:
            right_n+=1
    pre_id=[]
    for i in range(len(y_pre)):
        if y_pre[i][0]<y_pre[i][1]:
            pre_id.append(i)
    good_pre=set(pre_id)&set(id_list)
    print('查准率为：{}'.format(len(good_pre)/len(pre_id)))
    print('查全率为：{}'.format(right_n/len(id_list)))

get_pcr(y_test,y_pred_test)#查准率为：0.9205776173285198，查全率为：0.6623376623376623

y_pred_train = lm.predict_proba(transformed_training_matrix)   # Give the probabilty on each label
get_pcr(y_train,y_pred_train)#查准率为：0.9971139971139971，查全率为：0.9262734584450402


import sys
from math import log2, ceil
sys.stdin = open('input.txt')

def make_linked(node, left, right):                     # 배열의 숫자가 세그먼트 트리의 어느 인덱스에 저장되었는지 알기 위함
    if left >= right:
        linked[left] = node                             # 리프노드인 경우 배열에 저장
        return

    make_linked(node*2, left, (left+right)//2)          # 왼쪽 노드들 탐색
    make_linked(node*2+1, (left+right)//2+1, right)     # 오른쪽 노드들 탐색
    return

def query(node, left, right, start, end):                                   # 탐색
    if start <= left and right <= end:                                      # 찾으려는 범위에 완전히 속하면 현재 노드의 값 반환
        return segment_tree[node]
    elif end < left or right < start:                                       # 찾으려는 범위가 속하지 않으면 0 반환
        return 0

    left_nodes = query(node*2, left, (left+right)//2, start, end)           # 왼쪽 노드들 탐색
    right_nodes = query(node*2+1, (left+right)//2+1, right, start, end)     # 오른쪽 노드들 탐색
    return left_nodes + right_nodes                                         # 일부만 겹치면 왼쪽 노드와 오른쪽 노드에서 겹치는거 찾아서 값 반환

def modify(node):
    if node <= 0:                                                           # 루트노드까지 모두 바꿨으면 종료
        return

    segment_tree[node] = segment_tree[node*2] + segment_tree[node*2+1]      # 자식 노드들의 합
    modify(node//2)                                                         # 부모 노드 탐색

N, M = map(int, sys.stdin.readline().split())                   # 숫자의 개수, 명령의 개수
segment_tree = [0] * 2**(ceil(log2(N))+1)                       # 세그먼트 트리 초기화
linked = [0] * (N+1)                                            # 배열의 숫자별로 세그먼트 트리 리프노드의 인덱스

make_linked(1, 1, N)                                            # 위치 찾기

for _ in range(M):
    command, a, b = map(int, sys.stdin.readline().split())

    if not command:                         # 합을 구할때
        if a > b:                           # b가 더 크면 a와 스왑
            a, b = b, a
        print(query(1, 1, N, a, b))         # 탐색
    else:
        segment_tree[linked[a]] = b         # 배열의 숫자 값 변경
        modify(linked[a]//2)                # 부모 노드들의 값 변경


from pathlib import Path
import os
import datetime
import json

import h5py
import numpy as np
import pandas as pd
import click
import tensorflow as tf

from src.data.tf_data_hdf5 import get_tf_data, RandomStandardization
from src.models.models import unet_model, unetclassif_model
from src.models.losses import CustomLoss, MaskedDiceLoss
from src.models.callbacks import EarlyStopping
from src.models.evaluation import evaluate_pred_volume

DEBUG = False

project_dir = Path(__file__).resolve().parents[2]
splits_path = project_dir / "data/splits.json"

if DEBUG:
    EPOCHS = 3
else:
    EPOCHS = 400

plot_only_gtvl = False

@click.command()
@click.option("--config", type=click.Path(exists=True))
@click.option("--upsampling-kind", type=click.STRING, default="upsampling")
@click.option("--split", type=click.INT, default=0)
@click.option("--alpha", type=click.FLOAT, default=0.25)
@click.option("--w-gtvl", type=click.FLOAT, default=1.0)
@click.option("--w-gtvt", type=click.FLOAT, default=0.0)
@click.option("--w-lung", type=click.FLOAT, default=0.0)
@click.option("--gpu-id", type=click.STRING, default="0")
@click.option("--random-angle", type=click.FLOAT, default=None)
@click.option("--center-on", type=click.STRING, default="GTVl")
@click.option("--loss-type", type=click.STRING, default="sum_of_dice")
@click.option('--oversample/--no-oversample', default=False)
@click.option('--pretrained/--no-pretrained', default=True)
@click.option('--multitask/--no-multitask', default=False)
@click.option("--random-position/--no-random-position", default=True)
def main(config, upsampling_kind, split, alpha, w_gtvl, w_gtvt, w_lung, gpu_id,
         random_angle, center_on, loss_type, oversample, pretrained, multitask,
         random_position):
    os.environ["CUDA_VISIBLE_DEVICES"] = gpu_id
    h5_file = h5py.File(
        project_dir / "data/processed/hdf5_2d/data_selected_slices.hdf5", "r")

    if not pretrained:
        n_channels = 2
    else:
        n_channels = 3

    if oversample:
        steps_per_epoch = 40
    else:
        steps_per_epoch = None

    clinical_df = pd.read_csv(
        project_dir /
        "data/clinical_info_with_lung_info.csv").set_index("patient_id")

    with open(splits_path, "r") as f:
        splits_list = json.load(f)

    ids_train = splits_list[split]["train"]
    ids_val = splits_list[split]["val"]
    ids_test = splits_list[split]["test"]

    preprocessor = RandomStandardization()
    preprocessor_nrdm = RandomStandardization(p=0.0)
    if multitask:
        f = lambda x, y, plc_status, patient: (preprocessor(x),
                                               (y, plc_status))
        f_nrdm = lambda x, y, plc_status, patient: (preprocessor_nrdm(x),
                                                    (y, plc_status))
    else:
        f = lambda x, y, plc_status, patient: (preprocessor(x), y)
        f_nrdm = lambda x, y, plc_status, patient: (preprocessor_nrdm(x), y)
    ds_train = get_tf_data(h5_file,
                           clinical_df,
                           patient_list=ids_train,
                           shuffle=True,
                           oversample=oversample,
                           random_angle=random_angle,
                           random_position=random_position,
                           center_on=center_on,
                           n_channels=n_channels).map(f).batch(16)
    ds_val = get_tf_data(h5_file,
                         clinical_df,
                         patient_list=ids_val,
                         center_on="GTVl",
                         random_slice=False,
                         n_channels=n_channels).map(f_nrdm).batch(4)
    ids_val_pos = [p for p in ids_val if clinical_df.loc[p, "plc_status"] == 1]
    ids_val_neg = [p for p in ids_val if clinical_df.loc[p, "plc_status"] == 0]
    ds_sample = get_tf_data(h5_file,
                            clinical_df,
                            patient_list=ids_val_pos[:2] + ids_val_neg[:1],
                            center_on="GTVt",
                            random_slice=False,
                            n_channels=n_channels).map(f_nrdm).batch(3)

    if multitask:
        sample_images, sample_outputs = next(
            ds_sample.take(1).as_numpy_iterator())
        sample_seg = sample_outputs[0]
        model = unetclassif_model(3,
                                  upsampling_kind=upsampling_kind,
                                  pretrained=pretrained)
    else:
        sample_images, sample_seg = next(ds_sample.take(1).as_numpy_iterator())
        model = unet_model(3,
                           upsampling_kind=upsampling_kind,
                           pretrained=pretrained)

    sample_seg = np.stack(
        [sample_seg[..., 0], sample_seg[..., 1], sample_seg[..., -1]], axis=-1)

    if multitask:
        losses = [
            MaskedDiceLoss(
                w_lung=w_lung,
                w_gtvt=w_gtvt,
                w_gtvl=w_gtvl,
            ),
            tf.keras.losses.BinaryCrossentropy()
        ]
    else:
        losses = MaskedDiceLoss(
            w_lung=w_lung,
            w_gtvt=w_gtvt,
            w_gtvl=w_gtvl,
        )

    model.compile(
        optimizer=tf.keras.optimizers.Adam(1e-3),
        loss=losses,
        run_eagerly=False,
    )

    dir_name = (
        "unet__" +
        f"prtrnd_{pretrained}__a_{alpha}__wt_{w_gtvt}__wl_{w_lung}__wgtvl_{w_gtvl}"
        f"upsmpl_{upsampling_kind}__" +
        f"split_{split}__ovrsmpl_{oversample}__" + f"con_{center_on}" +
        f"ltyp_{loss_type}__mltsk_{multitask}__" +
        datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))

    callbacks = list()

    if not DEBUG:
        log_dir = str((project_dir / ("logs/fit/" + dir_name)).resolve())
        callbacks.append(
            tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1))
        file_writer_image = tf.summary.create_file_writer(log_dir + '/images')

        def log_prediction(epoch, logs):
            # Use the model to predict the values from the validation dataset.
            if multitask:
                sample_pred, sample_pred_pstatus = model.predict(sample_images)
            else:
                sample_pred = model.predict(sample_images)

            if plot_only_gtvl:
                sample_pred[..., 0] = 0
                sample_pred[..., 2] = 0

            # Log the confusion matrix as an image summary.
            with file_writer_image.as_default():
                tf.summary.image("Validation images",
                                 np.stack(
                                     [
                                         sample_images[..., 0],
                                         sample_images[..., 1],
                                         np.zeros_like(sample_images[..., 0]),
                                     ],
                                     axis=-1,
                                 ),
                                 step=epoch)
                tf.summary.image("Predictions", sample_pred, step=epoch)
                tf.summary.image("GTs", sample_seg, step=epoch)

        callbacks.extend([
            tf.keras.callbacks.LambdaCallback(on_epoch_end=log_prediction),
            EarlyStopping(
                minimal_num_of_epochs=350,
                monitor='val_loss',
                patience=20,
                verbose=0,
                mode='min',
                restore_best_weights=True,
            )
        ])

    model.fit(
        x=ds_train,
        epochs=EPOCHS,
        validation_data=ds_val,
        callbacks=callbacks,
        steps_per_epoch=steps_per_epoch,
    )
    if multitask:
        model.trainable = True
        callbacks.pop(-1)
        callbacks.append(
            EarlyStopping(
                minimal_num_of_epochs=0,
                monitor='val_loss',
                patience=20,
                verbose=0,
                mode='min',
                restore_best_weights=True,
            ))

        model.compile(
            optimizer=tf.keras.optimizers.Adam(1e-5),
            loss=losses,
            run_eagerly=False,
        )
        model.fit(
            x=ds_train,
            epochs=EPOCHS,
            validation_data=ds_val,
            callbacks=callbacks,
            steps_per_epoch=steps_per_epoch,
        )

    model_dir = project_dir / ("models/" + dir_name)
    model_dir.mkdir()
    model.save(model_dir / "model_weight")
    roc_test = evaluate_pred_volume(
        model,
        ids_test,
        h5_file,
        clinical_df,
        n_channels=n_channels,
        multitask=multitask,
        preprocessor=preprocessor_nrdm,
    )
    roc_val = evaluate_pred_volume(
        model,
        ids_val,
        h5_file,
        clinical_df,
        n_channels=n_channels,
        multitask=multitask,
        preprocessor=preprocessor_nrdm,
    )
    print(f"The ROC AUC for the val and "
          f"test are {roc_val} and {roc_test} respectively.")

if __name__ == '__main__':
    main()


from django.contrib.gis.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import smart_str
from django.utils.translation import gettext_lazy as _

# Create your models here.

class Country(models.Model):
    """Class for country info"""

    name = models.CharField(max_length=255)
    shortname = models.CharField(max_length=3)
    geom = models.MultiPolygonField(srid=4326)

    class Meta:
        ordering = ["name"]
        db_table = "country"

    def __unicode__(self):
        return smart_str(self.name)

    def __str__(self):
        return self.__unicode__()

    def natural_key(self):
        return self.__unicode__()

class Project(models.Model):
    """"""
    name = models.CharField(max_length=100)
    start_year = models.IntegerField()
    pager_status = models.URLField(null=True, blank=True)
    mailing_list = models.URLField(null=True, blank=True)
    template_link = models.URLField(null=True, blank=True)
    termsofuse_link = models.URLField(null=True, blank=True)

    class Meta:
        ordering = ["name"]
        db_table = "project"

    def __unicode__(self):
        return smart_str(self.name)

    def __str__(self):
        return self.__unicode__()

    def natural_key(self):
        return self.__unicode__()

class Organization(models.Model):
    """This table is useful to save info about organizations """
    name = models.CharField(max_length=255)
    shortname = models.CharField(max_length=25)
    address = models.CharField(max_length=250, null=True, blank=True)
    city = models.CharField(max_length=250, null=True, blank=True)
    country = models.ForeignKey(
        Country, on_delete=models.PROTECT, null=True, blank=True
    )
    email = models.EmailField(null=True, blank=True)
    website = models.URLField(max_length=150, null=True, blank=True)
    image = models.ImageField(upload_to="logo/organizations/", null=True, blank=True)
    geom = models.PointField(
        srid=4326,
        null=True,
        blank=True,
        help_text=_("The position of the organization"),
    )

    class Meta:
        ordering = ["name"]
        db_table = "organization"

    def __unicode__(self):
        if self.country:
            return smart_str(
                "{na} ({co})".format(na=self.name, co=self.country.shortname)
            )
        else:
            return smart_str("{na}".format(na=self.name))

    def __str__(self):
        return self.__unicode__()

    def natural_key(self):
        return self.__unicode__()

class ResearchGroup(models.Model):
    """"""
    name = models.CharField(max_length=255)
    shortname = models.CharField(max_length=25)
    organization = models.ForeignKey(Organization, on_delete=models.PROTECT)
    email = models.EmailField(null=True, blank=True)
    website = models.URLField(max_length=150, null=True, blank=True)
    image = models.ImageField(upload_to="logo/organizations/", null=True, blank=True)
    projects = models.ManyToManyField(Project, through='ResearchGroupProject')
    geom = models.PointField(
        srid=4326,
        null=True,
        blank=True,
        help_text=_("The position of the organization"),
    )

    class Meta:
        ordering = ["name"]
        db_table = "research_group"

    def __unicode__(self):
        if self.organization.shortname:
            return smart_str(
                "{na} ({co})".format(na=self.name, co=self.organization.shortname)
            )
        if self.organization.name:
            return smart_str(
                "{na} ({co})".format(na=self.name, co=self.organization.name)
            )
        else:
            return smart_str("{na}".format(na=self.name))

    def __str__(self):
        return self.__unicode__()

    def natural_key(self):
        return self.__unicode__()

class ResearchGroupProject(models.Model):
    researchgroup = models.ForeignKey(ResearchGroup, on_delete=models.PROTECT)
    project = models.ForeignKey(Project, on_delete=models.PROTECT)
    year = models.IntegerField()
    contact_people = models.TextField()

class User(AbstractUser):
    """Extent the abstract user class"""

    bio = models.TextField(max_length=500, null=True, blank=True)
    image = models.ImageField(upload_to="users/", null=True, blank=True)
    #TODO could a person be connected with more then one group?
    research_group = models.ManyToManyField(ResearchGroup)
    projects = models.ManyToManyField(Project)
    euromammals_username = models.TextField(max_length=500, null=True, blank=True)


import time
from tqdm.auto import tqdm

def show_info_me():
    """ Показывает инфо о коллеге """
    about_me = {
        'ФИО': 'Левченко Алексей',
        'Должность': 'Ведущий исследователь данных',
        'Блок': 'Технологии',
        'Делаю': 'рекомендательные системы в HR',

    }
    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def show_info_patrik():
    about_me = {
        'ФИО': 'Патрикеев Михаил Алексеевич',
        'Должность': 'Ведущий инженер по разработке',
        'Блок': 'Розничный бизнес',
        'Делаю': 'Тестирую социальные и зарплатные решения',
    }
    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def show_info_you_v():
    about_me = {
        'Имя': 'Валерий',
        'Город': 'Самара',
        'Должность': 'Главный специалист',
        'Блок': 'Операционный центр',
        'Занимаюсь': 'Анализом счетов по банковским картам'
    }
    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def show_info_zylkov():
    about_me = {
        'ФИО': 'Зыльков Павел',
        'Должность': 'Инженер по сопровождению',
        'Блок': 'Технологии',
        'Делаю': 'Социальные и зарплатные решения'
    }
    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def show_info_me_():
    about_me = {
        'ФИО': 'Шахиев Азамат Рафикович',
        'Должность': 'Старший специалист отдела безопасности',
        'Блок': 'Сервисы',
        'Делаю': 'Сопровождение технических средств безопасности'
    }

    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def info_pro_menya():
    about_me = {
        'ФИО': 'Нетяга Светлана',
        'Должность': 'Главный аудитор',
        'Подразделение': 'Управление внутреннего аудита',
        'Делаю': 'анализ розничных некредитных операций'
    }

    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def show_info_me2():
    about_me = {
        'ФИО': 'Солодова Наталья',
        'Должность': 'клиентский менеджер',
        'Блок': 'ДомКлик'
    }
    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def info_pro_menya_ii():
    about_me = {
        'ФИО': 'Исайкина Ирина',
        'Должность': 'Заместитель руководителя ВСП',
        'Подразделение': 'ВСП',
        'Делаю': 'занимаюсь обслуживанием клиентов и решением их проблем',
    }
    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def show_info_me_eb():
    about_me = {
        'ФИО': 'Евгений Бодягин',
        'Должность': 'Эксперт Центра подбора в инновационные направления бизнеса',
        'Блок': 'HR',
        'Делаю': 'Методологию подбора, в т.ч. и подбор D-people и сбор статистики по подбору'
    }
    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def show_info_you_eg():
    about_me = {
        'ФИО': 'Евгений Головачев',
        'Город': 'Самара',
        'Должность': 'клиентский менеджер',
        'Блок': 'ДомКлик',
        'Занимаюсь': 'Помощь клиентам ипотечного кредитования'
    }
    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

def info_pro_menya_av():
    about_me = {
        'ФИО': 'Аня Великобратова',
        'Должность': 'КМ',
        'Подразделение': 'КИБ СРБ'
    }
    for k, v in about_me.items():
        print(f'{k}:{v}')
    else:
        print('_' * 30)

info_list = [
    show_info_me,
    info_pro_menya,
    show_info_me_,
    show_info_me2,
    show_info_patrik,
    show_info_you_eg,
    info_pro_menya_ii,
    show_info_you_v,
    show_info_zylkov,
    show_info_me_eb,
    info_pro_menya_av

]

if __name__ == "__main__":
    for show_info in info_list:
        show_info()
        for i in tqdm(range(30)):
            time.sleep(1)

        print('Спасибо за инфо!')
        print('_' * 30)


"""Pytest fixtures for huesensors tests."""
from copy import deepcopy
from unittest.mock import MagicMock, patch

import pytest
from aiohue import Bridge
from aiohue.sensors import GenericSensor
from homeassistant.components.hue import DOMAIN as HUE_DOMAIN
from homeassistant.components.hue import HueBridge
from homeassistant.components.hue.sensor_base import SensorManager
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.util import slugify

from custom_components.huesensor.data_manager import (
    BINARY_SENSOR_MODELS,
    HueSensorBaseDevice,
    HueSensorData,
)

from .sensor_samples import (
    MOCK_GEOFENCE,
    MOCK_ZLLLightlevel,
    MOCK_ZLLPresence,
    MOCK_ZLLTemperature,
)

DEV_ID_SENSOR_1 = "SML_00:17:88:01:02:00:af:28-02"

async def entity_test_added_to_hass(
    data_manager: HueSensorData,
    entity: HueSensorBaseDevice,
):
    """Test routine to mock the internals of async_added_to_hass."""
    entity.hass = data_manager.hass
    if entity.unique_id.startswith(BINARY_SENSOR_MODELS):
        entity.entity_id = f"binary_sensor.test_{slugify(entity.name)}"
    else:
        entity.entity_id = f"remote.test_{slugify(entity.name)}"
    await entity.async_added_to_hass()
    assert data_manager.available
    assert entity.unique_id in data_manager.sensors

class MockAsyncCounter:
    """
    Call counter for the hue data coordinator.

    Used to mock and count bridge updates done with
    `await bridge.sensor_manager.coordinator.async_request_refresh()`.
    """

    _counter: int = 0

    def __await__(self):
        """Dumb await."""
        yield

    def __call__(self, *args, **kwargs):
        """Call just returns self, increasing counter."""
        self._counter += 1
        return self

    @property
    def call_count(self) -> int:
        """Return call counter."""
        return self._counter

def add_sensor_data_to_bridge(bridge, sensor_key, raw_data):
    """Append a sensor raw data packed to the mocked bridge."""
    bridge.sensors[sensor_key] = GenericSensor(
        raw_data["uniqueid"], deepcopy(raw_data), None
    )

def _make_mock_bridge(idx_bridge, *sensors):
    bridge = MagicMock(spec=Bridge)
    bridge.sensors = {}
    for i, raw_data in enumerate(sensors):
        add_sensor_data_to_bridge(
            bridge, f"{raw_data['type']}_{idx_bridge}_{i}", raw_data
        )
    return bridge

def _mock_hue_bridges(bridges):
    # mocking HueBridge at homeassistant.components.hue level
    hue_bridges = {}
    for i, bridge in enumerate(bridges):
        coordinator = MagicMock(spec=DataUpdateCoordinator)
        coordinator.async_request_refresh = MockAsyncCounter()

        sensor_manager = MagicMock(spec=SensorManager)
        sensor_manager.coordinator = coordinator

        hue_bridge = MagicMock(spec=HueBridge)
        hue_bridge.api = bridge
        hue_bridge.sensor_manager = sensor_manager

        hue_bridges[i] = hue_bridge

    return hue_bridges

@pytest.fixture
def mock_hass():
    """Mock HA object for tests, including some sensors in hue integration."""
    hass = MagicMock(spec=HomeAssistant)
    hass.data = {
        HUE_DOMAIN: _mock_hue_bridges(
            [
                _make_mock_bridge(
                    0,
                    MOCK_ZLLPresence,
                    MOCK_ZLLLightlevel,
                    MOCK_ZLLTemperature,
                ),
                _make_mock_bridge(1, MOCK_GEOFENCE),
            ]
        )
    }
    hass.config = MagicMock()
    hass.states = MagicMock()

    return hass

def patch_async_track_time_interval():
    """Mock hass.async_track_time_interval for tests."""
    return patch(
        "custom_components.huesensor.data_manager.async_track_time_interval",
        autospec=True,
    )


import sys

result = {'C':0,'H':0,'O':0}
eachCnt = []
chemical = sys.stdin.readline().rstrip()
M = chemical.replace('+', ' ').replace('=',' ').split(' ') # 일단 분해하고보자

def solve():
    global eachCnt
    word = ['C','H','O']
    for i in range(1,11):
        for j in range(1,11):
            for k in range(1,11):
                cnt = 0
                for w in word:
                    if(eachCnt[0][w]*i + eachCnt[1][w]*j == eachCnt[2][w]*k):
                        cnt+=1
                if(cnt == 3):
                    print(i,j,k,sep=' ')
                    return

for m in M:
    temp = {'C':0,'H':0,'O':0}
    for i in range(len(m)):
        if(m[i]=='C'):
            if( i != len(m)-1 and m[i+1].isdigit()):
                temp[m[i]]+=int(m[i+1])
            else:
                temp[m[i]]+=1
        elif(m[i]=='H'):
            if(i != len(m)-1 and m[i+1].isdigit()):
                temp[m[i]]+=int(m[i+1])
            else:
                temp[m[i]]+=1
        elif(m[i]=='O'):
            if(i != len(m)-1 and m[i+1].isdigit()):
                temp[m[i]]+=int(m[i+1])
            else:
                temp[m[i]]+=1
    eachCnt.append(temp)
solve()


from PIL import Image
import glob
import random
import os
from collections import defaultdict

#################################
test_percentage = 0.20

def partitionRankings(rawRatings, testPercent):
    # https://stackoverflow.com/questions/23299099/trying-to-split-list-by-percentage
    howManyNumbers = int(round(testPercent*len(rawRatings)))
    shuffled = rawRatings[:]
    random.shuffle(shuffled)
    return shuffled[howManyNumbers:], shuffled[:howManyNumbers]

#################################################################
####    Make Directories (if needed)
#################################################################
caboodle = defaultdict(list)
categories = [x[1] for x in os.walk('./DATA')][0]

if 'train' in categories:
    categories.remove('train')
    categories.remove('validate')

for category in categories:
    val_dir = 'DATA/validate/'+str(category)
    train_dir = 'DATA/train/'+str(category)
    subdata = []

    if not os.path.exists(val_dir):
        os.makedirs(val_dir)

    if not os.path.exists(train_dir):
        os.makedirs(train_dir)

    #  Read images (currently either png or jpg format)
    for filename in glob.glob('DATA/'+str(category)+'/*.jpg'):
        im = Image.open(filename)
        keep = im.copy()
        subdata.append(keep)
        im.close()

    for filename in glob.glob('DATA/'+str(category)+'/*.png'):
        im = Image.open(filename)
        keep = im.copy()
        subdata.append(keep)
        im.close()

    random.shuffle(subdata)
    train_sample, test_sample = partitionRankings(subdata, test_percentage)

    #  Read images (save shuffled images to new train/validate folders in a jpg format)
    for i in range(len(train_sample)):
        train_sample[i].save(train_dir+'/'+str(category) + str(i) + '.jpg')

    for i in range(len(test_sample)):
        test_sample[i].save(val_dir+'/'+str(category) + str(i) + '.jpg')

#################################################################
####    Make labels.txt
#################################################################
f = open('DATA/labels.txt', 'w')

for category in categories:
        f.write(category+'\n')
f.close()


# coding: utf-8
import torch
import sys
from torch import nn
from TTS.utils.text.symbols import symbols
from TTS.layers.tacotron import Prenet, Encoder, Decoder, PostCBHG

class Tacotron(nn.Module):
    def __init__(self,
                 embedding_dim=256,
                 linear_dim=1025,
                 mel_dim=80,
                 r=5,
                 padding_idx=None):
        super(Tacotron, self).__init__()
        self.r = r
        self.mel_dim = mel_dim
        self.linear_dim = linear_dim
        self.embedding = nn.Embedding(
            len(symbols), embedding_dim, padding_idx=padding_idx)
        #print(" | > Number of characters : {}".format(len(symbols)))
        self.embedding.weight.data.normal_(0, 0.3)
        self.encoder = Encoder(embedding_dim)
        self.decoder = Decoder(256, mel_dim, r)
        self.postnet = PostCBHG(mel_dim)
        self.last_linear = nn.Sequential(
            nn.Linear(self.postnet.cbhg.gru_features * 2, linear_dim),
            nn.Sigmoid())

    def forward(self, characters, mel_specs=None, mask=None):
        B = characters.size(0)
        inputs = self.embedding(characters)
        # batch x time x dim
        encoder_outputs = self.encoder(inputs)
        # batch x time x dim*r
        mel_outputs, alignments, stop_tokens = self.decoder(
            encoder_outputs, mel_specs, mask)
        # Reshape
        # batch x time x dim
        mel_outputs = mel_outputs.view(B, -1, self.mel_dim)
        linear_outputs = self.postnet(mel_outputs)
        linear_outputs = self.last_linear(linear_outputs)
        return mel_outputs, linear_outputs, alignments, stop_tokens


import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib.dates as mdates
import mpl_finance as mpl
from tkinter import *
from yahoo_fin.stock_info import get_data
import pandas as pd
import plotly.graph_objects as go

class AutoPlot:
    def __init__(self):
        master = Tk()
        Label(master, text="Stock Ticker").grid(row=0)
        Label(master, text="Range Start").grid(row=1)
        Label(master, text="Range End").grid(row=2)

        self.e1 = Entry(master)
        self.e2 = Entry(master)
        self.e3 = Entry(master)
        self.e1.grid(row=0, column=1)
        self.e2.grid(row=1, column=1)
        self.e3.grid(row=2, column=1)

        Button(master, text='Quit', command=master.destroy).grid(row=3, column=0, sticky=W, pady=4)
        Button(master, text='Show', command=self.make_plot).grid(row=3, column=1, sticky=W, pady=4)

        mainloop()

    def make_plot(self):
        #Extracting data
        df = get_data("{ticker}".format(ticker=self.e1.get()),
                        start_date = self.e2.get(), end_date = self.e3.get())

        df.index = pd.to_datetime(df.index)

        fig = go.Figure(data=[go.Candlestick(x=df.index,
                open=df['open'],
                high=df['high'],
                low=df['low'],
                close=df['close'])])

        fig.show()

AutoPlot()


# -*- coding: utf-8 -*-
from os import path
import os
from wordcloud import WordCloud, STOPWORDS
import requests
import matplotlib.pyplot as plt
# from scipy.misc import imread
import numpy as np
from PIL import Image
import jieba
import jieba.posseg as pseg
import jieba.analyse

def makeCiyun(file_name):
    d = path.dirname(__file__)

    # Read the whole text.
    text = open(path.join(d, file_name), encoding="utf8").read()
    jieba_info = jieba.cut(text, cut_all=True)

    font = os.path.join(os.path.dirname(__file__), "ziti.otf")
    imgmask = "255fk.jpg"
    alice_mask = np.array(Image.open(path.join(d, imgmask)))
    # lower max_font_size
    wordcloud = WordCloud(
        max_font_size=40, font_path=font, mask=alice_mask,
        stopwords=STOPWORDS
    ).generate(jieba_info)
    plt.figure()
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()
    wordcloud.to_file(path.join(d, "xiaoguo.png"))

import json

def getInfo(productId, page):
    url = "https://club.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv7667&productId=" + \
        productId + "&score=0&sortType=5&page=" + str(page) + "&pageSize=10&isShadowSku=0&fold=1"
    header = {
        'Host': 'club.jd.com',
        'Referer': "https://item.jd.com/" + productId + ".html"
    }
    content = requests.get(url, headers=header).content
    content = content[len("fetchJSON_comment98vv7667("):-2]
    # print(type(content))

    # open("li.txt", 'w').write(str(content))
    # print(content)
    content = json.loads((content).decode("GBK"))
    comments = content['comments']
    infos = ""
    for item in comments:
        # print(item['content'])
        # files.write(item['content'] + "\n")
        infos += item['content'] + "\n"
        # break
    return infos
    # print(content)
    # files.close()

def start(productId):
    file_name = "jd_" + productId + ".txt"
    try:
        os.remove(file_name)
    except Exception as ex:
        pass
    files = open(file_name, 'a', encoding="utf8")
    for i in range(100):
        infos = getInfo(productId, i)
        files.write(infos)
        print("finish", i)
        files.write("//*\n")
    files.close()
    makeCiyun(file_name)

# start("4213316")
makeCiyun("jd_4213316.txt")


import json
import os

import requests

from utils import is_snapshot_week, get_dependency_version, get_latest_tag, get_snapshot_branch, \
    get_dependency_version_from_tags

github_token = os.getenv("GITHUB_TOKEN")
headers = {"Authorization": "Bearer " + github_token}

def build_message():
    message = '@navigation-ios '

    releases_url = "https://api.github.com/repos/mapbox/mapbox-navigation-ios/releases"
    releases = requests.get(releases_url, headers=headers).json()
    if is_snapshot_week(releases):
        message += 'Navigation SDK snapshot must be released today (rc or GA release was not released this week).\n'
    else:
        message += 'Navigation SDK snapshot must not be released today (rc or GA release was released this week).\n'
        return message

    maps_releases = requests.get(
        'https://api.github.com/repos/mapbox/mapbox-maps-ios/releases',
        headers=headers
    ).json()
    maps_version = get_dependency_version(maps_releases)
    if maps_version:
        message += ':white_check_mark: Maps ' + maps_version + ' is ready.\n'
    else:
        message += ':siren: Expected Maps release was not released.\n'

    nav_native_tags = requests.get(
        'https://api.github.com/repos/mapbox/mapbox-navigation-native-ios/tags',
        headers=headers
    ).json()
    nav_native_version = get_dependency_version_from_tags(nav_native_tags)
    if nav_native_version:
        message += ':white_check_mark: Nav Native ' + nav_native_version + ' is ready.\n'
    else:
        message += ':siren: Expected Nav Native release was not released.\n'

    tags = requests.get('https://api.github.com/repos/mapbox/mapbox-navigation-ios/tags', headers=headers).json()
    latest_tag = get_latest_tag(tags)
    snapshot_branch = get_snapshot_branch(latest_tag)

    message += 'Snapshot branch is *' + snapshot_branch + '*.\n'

    message += '*Release time is today night.*\n'

    return message

def send_message(message):
    payload = {'text': message, 'link_names': 1}
    slack_url = os.getenv("SLACK_WEBHOOK")
    requests.post(slack_url, data=json.dumps(payload))

message = build_message()
send_message(message)


# the question link https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc8/00000000002d82e6

T = int(input())#input of number of test cases
for x in range(1, T + 1):
    n=int(input())#no of entries
    s = str(input())#input of entries
    c=0
    tnop = list(s.split(" "))#conversion of entries to list
    for i in range(1,len(tnop)-1):
        if int(tnop[i])>int(tnop[i-1]) and int(tnop[i])>int(tnop[i+1]):#checking of the strictly greater than condition
            c+=1
    print("Case #{}: {}".format(x, c), flush=True)


import os
import json
import argparse
from multiprocessing import Pool
import string
import shutil

# external libraries
from numpy import argmax
from rouge import Rouge
from tqdm import tqdm

def ROUGE(hypsumm, refsumm):
        rouge = Rouge()
        rouge.metrics = ['rouge-2']
        rouge.stats = ['r']

        ref = '\n'.join(refsumm)
        hyp = '\n'.join(hypsumm)
        if len(hyp.strip()) < 10: return 0
        if len(ref.strip()) < 10: return 0

        scores = rouge.get_scores(hyp, ref, avg = True)
        return scores['rouge-2']['r']

def AVGROUGE(hypsumm, refsumm):
        rouge = Rouge()
        rouge.stats = ['f']

        ref = '\n'.join(refsumm)
        hyp = '\n'.join(hypsumm)
        if len(hyp.strip()) < 10: return 0
        if len(ref.strip()) < 10: return 0

        scores = rouge.get_scores(hyp, ref, avg = True)
        val = scores['rouge-1']['f'] + scores['rouge-2']['f'] + scores['rouge-l']['f']
        return val / 3

###########################################################################
# This class selects 'num_sents' sentences from the full text
# for each sentence in the summary wrt the highest average ROUGE scores.
# Ref: Narayan et.al. NAACL 2018. "Ranking sentences for extractive
# summarization with reinforcement learning"
###########################################################################
class AVGROUGEscorer:
        def __init__(self, judgesents, summsents):
                self.judgesents = judgesents
                self.summsents = summsents

                self.labels = [False for sent in judgesents]

        def getLabels(self, num_sent = 3):
                # [facets: [support groups: [sent indices]]]
                for sent in self.summsents:
                        # get scores with all judgesents
                        scores = list(map(lambda x: AVGROUGE([sent], [x]), self.judgesents))
                        # mark top labels
                        for i in range(num_sent):
                                index = int(argmax(scores))
                                self.labels[index] = True
                                scores[index] = -1

                return self.labels

###########################################################################
# This class selects greedily selects the maximal sentences from full text
# to maximize ROUGE scores wrt the summary.
# Ref: Nallapati et. al. AAAI 2017. "SummaRuNNer: A Recurrent Neural Network
# based Sequence Model for Extractive Summarization of Documents"
###########################################################################
class ROUGEscorer:
        def __init__(self, judgesents, summsents):
                self.judgesents = judgesents
                self.summsents = summsents

                self.currsents = []
                self.labels = [False for sent in judgesents]

        def score(self, i):
                if self.labels[i]: return 0
                t = self.judgesents[i]
                if len(t.translate(t.maketrans('', '', string.punctuation + string.whitespace))) < 5: return 0

                new = self.currsents + [self.judgesents[i]]
                score = ROUGE(new, self.summsents)
                return score

        def getmaxscore(self):
                # with Pool(N_PROCESS) as p:
                #         scores = p.map(self.score, range(len(self.judgesents)))
                #         p.close()
                #         p.terminate()

                scores = list(map(self.score, range(len(self.judgesents))))
                index = argmax(scores)
                return index, scores[index]

        def getLabels(self, min_labels = 10):
                currscore = 0.0
                while True:
                        # select sent index which maximises ROUGE
                        index, maxscore = self.getmaxscore()
                        if maxscore <= currscore and len(self.currsents) >= min_labels: break

                        currscore = maxscore
                        self.currsents.append(self.judgesents[index])
                        self.labels[index] = True

                #print(len(self.currsents), len(self.judgesents))
                return self.labels

def prepare(judgepath, summarypath):

        with open(judgepath) as fp:
                judgesents = fp.read().splitlines()
        with open(summarypath) as fp:
                summsents = fp.read().splitlines()

        data = {}
        # prepare doc
        data['doc'] = '\n'.join(judgesents)
        # prepare summ
        data['summaries'] = '\n'.join(summsents)

        scorer = MODEL(judgesents, summsents)
        labels = scorer.getLabels()

        # prepare labels
        data['labels'] = '\n'.join(map(lambda x: str(int(x)), labels))
        return data

def generateData(f):
        #print(f)
        try:
                d = prepare(os.path.join(JUDGEPATH, f), os.path.join(SUMMPATH, f))
                d['file'] = f
                assert len(d['doc'].splitlines()) == len(d['labels'].splitlines()), "INCORRECT Number of sentences and labels"
                with open(os.path.join(tmpdir, f), 'w') as fout:
                        json.dump(d, fout)

        except Exception as args:
                print("ERROR in", f)
                print(args)

#%% MAIN

if __name__ == '__main__':

        #PARAMS

        parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
        parser.add_argument("base_dir", type=str, help="base directory where the other files and folders are present")

        parser.add_argument("--method", type=str, choices=['avg_rg', 'm_rg'], default="avg_rg", help="method to use for generating labels.")
        parser.add_argument("--separator", type=str, default="$$$", help="separator used in output docs, to separate between the text and labels.")
        parser.add_argument("--n_process", type=int, default=1, help="number of subprocesses to use (for parallel computation).")

        parser.add_argument("--judgement_dir", type=str, default="judgement", help="subdirectory containing the judgements.")
        parser.add_argument("--summary_dir", type=str, default="summary", help="subdirectory containing the summaries.")

        parser.add_argument("--tmp_dir", type=str, default="tmp", help="temporary directory where the files will be stored. This directory can be deleted after running.")
        parser.add_argument("--out_dir", type=str, default="labelled", help="subdirectory where the output will be stored.")
        parser.add_argument("--out_json", type=str, default="labelled.jsonl", help="json-line file where the output will be stored.")

        parser.add_argument("--remove_tmp", action='store_true', help="if given any existing files inside tmp_dir will be deleted first. Else they will be reused (they won't be calculated again).")

        args = parser.parse_args()
        BASE = args.base_dir

        JUDGEPATH = os.path.join(BASE, args.judgement_dir)
        SUMMPATH = os.path.join(BASE, args.summary_dir)

        OUTPATH_JSON = os.path.join(BASE, args.out_json)
        OUTPATH = os.path.join(BASE, args.out_dir)

        tmpdir = os.path.join(BASE, args.tmp_dir)

        METHOD = args.method

        if METHOD == 'avg_rg': MODEL = AVGROUGEscorer
        elif METHOD == 'm_rg': MODEL = ROUGEscorer

        SEP = args.separator

        KEEP_TMP = not args.remove_tmp
        N_PROCESS = args.n_process

        ###########################################################################
        # CODE STARTS

        if not KEEP_TMP:
                shutil.rmtree(tmpdir)

        if not os.path.exists(tmpdir): os.mkdir(tmpdir)

        files = set(next(os.walk(JUDGEPATH))[2])
        excludefiles = set(next(os.walk(tmpdir))[2])
        files = [f for f in (files - excludefiles)]# if int(f.split('.')[0]) <= 3500]

        if N_PROCESS > 1:
                with Pool(N_PROCESS) as p:
                        list(tqdm(p.imap_unordered(generateData, files), total = len(files)))

        else:
                list(tqdm(map(generateData, files), total = len(files)))

        files = next(os.walk(tmpdir))[2]

        if not os.path.exists(OUTPATH): os.mkdir(OUTPATH)

        with open(OUTPATH_JSON, 'w') as fout:
                for f in tqdm(files):
                        with open(os.path.join(tmpdir, f)) as fp:
                                try: d = json.load(fp)
                                except:
                                        os.system('rm ' + os.path.join(tmpdir, f))
                                        continue

                        with open(os.path.join(OUTPATH, f), 'w') as fout2:
                                for line, label in zip(d['doc'].split('\n'), d['labels'].split('\n')):
                                        print(line, SEP, label, sep = '', file = fout2)

                        print(json.dumps(d), file = fout)


# XXX there is much grot here.

# some of this comes from trying to present a reasonably intuitive and
# useful interface, which implies a certain amount of DWIMmery.
# things surely still could be more transparent.

class FormException(Exception):
    pass

class Instruction(object):
    def __init__(self, fields):
        self.fields = fields
        self.lfields = [k for (k,v) in fields.iteritems()
                        if isinstance(v, str)]
        #if not self.lfields:
        #    self.assemble() # for error checking only
    def assemble(self):
        r = 0
        for field in self.fields:
            r |= field.encode(self.fields[field])
        return r

class IBoundDesc(object):
    def __init__(self, desc, fieldmap, assembler):
        self.fieldmap = fieldmap
        self.desc = desc
        self.assembler = assembler
    def calc_fields(self, args, kw):
        fieldsleft = list(self.desc.fields)
        fieldvalues = {}
        for fname in kw:
            kw[fname] = self.fieldmap[fname]
        for d in (self.desc.specializations, kw):
            for field in d:
                fieldsleft.remove(field)
                fieldvalues[field] = d[field]
        for i in range(min(len(self.desc.defaults), len(fieldsleft) - len(args))):
            f, v = self.desc.defaults[i]
            fieldvalues[f] = v
            fieldsleft.remove(f)
        for a in args:
            field = fieldsleft.pop(0)
            fieldvalues[field] = a
        return fieldvalues, fieldsleft
    def __call__(self, *args, **kw):
        fieldvalues, sparefields = self.calc_fields(args, kw)
        if sparefields:
            raise FormException('fields %s left'%sparefields)
        self.assembler.insts.append(Instruction(fieldvalues))

class IBoundDupDesc(IBoundDesc):
    def calc_fields(self, args, kw):
        s = super(IBoundDupDesc, self)
        fieldvalues, sparefields = s.calc_fields(args, kw)
        for k, v in self.desc.dupfields.iteritems():
            fieldvalues[k] = fieldvalues[v]
        return fieldvalues, sparefields

class IDesc(object):
    boundtype = IBoundDesc
    def __init__(self, fieldmap, fields, specializations, boundtype=None):
        self.fieldmap = fieldmap
        self.fields = fields
        self.specializations = specializations
        self.defaults = ()
        if boundtype is not None:
            self.boundtype = boundtype
        for field in specializations:
            if field not in fields:
                raise FormException(field)

    def __get__(self, ob, cls=None):
        if ob is None: return self
        return self.boundtype(self, self.fieldmap, ob)

    def default(self, **defs):
        assert len(defs) == 1
        f, v = defs.items()[0]
        self.defaults = self.defaults + ((self.fieldmap[f], v),)
        return self

    def __call__(self, **more_specializatons):
        s = self.specializations.copy()
        ms = {}
        ds = {}
        for fname, v in more_specializatons.iteritems():
            field = self.fieldmap[fname]
            if field not in self.fields:
                raise FormException("don't know about '%s' here" % field)
            if isinstance(v, str):
                ds[field] = self.fieldmap[v]
            else:
                ms[field] = v
        s.update(ms)
        if len(s) != len(self.specializations) + len(ms):
            raise FormException("respecialization not currently allowed")
        if ds:
            fields = list(self.fields)
            for field in ds:
                fields.remove(field)
            return IDupDesc(self.fieldmap, tuple(fields), s, ds)
        else:
            r = IDesc(self.fieldmap, self.fields, s, self.boundtype)
            r.defaults = tuple([(f, d) for (f, d) in self.defaults if f not in s])
            return r

    def match(self, inst):
        c = 0
        for field in self.fields:
            if field in self.specializations:
                if field.decode(inst) != self.specializations[field]:
                    return 0
                else:
                    c += 1
        return c

    def __repr__(self):
        l = []
        for field in self.fields:
            if field in self.specializations:
                l.append('%s=%r'%(field.name, self.specializations[field]))
            else:
                l.append(field.name)
        r = '%s(%s)'%(self.__class__.__name__, ', '.join(l))
        if self.boundtype is not self.__class__.boundtype:
            r += ' => ' + self.boundtype.__name__
        return r

    def disassemble(self, name, inst, labels, pc):
        kws = []
        for field in self.fields:
            if field not in self.specializations:
                v = field.decode(inst)
                for f, d in self.defaults:
                    if f is field:
                        if d == v:
                            break
                else:
                    kws.append('%s=%s'%(field.name, field.r(inst, labels, pc)))
        return "%-5s %s"%(name, ', '.join(kws))

class IDupDesc(IDesc):
    boundtype = IBoundDupDesc
    def __init__(self, fieldmap, fields, specializations, dupfields):
        super(IDupDesc, self).__init__(fieldmap, fields, specializations)
        self.dupfields = dupfields

    def match(self, inst):
        for field in self.dupfields:
            df = self.dupfields[field]
            if field.decode(inst) != df.decode(inst):
                return 0
        else:
            return super(IDupDesc, self).match(inst)

class Form(object):
    fieldmap = None
    def __init__(self, *fnames):
        self.fields = []
        bits = {}
        overlap = False
        for fname in fnames:
            if isinstance(fname, str):
                field = self.fieldmap[fname]
            else:
                field = fname
            if field.overlap:
                overlap = True
            for b in range(field.left, field.right+1):
                if not overlap and b in bits:
                    raise FormException("'%s' and '%s' clash at bit '%s'"%(
                        bits[b], fname, b))
                else:
                    bits[b] = fname
            self.fields.append(field)

    def __call__(self, **specializations):
        s = {}
        for fname in specializations:
            field = self.fieldmap[fname]
            if field not in self.fields:
                raise FormException("no nothin bout '%s'"%fname)
            s[field] = specializations[fname]
        return IDesc(self.fieldmap, self.fields, s)

    def __repr__(self):
        return '%s(%r)'%(self.__class__.__name__, [f.name for f in self.fields])


import constant

from loguru import logger
from managers import AudioManager
from threading import Event, Thread

class Autonomous(object):

    def __init__(self, audio_manager: AudioManager):
        self.audio_manager = audio_manager
        self.event: Event = Event()
        self.event.set()
        self.thread: Thread | None = None

    def start(self):
        if not self.event.is_set():
            return

        logger.info("Starting Automation")
        self.event.clear()
        Thread(target=self.run, name="Autonomous Thread").start()

    def stop(self):
        if self.event.is_set():
            return

        logger.info("Stopping Automation")
        self.event.set()

    def toggle(self):
        if self.event.is_set():
            self.start()
        else:
            self.stop()

    def run(self):
        self.audio_manager.play_random_sound(constant.AUTO_CATEGORY)
        while not self.event.wait(constant.AUTO_INTERVAL):
            self.audio_manager.play_random_sound(constant.AUTO_CATEGORY)


import unittest
from BaseTestCases.BaseTestCase import BaseTestCase, os
from Pages.Deployment_Group import DG_Create
from Pages.LoginPage import LoginPage
from DataSource.read_excel import read_excel
from time import sleep
from ddt import ddt,data,unpack

@ddt
class test_DG_Create (BaseTestCase):

    @data(*read_excel.get_data_from_excel(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) +  '\Data\Test_Data.xlsx','DG'))
    @unpack

    def test_Create_DG(self,DGname,DGdesc,DGDB):
        self.driver.implicitly_wait(30)
        LoginPage.login(self,'Administrator','P@ssw0rd')
        sleep(3)
        DG_Create.DG_screenlink(self)
        sleep(3)
        DG_Create.DG_createlink(self)
        sleep(3)
        DG_Create.DG_DetailsPopup(self,DGname,DGdesc,int(DGDB))
        #Actual_Msg = DG_Create.DG_toast
        DG_Create.save_close_btn(self)
        sleep(3)
        self.assertEqual(DG_Create.Toast(self),"Deployment Group " + DGname + " has been created.")

        # self.assertTrue(DG_Create.DG_toast(DGname))
        #print(DG_Create.DG_toast)

if __name__ == '__main__':
    unittest.main()


    #m7homework7b-SetsDictionaries_2
# Pickled Vegetables
import pickle

def pickled_vege():
    pickvege = {'tomato' : '5.00', 'squash' : '2.34'}
    print(pickvege)

    c = pickvege['tomato'] # print value
    print(c)

    pickvege['lemon'] = '.25' # add
    print(pickvege)

    del pickvege['tomato'] # delete
    print(pickvege)

    pickvege.pop('squash') # remove
    print(pickvege)

    k = pickvege.keys()
    print(k)

    f = open('C://pickled.txt', 'wb') # open file for binary writing
    pickle.dump(pickvege, f) # write data to new file
    f.close() # close the file

    d = open('C://pickled.txt', 'rb') # open file to read
    read_data = pickle.load(d) # unpickle
    print(read_data)

pickled_vege()


from artist_data import ArtistData
import numpy as np
import igraph

class Network:
    def __init__(self, data):
        self._data = data
        self._graph = igraph.Graph()

    def graph(self):
        return self._graph

    def init(self):
        self._graph.add_vertices(list(self._data.artists.keys()))

        edges = [(max(key, i), min(key, i)) for key, item in self._data.adjacency.items() for i in item]
        edges = list(set(edges))
        self._graph.add_edges(edges)

        self._graph.vs['name'] = [item['name'] for item in self._data.artists.values()]
        self._graph.vs['followers'] = [item['followers'] for item in self._data.artists.values()]
        self._graph.vs['popularity'] = [item['popularity'] for item in self._data.artists.values()]
        self._graph.es['popularity'] = [(self._data.artists[edge[0]]['popularity'] + self._data.artists[edge[1]]['popularity']) / 2 for edge in edges]

    def draw(self, layout_name='large', file_format='pdf'):
        '''
        Draw created artists graph. Showing labels only for artists with popularity in 0.9 quantile.

        param: layout_name: name of algorithm to use for layout. Available options: see igraph documentation
        type: layout_name: str
        param: file_format: name of format to which graph should be saved
        type: file_format: str
        '''
        visual_style = {}
        visual_style['edge_width'] = [item/50 for item in self._graph.es['popularity']]
        visual_style['vertex_color'] = [[0, 1, 0, 0.9] if item['name'] == self._data.name else [1, 0, 0, 0.4] for item in self._data.artists.values()]
        quantile = np.quantile([item['popularity'] for item in self._data.artists.values()], 0.95)
        visual_style['vertex_label'] = [item['name'] if item['popularity'] > quantile or item['name'] == self._data.name else '' for item in self._data.artists.values()]
        visual_style['vertex_label_size'] = [20 if item['name'] == self._data.name else 7 for item in self._data.artists.values()]
        visual_style['vertex_label_color'] = [[0, 1, 0, 1] if item['name'] == self._data.name else [0, 0, 0, .8] for item in self._data.artists.values()]
        visual_style['vertex_size'] = [item/5 for item in self._graph.vs['popularity']]

        name = self._data.name.replace(' ', '')
        igraph.plot(
            self._graph,
            f'data/{name}/net_l{self._data.depth}.{file_format}',
            **visual_style,
            order=list(self._data.artists.keys()).reverse(),
            vertex_frame_width=.1,
            layout=self._graph.layout(layout_name),
            bbox=(1000,1000),
            autocurve=True)

if __name__ == '__main__':
    data = ArtistData('Giuseppe Verdi', depth=3)
    data.load_adjacency()
    data.load_artists()

    n = Network(data)
    n.init()
    n.draw(file_format='png')


import asyncio
import threading
import time
import speech_recognition as sr

r = sr.Recognizer()

# def do(audio):

def srcVoice(n, audio):
    for i in range(n, 0, -1):
        print('sssssss')
        # threading.Thread(target=r.recognize_google, args=(audio))
        words = r.recognize_google(audio)
        print(words, '$$$$$$$$$$$$')
        break

def audioLis(source):
    print('running')
    try:
        audio = r.listen(source, 3, 6)
        try:
            DN = threading.Thread(target=srcVoice, args=(1, audio))
            DN.start()
        except Exception as e:pass
    except Exception as e:

        print(e, '<<<<<<<<<<<<<<<<<<<')
source = 'None'
with sr.Microphone() as source:
    while True:
        audioLis(source)

# async
# await