import numpy
import numpy as np
import globals
import random
import h5py
import sys
import struct
import logging
import math
from os import path
from codecs import decode
from random import randint
from datetime import datetime
import hdf5_common

def log_delta(val_type: str, before_val, after_val, changed_bits, scaling_factor=None):
    corruption_type = "by a scale factor: " + str(scaling_factor) if scaling_factor is not None else\
        "at bits: " + str(changed_bits)

    logging.debug(val_type + " location value was corrupted " + corruption_type +
                  "  Delta: " + str(before_val) + " --> " + str(after_val) + "\n")

# given the range start and range end, it generates a random sample of the given length
def generate_random_sample(start: int, end: int, length: int, allow_0=False):
    random.seed(datetime.now())
    the_range = range(start, end+1)
    range_length = end - start
    # When start and end are the same
    if range_length == 0:
        range_length = 1
    sample = []
    while length > range_length:
        new_sample = random.sample(the_range, range_length)
        sample.extend(new_sample)
        length -= range_length

    new_sample = random.sample(the_range, length)
    sample.extend(new_sample)

    # first_bit should have been decreased by 1 when reading args, then occurrences on first_bit should actually 0
    if allow_0:
        sample = [0 if x == start else x for x in sample]

    return sample

# assumes string have same length
def string_xor(str1: str, str2: str):
    result = ""
    for x, y in zip(str1, str2):
        result += str(int(x) ^ int(y))

    return result

# given the bit mask and desired length, it pads n zeros at start and (length-n-mascLength) zeros at the end, n is rand
def random_pad_mask(masc: str, length: int):
    random.seed(datetime.now())
    masc_length = len(masc)
    start = random.randint(0, length - masc_length)
    zeros_start = '0' * start
    zeros_end = '0' * (length - masc_length - start)
    result = zeros_start + masc + zeros_end
    return result

def bin_to_float(b):
    bf = int_to_bytes(int(b, 2), globals.BYTES_PER_FLOAT)  # 8 bytes needed for IEEE 754 binary64.
    val = struct.unpack(globals.PRECISION_CODE, bf)[0]
    return to_float_using_current_precision(val)

def int_to_bytes(n, length):  # Helper function
    return decode('%%0%dx' % (length << 1) % n, 'hex')[-length:]

# converts the value to the current bit precision
def to_float_using_current_precision(val: float):
    if globals.FLOAT_PRECISION == "auto":
        return val
    if globals.FLOAT_PRECISION == "64":
        return numpy.float64(val)
    if globals.FLOAT_PRECISION == "32":
        return numpy.float32(val)
    return numpy.float16(val)

def float_to_bin(num):
    num = to_float_using_current_precision(num)
    # Struct can provide us with the float packed into bytes. The '!' ensures that
    # it's in network byte order (big-endian) and the 'f' says that it should be
    # packed as a float. Alternatively, for double-precision, you could use 'd'.
    packed = struct.pack(globals.PRECISION_CODE, num)
    # print('Packed: %s' % repr(packed))

    # For each character in the returned string, we'll turn it into its corresponding
    # integer code point
    #
    # [62, 163, 215, 10] = [ord(c) for c in '>\xa3\xd7\n']
    integers = [c for c in packed]
    # print('Integers: %s' % integers)

    # For each integer, we'll convert it to its binary representation.
    binaries = [bin(i) for i in integers]
    # print('Binaries: %s' % binaries)

    # Now strip off the '0b' from each of these
    stripped_binaries = [s.replace('0b', '') for s in binaries]
    # print('Stripped: %s' % stripped_binaries)

    # Pad each byte's binary representation's with 0's to make sure it has all 8 bits_to_corrupt:
    #
    # ['00111110', '10100011', '11010111', '00001010']
    padded = [s.rjust(8, '0') for s in stripped_binaries]
    # print('Padded: %s' % padded)

    # At this point, we have each of the bytes for the network byte ordered float
    # in an array as binary strings. Now we just concatenate them to get the total
    # representation of the float:
    return ''.join(padded)

def change_bit_in_binary(binary: str, index: int):
    bit_flipped = "1" if binary[index] == '0' else "0"
    binary = binary[:index] + bit_flipped + binary[index + 1:]
    return binary

def corrupt_int(val: int):
    """
    Corrupts an integer value, since the byte length of integers is not fixed, we just flip a random bit given the
    binary representation that python itself returns when calling bin(values)
    :param val: The value to corrupt
    :return: The corrupted value
    """
    is_negative = val < 0
    if is_negative:
        val *= -1
    binary = str(bin(val))[2:]
    chosen_bit = randint(0, len(binary) - 1)
    new_binary = change_bit_in_binary(binary, chosen_bit)
    new_val = int(new_binary, 2)
    if is_negative:
        new_val *= -1
    return new_val, chosen_bit

def corrupt_float_at_bits(val: float, chosen_bits: []):
    successful_bits = chosen_bits.copy()
    new_val = val
    for bit in chosen_bits:
        binary = float_to_bin(new_val)
        new_binary = change_bit_in_binary(binary, bit)
        temp_val = bin_to_float(new_binary)
        if not globals.ALLOW_NaN_VALUES and (math.isnan(temp_val) or math.isinf(temp_val)):
            successful_bits.remove(bit)
        else:
            # successful corruption
            new_val = temp_val

    failed_attempts = len(chosen_bits) - len(successful_bits)
    if failed_attempts > 0:
        start = 0 if globals.FIRST_BIT is None else globals.FIRST_BIT
        end = 63 if globals.LAST_BIT is None else globals.LAST_BIT
        new_val, other_successful_bits =\
            corrupt_float_at_bits(new_val, generate_random_sample(
                start=start,
                end=end,
                length=failed_attempts,
                allow_0=globals.ALLOW_SIGN_CHANGE
            ))
        successful_bits.extend(other_successful_bits)

    return new_val, successful_bits

# returns list with the indexes_array of all the 1s on the mask
def get_corrupted_bits_from_mask(mask: str):
    corrupted_bits = []
    for i in range(0, len(mask)):
        if mask[i] == '1':
            corrupted_bits.append(i)

    return corrupted_bits

# corrupts a float value using a bit mask
def corrupt_float_using_mask(val: float, mask: str):
    return _corrupt_float_using_mask(val, mask, random_pad_mask(mask, int(globals.FLOAT_PRECISION)))

# aux method
def _corrupt_float_using_mask(val: float, mask: str, full_mask: str):
    val_binary = float_to_bin(val)
    new_binary = string_xor(val_binary, full_mask)
    temp_val = bin_to_float(new_binary)
    if not globals.ALLOW_NaN_VALUES and (math.isnan(temp_val) or math.isinf(temp_val)):
        return corrupt_float_using_mask(val, mask)

    return temp_val, get_corrupted_bits_from_mask(full_mask)

def auto_set_values(val):
    """
    TODO: improve at the dataset level
    sets the bit-range to be the whole range of bits_to_corrupt,
    based on the precision of the value to corrupt
    :param val: The value to corrupt
    """
    globals.FIRST_BIT = 0
    if isinstance(val, np.float16):
        globals.LAST_BIT = 15
    elif isinstance(val, np.float32):
        globals.LAST_BIT = 31
    elif isinstance(val, np.float64):
        globals.LAST_BIT = 63

    logging.debug("Value has a: " + str(globals.LAST_BIT + 1) + "-bit precision")
    globals.set_precision_settings(globals.LAST_BIT + 1)
    globals.BIT_MASK = None

def try_corrupt_value(val, corruption_prob: float, injection_burst: int):
    """
    Given a corruption probability, it tries to corrupt the value at injection_burst-different bits
    :param corruption_prob: The corruption probability
    :param val: The value to corrupt
    :param injection_burst: How many times the value is going to be corrupted
    :return: The corrupted value and the chosen bits_to_corrupt for corruption
    """
    random.seed(datetime.now())
    chosen_bits = None
    if random.random() < corruption_prob:
        str_val_type = str(type(val))
        if globals.SCALING_FACTOR is None:
            if "int" in str_val_type:
                new_val, chosen_bits = corrupt_int(val)
                log_delta("Int", val, new_val, chosen_bits)
            else:
                if globals.FLOAT_PRECISION == "auto":
                    auto_set_values(val)

                # Injection with bit range
                if globals.BIT_MASK is None:
                    chosen_bits = generate_random_sample(
                        start=globals.FIRST_BIT,
                        end=globals.LAST_BIT,
                        length=injection_burst,
                        allow_0=globals.ALLOW_SIGN_CHANGE
                    )
                    new_val, chosen_bits = corrupt_float_at_bits(val, chosen_bits)
                    log_delta("Float", val, new_val, chosen_bits)

                # Injection with bit mask
                else:
                    new_val, chosen_bits = corrupt_float_using_mask(val, globals.BIT_MASK)
                    log_delta("Float", val, new_val, chosen_bits)

        # Injection with scaling factor
        else:
            new_val = val * globals.SCALING_FACTOR
            chosen_bits = [-2]  # -2, so it counts the injection
            log_delta("", val, new_val, -1, globals.SCALING_FACTOR)

        return new_val, chosen_bits

    logging.debug("Did not corrupt value at the index")
    return val, chosen_bits

# given the bit to flip, it corrupts the value changing that bit
def corrupt_value_at_bits(val, chosen_bits: []):
    if globals.FLOAT_PRECISION == "auto":
        auto_set_values(val)
    str_val_type = str(type(val))
    if "int" in str_val_type:
        new_val, chosen_bits = corrupt_int(val)
        log_delta("Int", val, new_val, chosen_bits)
    else:
        new_val, chosen_bits = corrupt_float_at_bits(val, chosen_bits)
        log_delta("Float", val, new_val, chosen_bits)

    return new_val, chosen_bits

# given a dataset, returns a random index based on its shape
def __get_random_indexes(dataset):
    random.seed(datetime.now())
    dimensions = 1 if dataset.ndim == 0 else dataset.ndim
    indexes = [0] * dimensions
    current_dim = 0
    for dimLength in dataset.shape:
        ranIndex = random.randint(0, dimLength-1)
        indexes[current_dim] = ranIndex
        current_dim += 1

    return indexes

def try_corrupt_dataset(dataset, corruption_prob: float, injection_burst: int):
    """
        Tries to corrupt the given dataset at a random index with the given probability. If successful, returns
        the indexes_array where the corruption happened and at which indexes_array
        :param dataset: The dataset to corrupt
        :param corruption_prob: The corruption probability
        :param injection_burst: How many times the value is going be corrupted
        :return: The indexes_array of chosen entry and which bits_to_corrupt were corrupted
    """
    corrupted_bits = None
    indexes_array = __get_random_indexes(dataset)
    logging.debug("Dataset indexes_array to corrupt: " + str(indexes_array))
    if dataset.ndim == 0:
        dataset[()], corrupted_bits = try_corrupt_value(dataset[()], corruption_prob, injection_burst)
    elif dataset.ndim == 1:
        dataset[indexes_array[0]], corrupted_bits = try_corrupt_value(dataset[indexes_array[0]], corruption_prob, injection_burst)
    elif dataset.ndim == 2:
        dataset[indexes_array[0], indexes_array[1]], corrupted_bits = \
            try_corrupt_value(dataset[indexes_array[0], indexes_array[1]], corruption_prob, injection_burst)
    elif dataset.ndim == 3:
        dataset[indexes_array[0], indexes_array[1], indexes_array[2]], corrupted_bits = \
            try_corrupt_value(dataset[indexes_array[0], indexes_array[1], indexes_array[2]], corruption_prob, injection_burst)
    elif dataset.ndim == 4:
        dataset[indexes_array[0], indexes_array[1], indexes_array[2], indexes_array[3]], corrupted_bits = \
            try_corrupt_value(dataset[indexes_array[0], indexes_array[1], indexes_array[2], indexes_array[3]], corruption_prob, injection_burst)
    # more than 4 is very unlikely... right?

    return indexes_array, corrupted_bits

def corrupt_dataset_using_location(dataset, indexes_array: [], bits_to_corrupt: []):
    """
        Corrupts the dataset value at the given indexes, at the given bits
        :param dataset: The dataset to corrupt
        :param indexes_array: Where in the dataset to corrupt, might be empty
        :param bits_to_corrupt: Which values must be flipped
        :return: The indexes of chosen entry and which bits were corrupted
    """
    if not indexes_array:
        indexes_array = __get_random_indexes(dataset)
    logging.debug("Dataset indexes_array to corrupt: " + str(indexes_array))
    if dataset.ndim == 0:
        dataset[()], corrupted_bit = corrupt_value_at_bits(dataset[()], bits_to_corrupt)
    elif dataset.ndim == 1:
        dataset[indexes_array[0]], corrupted_bit = corrupt_value_at_bits(dataset[indexes_array[0]], bits_to_corrupt)
    elif dataset.ndim == 2:
        dataset[indexes_array[0], indexes_array[1]], corrupted_bit = \
            corrupt_value_at_bits(dataset[indexes_array[0], indexes_array[1]], bits_to_corrupt)
    elif dataset.ndim == 3:
        dataset[indexes_array[0], indexes_array[1], indexes_array[2]], corrupted_bit = \
            corrupt_value_at_bits(dataset[indexes_array[0], indexes_array[1], indexes_array[2]], bits_to_corrupt)
    elif dataset.ndim == 4:
        dataset[indexes_array[0], indexes_array[1], indexes_array[2], indexes_array[3]], corrupted_bit = \
            corrupt_value_at_bits(dataset[indexes_array[0], indexes_array[1], indexes_array[2], indexes_array[3]], bits_to_corrupt)
    # more than 4 is very unlikely... right?

    return indexes_array, bits_to_corrupt

def save_values_in_sequence(corrupted_bits, indexes_array, location):
    """
    If applies, saves [indexes_array, corrupted bits] at location index
    :param corrupted_bits: the bits that were corrupted
    :param indexes_array: the indexes of the dataset of the corrupted value
    :param location: the name of the dataset
    """
    if globals.SAVE_INJECTION_SEQUENCE:
        corruption_location = [indexes_array, corrupted_bits] \
            if globals.INJECTION_SEQUENCE_SAVE_INDEXES else [[], corrupted_bits]
        base_location = hdf5_common.get_base_locations_for(location, globals.BASE_LOCATIONS)
        if base_location in globals.INJECTION_SEQUENCE_SAVED:
            globals.INJECTION_SEQUENCE_SAVED[base_location].append(corruption_location)
        else:
            globals.INJECTION_SEQUENCE_SAVED.update({base_location: [corruption_location]})

# Tries to corrupt the input file at the given locations, with the given probability, num_injection_attempts times
def try_corrupt_hdf5_file(input_file: str, locations_to_corrupt, corruption_prob: float,
                          num_injection_attempts: int, injection_burst: int):
    if path.exists(input_file):
        errors_injected = 0
        logging.info("----------- Corrupting file, main loop -----------")
        with h5py.File(input_file, 'a') as hdf:
            locations_count = locations_to_corrupt.__len__()

            while num_injection_attempts > 0:
                random.seed(datetime.now())
                # randomly calculates the next location to corrupt
                next_location_index = random.randint(0, locations_count-1) if locations_count > 1 else 0
                location = locations_to_corrupt[next_location_index]
                logging.debug("Will try to corrupt at dataset: " + str(location))

                dataset = hdf.get(location)
                if dataset is not None:
                    indexes_array, corrupted_bits = try_corrupt_dataset(dataset, corruption_prob, injection_burst)
                    if corrupted_bits is not None:
                        errors_injected += 1
                    save_values_in_sequence(corrupted_bits, indexes_array, location)
                else:
                    logging.error(str(location) + " doesn't exist or it is not supported for error injection")
                    sys.exit(-1)

                num_injection_attempts -= 1
        return errors_injected
    else:
        logging.error("Specified file does not exist... exiting the tool")
        sys.exit(2)

def corrupt_hdf5_file_based_on_sequence(input_file: str, injection_sequence: {}, locations_to_corrupt: []):
    if path.exists(input_file):
        logging.info("----------- Corrupting file based on sequence, main loop -----------")
        with h5py.File(input_file, 'a') as hdf:
            random.seed(datetime.now())
            for injection_path in injection_sequence:
                inner_locations = hdf5_common.get_full_location_paths_for(injection_path, locations_to_corrupt)
                locations_count = inner_locations.__len__()
                for indexes, bits in injection_sequence[injection_path]:
                    next_location_index = random.randint(0, locations_count-1) if locations_count > 1 else 0
                    location = inner_locations[next_location_index]
                    logging.debug("Will corrupt at: " + str(location))
                    dataset = hdf.get(location)
                    if dataset is not None:
                        indexes_array, corrupted_bits = corrupt_dataset_using_location(dataset, indexes, bits)
                        save_values_in_sequence(corrupted_bits, indexes_array, location)
    else:
        logging.error("Specified file does not exist... exiting the tool")
        sys.exit(2)


#!/usr/bin/env python3

# exec(open("setupcardano.py").read())

# este lo uso para mandar desde el creador
txargs0 = {"from": acc0, "gasPrice": 5000000000, "gas": 4000000}
# este lo uso para mandar desde el user
txargs1 = {"from": acc1, "gasPrice": 5000000000, "gas": 4000000}

with open("../Contratos/Compilado/Cardano.abi") as contract_abi_file:
  contract_abi = json.load(contract_abi_file)
with open("../Contratos/Compilado/Cardano.bin") as contract_bin_file:
  contract_bytecode = '0x' + contract_bin_file.read()

contract_address = "0x02F62A1e10C3ED6eA170856f505703f834D49779"

# Una vez que calcule la direccion del contrato, se la asigno a la instancia
card = web3.eth.contract(address = contract_address, abi = contract_abi, bytecode = contract_bytecode)

nonce = web3.eth.getTransactionCount(acc1)

cardano_txn = card.functions.setNum(
	  100,
  ).buildTransaction({
	  'gas': 100000,
	  'gasPrice': web3.toWei('5', 'gwei'),
	  'nonce': nonce,
  })

signed_txn = web3.eth.account.signTransaction(cardano_txn, private_key=private_key)

web3.eth.sendRawTransaction(signed_txn.rawTransaction)


def merge_sort(sort_this, low, high):
    if low < high:
        mid = (low + high) // 2
        merge_sort(sort_this, low, mid)
        merge_sort(sort_this, mid + 1, high)
        merge(sort_this, low, mid, high)

def merge(merge_this, low, mid, high):
    temp = merge_this[:]
    i, j, k = low, mid + 1, low
    while i <= mid and j <= high:
        if temp[i] <= temp[j]:
            merge_this[k] = temp[i]
            i += 1
        else:
            merge_this[k] = temp[j]
            j += 1
        k += 1
    while i <= mid:
        merge_this[k] = temp[i]
        i += 1
        k += 1

if __name__ == '__main__':
    with open('inp') as f:
        line = f.readlines()
    nums = [int(i) for i in line]
    merge_sort(nums, 0, len(nums) - 1)
    print(nums)


from typing import Sequence, TypeVar, Generic, Callable, Optional, TypeAlias, Union
from alchemy_graph import get_only_selected_fields
from pydantic.generics import GenericModel
from sqlalchemy import desc, delete, insert, update, select, func, Select, ColumnElement
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import DeclarativeMeta
from strawberry.types import Info

T = TypeVar('T', bound=type[DeclarativeMeta])
FilterType: TypeAlias = Union[list[ColumnElement], tuple[ColumnElement], any]

class ListType(GenericModel, Generic[T]):
    items: Sequence[T]
    count: int

def get_selected_sql(model: T, info: Info) -> Optional[Callable[..., Select]]:
    def selected_inner(table_inner: str | None = None):
        return get_only_selected_fields(model, info, table_inner)

    if not info:
        return None
    return selected_inner

class AbstractBL(Generic[T]):
    def __init__(
            self,
            info: Info,
            page: int = 1,
            page_size: int = 15
    ):
        self.info = info
        try:
            self.sql = get_selected_sql(T, info)
        except Exception as e:
            print(e)
            self.sql = None
        self.model: T = T
        self.page_size = page_size
        self.offset = (page - 1) * self.page_size

    def _paginate(self, sql: Select, limit: int = None, offset: int = None) -> Select:
        return sql.limit(limit or self.page_size).offset(offset or self.offset)

    def _order(self, sql: Select) -> Select:
        return sql.order_by(desc(self.model.id))

    @staticmethod
    async def _fetch_all(sql: Select, session: AsyncSession):
        return (await session.execute(sql)).scalars().unique().all()

    @staticmethod
    async def _fetch_first(sql: Select, session: AsyncSession):
        return (await session.execute(sql)).scalars().unique().first()

    async def fetch_one(self, obj_id: int, session: AsyncSession) -> T:
        return await self._fetch_first(
            self.sql().where(self.model.id == obj_id),
            session
        )

    async def filter_one(self, session: AsyncSession, filters: FilterType = None) -> T | None:
        return await self._fetch_first(
            self.sql().where(*filters),
            session
        )

    async def fetch_all(
            self,
            session: AsyncSession,
            inner: str = None,
            filters: FilterType = None,
            limit: int = None,
            offset: int = None
    ) -> Sequence[T]:
        sql = self.sql(inner)
        if filters:
            sql = sql.where(*filters)
        return await self._fetch_all(
            self._order(self._paginate(sql, limit, offset)),
            session
        )

    async def list_items(
            self,
            session: AsyncSession,
            inner: str = None,
            filters: FilterType = None,
            limit: int = None,
            offset: int = None
    ) -> ListType[T]:
        items = await self.fetch_all(session, inner, filters, limit, offset)
        count = await self.count_items(session, filters)
        return ListType(
            items=items,
            count=count
        )

    async def count_items(self, session: AsyncSession, filters: FilterType = None) -> int:
        sql = select(func.count(self.model.id))
        if filters:
            sql = sql.where(*filters)
        return await self._fetch_first(sql, session)

    async def delete_item(self, obj_id: int, session: AsyncSession) -> None:
        await session.execute(
            delete(self.model).where(self.model.id == obj_id)
        )
        await session.commit()

    async def update_item(self, obj_id: int, values: dict, session: AsyncSession) -> None:
        await session.execute(
            update(self.model).where(self.model.id == obj_id).values(**values)
        )
        await session.commit()

    async def create_item(self, payload: dict | list[dict], session: AsyncSession) -> T | None:
        item_id = (await session.execute(
            insert(self.model).values(payload).returning(self.model.id)
        )).scalars().first()
        await session.commit()
        if not item_id:
            return None
        return self.model(
            id=item_id,
            **payload
        )


"""
This file defines actions, i.e. functions the URLs are mapped into
The @action(path) decorator exposed the function at URL:

    http://127.0.0.1:8000/{app_name}/{path}

If app_name == '_default' then simply

    http://127.0.0.1:8000/{path}

If path == 'index' it can be omitted:

    http://127.0.0.1:8000/

The path follows the bottlepy syntax.

@action.uses('generic.html')  indicates that the action uses the generic.html template
@action.uses(session)         indicates that the action uses the session
@action.uses(db)              indicates that the action uses the db
@action.uses(T)               indicates that the action uses the i18n & pluralization
@action.uses(auth.user)       indicates that the action requires a logged in user
@action.uses(auth)            indicates that the action requires the auth object

session, db, T, auth, and tempates are examples of Fixtures.
Warning: Fixtures MUST be declared with @action.uses({fixtures}) else your app will result in undefined behavior
"""

from py4web import action, request, abort, redirect, URL
from yatl.helpers import A
from .common import db, session, T, cache, auth, logger, authenticated, unauthenticated, flash
from py4web.utils.url_signer import URLSigner
from .models import get_user_email, get_user_name

url_signer = URLSigner(session)

@action('index')
@action.uses('index.html', db, auth.user, url_signer)
def index():
    db(db.posts.user_email == get_user_email()).update(temp_id="None")

    return dict(
        get_user_email_url=URL('get_current_user_email', signer=url_signer),
        get_user_name_url=URL('get_current_user_name', signer=url_signer),
        get_posts_url=URL('get_posts', signer=url_signer),
        add_post_url=URL('add_post', signer=url_signer),
        del_post_url=URL('del_post', signer=url_signer),
        get_likes_url=URL('get_likes', signer=url_signer),
        like_post_url=URL('like_post', signer=url_signer),
        dislike_post_url=URL('dislike_post', signer=url_signer)
    )

@action('get_posts')
@action.uses(url_signer.verify(), db)
def get_posts():
    posts = db(db.posts).select().as_list()
    return dict(posts=posts)

@action('get_likes')
@action.uses(url_signer.verify(), db)
def get_likes():
    post_id = request.params.get('post_id')
    assert post_id is not None
    likes = db(db.likes.post_id == post_id).select().as_list()
    return dict(likes=likes)

@action('like_post', method='POST')
@action.uses(url_signer.verify(), db, auth.user)
def like_post():
    post_id = request.json.get('post_id')
    remove = request.json.get('remove')
    assert post_id is not None
    assert remove is not None

    if post_id < 0:
        post_id = db(db.posts.temp_id == post_id).select(db.posts.id)[0].id

    if remove:
        db((db.likes.post_id == post_id) & (db.likes.user_email ==
           get_user_email()) & (db.likes.is_like == "true")).delete()
    else:
        db.likes.update_or_insert(
            ((db.likes.post_id == post_id) & (
                db.likes.user_email == get_user_email())),
            post_id=post_id,
            name=get_user_name(),
            is_like="true"
        )

    return "ok"

@action('dislike_post', method='POST')
@action.uses(url_signer.verify(), db, auth.user)
def dislike_post():
    post_id = request.json.get('post_id')
    remove = request.json.get('remove')
    assert post_id is not None
    assert remove is not None

    if post_id < 0:
        post_id = db(db.posts.temp_id == post_id).select(db.posts.id)[0].id

    if remove:
        db((db.likes.post_id == post_id) & (db.likes.user_email ==
           get_user_email()) & (db.likes.is_like == "false")).delete()
    else:
        db.likes.update_or_insert(
            ((db.likes.post_id == post_id) & (
                db.likes.user_email == get_user_email())),
            post_id=post_id,
            name=get_user_name(),
            is_like="false"
        )

    return "ok"

@action('get_current_user_email')
@action.uses(url_signer.verify(), db)
def get_current_user_email():
    return dict(user_email=get_user_email())

@action('get_current_user_name')
@action.uses(url_signer.verify(), db)
def get_current_user_name():
    return dict(user_name=get_user_name())

@action('add_post', method='POST')
@action.uses(url_signer.verify(), db, auth.user)
def add_post():
    name = get_user_name()
    content = request.json.get('content')
    temp_id = request.json.get('temp_id')

    assert content is not None
    db.posts.insert(
        name=name,
        content=content,
        temp_id=temp_id
    )
    return "ok"

@action('del_post', method='POST')
@action.uses(url_signer.verify(), db, auth.user)
def del_post():
    post_id = request.json.get('post_id')
    assert post_id is not None

    if post_id < 0:
        post_id = db(db.posts.temp_id == post_id).select(db.posts.id)[0].id

    db(db.posts.id == post_id).delete()
    db(db.likes.post_id == post_id).delete()
    return "ok"


class UndirectedGraphNode:
    def __init__(self, x):
        self.label = x
        self.neighbors = []

def build_graph(input_str: str, values: list) -> list:
    nodes = [UndirectedGraphNode(val) for val in values]
    str_temp = input_str.split('{')[1].split('}')[0]
    strs_to_set_neighbors = str_temp.split('#')
    for the_str in strs_to_set_neighbors:
        node_idx_plus1, *neighbors_idx_plus1 = [int(x) for x in the_str.split(',')]
        for neighbor_idx_plus1 in neighbors_idx_plus1:
            nodes[node_idx_plus1 - 1].neighbors.append(nodes[neighbor_idx_plus1 - 1])

    return nodes

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def __repr__(self):
        left = None if self.left is None else self.left.val
        right = None if self.right is None else self.right.val
        return '(D:{}, L:{}, R:{})'.format(self.val, left, right)

def build_tree_breadth_first(sequence):
    # Create a list of trees
    forest = [TreeNode(x) if x is not None else None for x in sequence]

    # Fix up the left- and right links
    count = len(forest)
    for index, tree in enumerate(forest):
        left_index = 2 * index + 1
        if left_index < count:
            tree.left = forest[left_index]

        right_index = 2 * index + 2
        if right_index < count:
            tree.right = forest[right_index]

    for index, tree in enumerate(forest):
        print('[{}]: {}'.format(index, tree))
    return forest[0]  # root

# Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

    def __repr__(self):
        return 'val:{} next:{}'.format(self.val, self.next.val if self.next else None)

def build_linked_list_from_array(vals):
    nodes = [ListNode(val) for val in vals]
    for i in range(len(nodes) - 1):
        nodes[i].next = nodes[i + 1]

    return nodes[0]


from collections import OrderedDict
import operator

number = int(input())
genresDict = OrderedDict()

Horror = 0
Romance = 0
Comedy = 0
Action = 0
Adventure = 0
History = 0

i=1
while i<=number:
    faveGenres = str(input())
    faveGenres = faveGenres.split(' ')

    for letter in faveGenres:
        if letter == "Horror" :
            Horror+=1
        if letter == "Romance"  :
            Romance+=1
        if letter == "Comedy":
            Comedy+=1
        if letter == "Action":
            Action+=1
        if letter == "Adventure":
            Adventure+=1
        if letter == "History":
            History+=1
    i+=1

genresDict["Horror"] =  Horror
genresDict["Romance"] =  Romance
genresDict["Comedy"] =  Comedy
genresDict["Action"] =  Action
genresDict["Adventure"] =  Adventure
genresDict["History"] =  History

genresDict = OrderedDict(sorted(genresDict.items(), key=lambda x: (-x[1], x[0])))

for key, value in genresDict.items():
    print(key , ":", value)


import sys

def main(stringspace, strlength):
    hold = []

    for i in range(int(strlength)):
        if stringspace[i] == ' ':
            hold.append("%20")
        else:
            hold.append(stringspace[i])

    string = ''.join(hold)
    print(string)

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])


#!/usr/bin/env python

import mpi4py
import numpy as np
import sys

from mpi4py import MPI

def find_primes(high: int):

    numbers = np.arange(high + 1, dtype=int)
    mask = np.ones_like(numbers, dtype=bool)
    mask[0:2] = False
    for i in range(2, int(np.sqrt(high)) + 1):
        if mask[i]:
            mask[i*i::i] = False

    return numbers[mask]

def find_primes_interval(low: int, high: int, dividers: list):

    numbers = np.arange(low, high + 1, dtype=int)
    mask = np.ones_like(numbers, dtype=bool)
    for n in numbers:
        i = n - low
        for d in dividers:
            if n % d == 0:
                mask[i] = False
                break

    return numbers[mask]

def find_primes_parallel(high: int):

    comm = MPI.COMM_WORLD
    rank = comm.Get_rank()
    size = comm.Get_size()

    limit_B = int(np.sqrt(high))
    dividers_B = find_primes(limit_B)
    primes = np.copy(dividers_B)

    if rank == 0:
        # Calculate the interval length
        n_workers = size - 1
        interval_length = int(np.ceil((high - limit_B) / n_workers))

        # Send intervals to worker processes
        low_i = limit_B + 1
        high_i = limit_B + interval_length
        for i in range(1, n_workers):
            comm.send(low_i, dest=i)
            comm.send(high_i, dest=i)
            low_i += interval_length
            high_i += interval_length
        comm.send(low_i, dest=n_workers)
        comm.send(high, dest=n_workers)
    else:
        # Worker process
        low = comm.recv(source=0)
        high = comm.recv(source=0)

        primes_C = find_primes_interval(low, high, dividers_B)
        comm.send(primes_C, dest=0)

    if rank == 0:
        # Master process
        for i in range(1, size):
            primes_C = comm.recv(source=i)
            primes = np.concatenate((primes, primes_C))

        # Print the primes
        print(f"There are {len(primes)} primes up to {high}:\n{np.sort(primes)}")

    MPI.Finalize()

if __name__ == "__main__":
    high = int(sys.argv[1])
    find_primes_parallel(high)


import pygame
from pygame.locals import *
import sys
import os
import time

pygame.init()
pygame.display.set_caption("game")
SCREEN_RECT = Rect(0, 0, 640, 480)
screen = pygame.display.set_mode(SCREEN_RECT.size)
font = pygame.font.Font('ロゴたいぷゴシック.otf',30)
clock = pygame.time.Clock()
CS = 32
SCREEN_NCOL = SCREEN_RECT.width//CS
SCREEN_NROW = SCREEN_RECT.height//CS
SCREEN_CENTER_X = SCREEN_RECT.width//2//CS
SCREEN_CENTER_Y = SCREEN_RECT.height//2//CS

#playerstatas = [最大HP MAXHP,HP,最大MP MAXMP,MP,耐性 RES,筋力 STR,魔力 MGC,知力 INT,技巧 TEC,速さ QUI,幸運 LUK]
class playerstatas:
    MAXHP = 0
    MAXMP = 0
    HP = 0
    MP = 0
    RES = 0
    STR = 0
    MGC = 0
    INT = 0
    TEC = 0
    QUI = 0
    LUK = 0
class humanstatas:
    MAXHP = 20
    MAXMP = 10
    HP = 20
    MP = 10
    RES = 10
    STR = 10
    MGC = 10
    INT = 10
    TEC = 10
    QUI = 10
    LUK = 10
class elfstatas:
    MAXHP = 15
    MAXMP = 15
    HP = 15
    MP = 15
    RES = 10
    STR = 5
    MGC = 15
    INT = 15
    TEC = 5
    QUI = 10
    LUK = 10
class dowarfstatas:
    MAXHP = 25
    MAXMP = 5
    HP = 25
    MP = 5
    RES = 15
    STR = 20
    MGC = 5
    INT = 5
    TEC = 15
    QUI = 5
    LUK = 5
class beastmanstatas:
    MAXHP = 20
    MAXMP = 10
    HP = 20
    MP = 10
    RES = 10
    STR = 15
    MGC = 0
    INT = 5
    TEC = 10
    QUI = 20
    LUK = 10
class plantmanstatas:
    MAXHP = 30
    MAXMP = 20
    HP = 30
    MP = 20
    RES = 5
    STR = 5
    MGC = 20
    INT = 5
    TEC = 5
    QUI = 5
    LUK = 5
class dragonoidstatas:
    MAXHP = 20
    MAXMP = 10
    HP = 20
    MP = 10
    RES = 25
    STR = 10
    MGC = 5
    INT = 10
    TEC = 10
    QUI = 5
    LUK = 5
class wedystatas:
    MAXHP = 15
    MAXMP = 10
    HP = 15
    MP = 10
    RES = 10
    STR = 5
    MGC = 15
    INT = 15
    TEC = 10
    QUI = 15
    LUK = 5

def load_image(filename):
    filename = os.path.join("data", filename)
    image = pygame.image.load(filename)
    image = image.convert_alpha()
    return image

def load_image_color(filename):
    filename = os.path.join("data", filename)
    image = pygame.image.load(filename)
    image = image.convert()
    colorkey = image.get_at((0, 0))
    image.set_colorkey(colorkey, RLEACCEL)
    return image

def get_image(sheet, x, y, width, height, useColorKey=False):
    image = pygame.Surface([width, height])
    image.blit(sheet, (0, 0), (x, y, width, height))
    image = image.convert()
    if useColorKey:
        colorkey = image.get_at((0, 0))
        image.set_colorkey(colorkey, RLEACCEL)
    #image = pygame.transform.scale(image, (32*2, 32*2))
    return image

def bigin():
  while True:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
      if event.type == KEYDOWN:
          if event.key == K_SPACE:
            return
      title=load_image("title.png")
      rect_title=title.get_rect()
      screen.blit(title,rect_title)
      text=font.render("スペースキーでゲーム開始",True,(0,0,0),300)
      screen.blit(text,[150,350])
      pygame.display.update()
      clock.tick(30)

def charamake():
  global playerstatas,player
  while True:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
      if event.type == KEYDOWN:
          if event.key == K_1:
            playerstatas=humanstatas
            while True:
              for event in pygame.event.get():
                if event.type == pygame.QUIT:
                  pygame.quit()
                  sys.exit()
                if event.type == KEYDOWN:
                  if event.key == K_ESCAPE:
                      playerstatas=[]
                      main()
                  if event.key == K_1:
                    player=Player("$yuhinamv146.png")
                    return player
                  if event.key == K_2:
                    player=Player("$yuhinamv218.png")
                    return player
              race=load_image("race.png")
              rect_race=race.get_rect()
              screen.blit(race,rect_race)
              note_h=load_image_color("note_h.png")
              (x,y)=(5,106)
              screen.blit(note_h,(x,y))
              text=font.render("主人公の性別を入力してください",True,(0,0,0),70)
              text2=font.render("1.男性",True,(0,0,0))
              text3=font.render("2.女性",True,(0,0,0))
              screen.blit(text,[85,50])
              screen.blit(text2,[350,130])
              screen.blit(text3,[480,130])
              human_m=load_image("yh146.png")
              (x,y)=(305,190)
              screen.blit(human_m,(x,y))
              human_f=load_image("yh218.png")
              (x,y)=(430,203)
              screen.blit(human_f,(x,y))
              pygame.display.update()
              clock.tick(30)
          if event.key == K_2:
            playerstatas=elfstatas
            while True:
              for event in pygame.event.get():
                if event.type == pygame.QUIT:
                  pygame.quit()
                  sys.exit()
                if event.type == KEYDOWN:
                  if event.key == K_ESCAPE:
                      playerstatas=[]
                      main()
                  if event.key == K_1:
                    player=Player("$yuhinamv042.png")
                    return player
                  if event.key == K_2:
                    player=Player("$yuhinamv043.png")
                    return player
              race=load_image("race.png")
              rect_race=race.get_rect()
              screen.blit(race,rect_race)
              note_e=load_image_color("note_e.png")
              (x,y)=(5,106)
              screen.blit(note_e,(x,y))
              text=font.render("主人公の性別を入力してください",True,(0,0,0),70)
              text2=font.render("1.男性",True,(0,0,0))
              text3=font.render("2.女性",True,(0,0,0))
              screen.blit(text,[85,50])
              screen.blit(text2,[370,130])
              screen.blit(text3,[500,130])
              elf_f=load_image("yh043.png")
              (x,y)=(450,190)
              screen.blit(elf_f,(x,y))
              elf_m=load_image("yh042.png")
              (x,y)=(325,190)
              screen.blit(elf_m,(x,y))
              pygame.display.update()
              clock.tick(30)
          if event.key == K_3:
            playerstatas=dowarfstatas
            while True:
              for event in pygame.event.get():
                if event.type == pygame.QUIT:
                  pygame.quit()
                  sys.exit()
                if event.type == KEYDOWN:
                  if event.key == K_ESCAPE:
                      playerstatas=[]
                      main()
                  if event.key == K_1:
                    player=Player("$yuhinamv019.png")
                    return player
                  if event.key == K_2:
                    player=Player("$yuhinamv064.png")
                    return player
              race=load_image("race.png")
              rect_race=race.get_rect()
              screen.blit(race,rect_race)
              note_d=load_image_color("note_d.png")
              (x,y)=(5,106)
              screen.blit(note_d,(x,y))
              text=font.render("主人公の性別を入力してください",True,(0,0,0),70)
              text2=font.render("1.男性",True,(0,0,0))
              text3=font.render("2.女性",True,(0,0,0))
              screen.blit(text,[85,50])
              screen.blit(text2,[370,130])
              screen.blit(text3,[500,130])
              dwarf_f=load_image("yh064.png")
              (x,y)=(450,190)
              screen.blit(dwarf_f,(x,y))
              dwarf_m=load_image("yh019.png")
              (x,y)=(325,190)
              screen.blit(dwarf_m,(x,y))
              pygame.display.update()
              clock.tick(30)
          if event.key == K_4:
            playerstatas=beastmanstatas
            while True:
              for event in pygame.event.get():
                if event.type == pygame.QUIT:
                  pygame.quit()
                  sys.exit()
                if event.type == KEYDOWN:
                  if event.key == K_ESCAPE:
                      playerstatas=[]
                      main()
                  if event.key == K_1:
                    player=Player("$yuhinamv237.png")
                    return player
                  if event.key == K_2:
                    player=Player("$yuhinamv341.png")
                    return player
              race=load_image("race.png")
              rect_race=race.get_rect()
              screen.blit(race,rect_race)
              note_b=load_image_color("note_b.png")
              (x,y)=(5,106)
              screen.blit(note_b,(x,y))
              text=font.render("主人公の性別を入力してください",True,(0,0,0),70)
              text2=font.render("1.男性",True,(0,0,0))
              text3=font.render("2.女性",True,(0,0,0))
              screen.blit(text,[85,50])
              screen.blit(text2,[370,130])
              screen.blit(text3,[500,130])
              beastman_f=load_image("yh341.png")
              (x,y)=(450,200)
              screen.blit(beastman_f,(x,y))
              beastman_m=load_image("yh237.png")
              (x,y)=(310,168)
              screen.blit(beastman_m,(x,y))
              pygame.display.update()
              clock.tick(30)
          if event.key == K_5:
            playerstatas=plantmanstatas
            while True:
              for event in pygame.event.get():
                if event.type == pygame.QUIT:
                  pygame.quit()
                  sys.exit()
                if event.type == KEYDOWN:
                  if event.key == K_ESCAPE:
                      playerstatas=[]
                      main()
                  if event.key == K_1:
                    player=Player("$yuhinamv156.png")
                    return player
                  if event.key == K_2:
                    player=Player("$yuhinamv296.png")
                    return player
              race=load_image("race.png")
              rect_race=race.get_rect()
              screen.blit(race,rect_race)
              note_p=load_image_color("note_p.png")
              (x,y)=(5,106)
              screen.blit(note_p,(x,y))
              text=font.render("主人公の性別を入力してください",True,(0,0,0),70)
              text2=font.render("1.男性",True,(0,0,0))
              text3=font.render("2.女性",True,(0,0,0))
              screen.blit(text,[85,50])
              screen.blit(text2,[350,130])
              screen.blit(text3,[480,130])
              plantman_f=load_image("yh296.png")
              (x,y)=(430,190)
              screen.blit(plantman_f,(x,y))
              plantman_m=load_image("yh156.png")
              (x,y)=(305,190)
              screen.blit(plantman_m,(x,y))
              pygame.display.update()
              clock.tick(30)
          if event.key == K_6:
            playerstatas=dragonoidstatas
            while True:
              for event in pygame.event.get():
                if event.type == pygame.QUIT:
                  pygame.quit()
                  sys.exit()
                if event.type == KEYDOWN:
                  if event.key == K_ESCAPE:
                      playerstatas=[]
                      main()
                  if event.key == K_1:
                    player=Player("$yuhinamv329.png")
                    return player
                  if event.key == K_2:
                    player=Player("$yuhinamv073.png")
                    return player
              race=load_image("race.png")
              rect_race=race.get_rect()
              screen.blit(race,rect_race)
              note_dra=load_image_color("note_dra.png")
              (x,y)=(5,106)
              screen.blit(note_dra,(x,y))
              text=font.render("主人公の性別を入力してください",True,(0,0,0),70)
              text2=font.render("1.男性",True,(0,0,0))
              text3=font.render("2.女性",True,(0,0,0))
              screen.blit(text,[85,50])
              screen.blit(text2,[370,130])
              screen.blit(text3,[500,130])
              dragonoid_f=load_image("yh073.png")
              (x,y)=(450,200)
              screen.blit(dragonoid_f,(x,y))
              dragonoid_m=load_image("yh329.png")
              (x,y)=(305,180)
              screen.blit(dragonoid_m,(x,y))
              pygame.display.update()
              clock.tick(30)
          if event.key == K_7:
            playerstatas=wedystatas
            while True:
              for event in pygame.event.get():
                if event.type == pygame.QUIT:
                  pygame.quit()
                  sys.exit()
                if event.type == KEYDOWN:
                  if event.key == K_ESCAPE:
                      playerstatas=[]
                      main()
                  if event.key == K_1:
                    player=Player("$yuhinamv084.png")
                    return player
                  if event.key == K_2:
                    player=Player("$yuhinamv085.png")
                    return player
              race=load_image("race.png")
              rect_race=race.get_rect()
              screen.blit(race,rect_race)
              note_w=load_image_color("note_w.png")
              (x,y)=(5,106)
              screen.blit(note_w,(x,y))
              text=font.render("主人公の性別を入力してください",True,(0,0,0),70)
              text2=font.render("1.男性",True,(0,0,0))
              text3=font.render("2.女性",True,(0,0,0))
              screen.blit(text,[85,50])
              screen.blit(text2,[370,130])
              screen.blit(text3,[500,130])
              wedy_f=load_image("yh085.png")
              (x,y)=(450,180)
              screen.blit(wedy_f,(x,y))
              wedy_m=load_image("yh084.png")
              (x,y)=(315,180)
              screen.blit(wedy_m,(x,y))
              pygame.display.update()
              clock.tick(30)
    charamake=load_image("charamake.png")
    rect_charamake=charamake.get_rect()
    screen.blit(charamake,rect_charamake)
    text=font.render("主人公の種族を入力して下さい",True,(0,0,0),70)
    text2=font.render("1.ヒューマン",True,(0,0,0),70)
    text3=font.render("2.エルフ",True,(0,0,0),70)
    text4=font.render("3.ドワーフ",True,(0,0,0),70)
    text5=font.render("4.獣人",True,(0,0,0),70)
    text6=font.render("5.植物人",True,(0,0,0),70)
    text7=font.render("6.竜人",True,(0,0,0),70)
    text8=font.render("7.ウェディ",True,(0,0,0),70)
    screen.blit(text,[110,50])
    screen.blit(text2,[250,90])
    screen.blit(text3,[250,130])
    screen.blit(text4,[250,170])
    screen.blit(text5,[250,210])
    screen.blit(text6,[250,250])
    screen.blit(text7,[250,290])
    screen.blit(text8,[250,330])
    pygame.display.update()
    clock.tick(30)

def menu():
  while True:
    text=font.render("メニュー",True,(255,255,255),30)
    text2=font.render("1ステータス",True,(255,255,255),30)
    pygame.draw.rect(screen, (0,0,0), (20,20,200,120))
    screen.blit(text,[25,25])
    screen.blit(text2,[25,60])
    pygame.display.update()
    for event in pygame.event.get():
      if event.type == QUIT:
        pygame.quit()
        sys.exit()
      if event.type == KEYDOWN:
        if event.key == K_z:
          return
        if event.key == K_1:
          while True:
            plst = str('playerstatas.MAXHP','playerstatas.HP')
            text3=font.render(plst,True,(255,255,255))
            pygame.draw.rect(screen, (0,0,0), (70,140,400,120))
            screen.blit(text3,[75,200])
            pygame.display.update()
            for event in pygame.event.get():
              if event.type == QUIT:
                pygame.quit()
                sys.exit()
              if event.type == KEYDOWN:
                if event.key == K_z:
                    return
DIR_DOWN = 0
DIR_LEFT = 1
DIR_RIGHT = 2
DIR_UP = 3
ANIM_WAIT_COUNT = 8

class Player(pygame.sprite.Sprite):
    def __init__(self, filename):
        pygame.sprite.Sprite.__init__(self)
        sheet = load_image(filename)
        self.images = [[], [], [], []]
        for row in range(0, 4):
            for col in [0, 1, 2, 1]:
                self.images[row].append(get_image(sheet, 0 + 32 * col, 0 + 32 * row, 32, 32, True))
        self.image = self.images[DIR_DOWN][0]
        self.rect = self.image.get_rect()
        self.rect.x = SCREEN_CENTER_X * CS
        self.rect.y = SCREEN_CENTER_Y * CS
        self.frame = 0
        self.anim_count = 0
        self.dir = DIR_DOWN
        self.wx, self.wy = 1, 1
    def update(self):
        self.anim_count += 1
        if self.anim_count >= ANIM_WAIT_COUNT:
            self.anim_count = 0
            self.frame += 1
            if self.frame > 3:
                self.frame = 0
        self.image = self.images[self.dir][self.frame]

class Map:
    def __init__(self, screen, filename, player):
        self.ncol = 0
        self.nrow = 0
        self.screen = screen
        self.player = player
        self.mapData = []
        self.readMap(filename)
        self.sheet0 = load_image("pipo-map001.png")
        self.sheet1 = load_image("pipo-map001_at-umi.png")
        self.sheet2 = load_image("pipo-map001_at-yama2.png")
        self.sheet3 = load_image("base.png")
        self.images = []
#平和な大陸
        self.images.append([self.sheet1, 0, 0])  # naraku(0)
        self.images.append([self.sheet0, 0, 0])  # shiba (1)
        self.images.append([self.sheet0, 2, 9])  # gate (2)
        self.images.append([self.sheet1, 0, 4])  # umi (3)
        self.images.append([self.sheet0, 1, 1])  # mori (4)
        self.images.append([self.sheet0, 1, 7])  # town_left (5)
        self.images.append([self.sheet0, 2, 7])  # town_right (6)
        self.images.append([self.sheet0, 1, 9])  # sinden (7)
        self.images.append([self.sheet0, 6, 2])  # doukutu (8)
#町
        self.images.append([self.sheet3, 0, 46])  # yuka (9)
        self.images.append([self.sheet3, 1, 46])  # renga (10)
        self.images.append([self.sheet3, 0, 98])  # table (11)
        self.images.append([self.sheet3, 2, 112])  # bedue (12)
        self.images.append([self.sheet3, 2, 113])  # bedsita (13)
        self.images.append([self.sheet3, 0, 95])  # bukiya (14)
        self.images.append([self.sheet3, 1, 95])  # bouguya (15)
        self.images.append([self.sheet3, 2, 95])  # douguya (16)
        self.images.append([self.sheet3, 1, 115])  # isu (17)
        self.images.append([self.sheet3, 3, 98])  # tablesita (18)

    def readMap(self, filename):
        with open(filename) as fi:
            line = fi.readline()
            self.ncol, self.nrow = [int(tok) for tok in line.split(",")]
            for row in range(self.nrow):
                line = fi.readline()
                self.mapData.append([int(tok) for tok in line.split(",")])
    def drawImage(self, idx, sx, sy):
        sheet, x, y = self.images[idx]
        self.screen.blit(sheet, (sx * 32, sy * 32), (x * 32, y * 32, 32, 32))
    def draw(self):
        screen_wx = self.player.wx - SCREEN_CENTER_X
        screen_wy = self.player.wy - SCREEN_CENTER_Y
        for sy in range(SCREEN_NROW):
            for sx in range(SCREEN_NCOL):
                wx = screen_wx + sx
                wy = screen_wy + sy
                if not (0 <= wx < self.ncol) or not (0 <= wy < self.nrow):
                    self.drawImage(0, sx, sy)  # naraku
                else:
                    idx = self.mapData[wy][wx]
                    self.drawImage(1, sx, sy)  # shiba
                    self.drawImage(idx, sx, sy)
    def can_move_at(self, wx, wy):
        if not (0 <= wx < self.ncol) or not (0 <= wy < self.nrow):
            return False
        idx = self.mapData[wy][wx]
        if idx == 0 or idx == 3 or idx == 10 or idx ==11 or idx == 18:  # naraku umi renga table
            return False
        return True

def main():
    bigin()
    charamake()
    group = pygame.sprite.RenderUpdates()
    group.add(player)
    fieldMap = Map(screen, "field01.map", player)
    player.wx += 10
    player.wy += 5

    while True:
        clock.tick(60)
        screen.fill((0, 255, 0))
        fieldMap.draw()
        group.update()
        group.draw(screen)
        pygame.display.update()
        clock.tick(30)
        pressed_key=pygame.key.get_pressed()
        if player.wx == 29 and player.wy == 33 or player.wx == 30 and player.wy == 33:
            player.wy += 89
        if player.wx == 28 and player.wy == 127 or player.wx == 29 and player.wy == 127 or player.wx == 30 and player.wy == 127 or player.wx == 31 and player.wy == 127:
            player.wy -= 93

        if pressed_key[K_s]:
            if fieldMap.can_move_at(player.wx, player.wy + 1):
                player.dir = DIR_DOWN
                player.wy += 1
                time.sleep(0.12)
        if pressed_key[K_a]:
            if fieldMap.can_move_at(player.wx - 1, player.wy):
                player.dir = DIR_LEFT
                player.wx -= 1
                time.sleep(0.12)
        if pressed_key[K_d]:
            if fieldMap.can_move_at(player.wx + 1, player.wy):
                player.dir = DIR_RIGHT
                player.wx += 1
                time.sleep(0.12)
        if pressed_key[K_w]:
            if fieldMap.can_move_at(player.wx, player.wy - 1):
                player.dir = DIR_UP
                player.wy -= 1
                time.sleep(0.12)
        if pressed_key[K_x]:
            menu()

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()
if __name__ == '__main__':
    main()


# Licensed under a 3-clause BSD style license - see LICENSE.rst

from astropy import log
import inspect
import numpy as np
from sofia_redux.toolkit.utilities.fits import gethdul
from sofia_redux.toolkit.fitting.polynomial import poly1d
from sofia_redux.toolkit.image.adjust import rotate90

__all__ = ['FlatBase', 'FlatInfo', 'Flat']

class FlatBase:

    def __init__(self, filename):
        self.shape = None
        self._filename = None
        self._header = None
        self._data = None
        self._ishell = None
        self.guesspos = None
        self.omask = None
        self.orders = None
        self.norders = None
        self.edgedeg = None
        self.edgecoeffs = None
        self.xranges = None
        self.rotation = None
        self.ybuffer = None
        self._default_xranges = None
        self._default_guesspos = None
        self.filename = str(filename)

    @property
    def filename(self):
        return self._filename

    @filename.setter
    def filename(self, value):
        value = value.strip()
        self._load_file(value)

    def __repr__(self):
        attributes = [x for x in dir(self) if not x.startswith('_')]
        s = ''
        for attrib in attributes:
            a = getattr(self, attrib)
            if not inspect.ismethod(a):
                if isinstance(a, np.ndarray):
                    a = '%s %s of %s' % (np.ndarray, a.shape, a.dtype)
                s += '%s: %s\n' % (attrib, repr(a))
        return s

    def _set_order_info(self):
        orders = np.array(
            [int(x) for x in self._header['ORDERS'].split(',')])
        norders = len(orders)
        edgedeg = int(self._header['EDGEDEG'])

        xranges = np.zeros((norders, 2), dtype=int)
        edgecoeffs = np.full((norders, 2, edgedeg + 1), np.nan)

        test = 'ODR%s_T*' % str(orders[0]).zfill(2)
        self._ishell = len(self._header.get(test)) == 0
        prefix, nz = ('OR', 3) if self._ishell else ('ODR', 2)

        for i, order in enumerate(orders):
            ostr = prefix + str(order).zfill(nz)
            bname = '%s_B*' % ostr
            tname = '%s_T*' % ostr
            xname = '%s_XR' % ostr
            edgecoeffs[i, 0] = list(self._header[bname].values())
            edgecoeffs[i, 1] = list(self._header[tname].values())
            xranges[i] = [int(x) for x in self._header[xname].split(',')]

        self.orders = orders
        self.norders = norders
        self.edgedeg = edgedeg
        self.edgecoeffs = edgecoeffs
        self.xranges = xranges
        self._default_xranges = xranges.copy()
        self.default_guess_position()

    def _load_file(self, filename):
        hdul = gethdul(filename, verbose=True)
        if hdul is None:
            raise ValueError("Could not load: %s" % filename)
        self._header = hdul[0].header.copy()
        if hdul[0].data is not None:
            self._data = hdul[0].data.copy()
        else:
            self._data = None
        self._filename = filename
        self._set_order_info()
        self.parse_info()

    def parse_info(self):  # pragma: no cover
        pass

    def generate_order_mask(self, offset=0):
        """
        Generate an order mask based on xranges and edge coefficients

        Notes
        -----
        No rotation is applied if we're generating the order mask.  The
        parameters required for order mask generation are already correct.

        Parameters
        ----------
        offset : int, optional
            If provided, will be added to the x coordinate before
            generating the edge coefficient polynomials.  This is intended
            to allow reusing edge coordinates for a shifted array in
            the x-direction.
        """
        nrow, ncol = self.shape
        yy, xx = np.mgrid[:nrow, :ncol]
        fillmask = np.empty(self.shape, dtype=bool)
        omask = np.zeros(self.shape, dtype=int)
        for i, order in enumerate(self.orders):
            fillmask[...] = False
            x = np.arange(self.xranges[i, 0], self.xranges[i, 1] + 1) + offset
            botedge = poly1d(x, self.edgecoeffs[i, 0])
            topedge = poly1d(x, self.edgecoeffs[i, 1])
            column_ok = topedge <= nrow - 0.5
            column_ok &= botedge >= -0.5
            botedge = np.clip(np.floor(botedge), 0, nrow).astype(int)
            topedge = np.clip(np.ceil(topedge), 0, nrow).astype(int)
            xl, xu = self.xranges[i]
            fillmask[:, xl:xu + 1] = ((yy[:, xl:xu + 1] <= topedge)
                                      & (yy[:, xl:xu + 1] >= botedge)
                                      & column_ok[None])
            omask[fillmask] = order
        return omask

    @staticmethod
    def create_order_mask(shape, orders, edgecoeffs, xranges):
        """
        Create an ordermask

        Parameters
        ----------
        shape : 2-tuple
            (nrow, ncol) shape of the ordermask
        orders : array_like of int
            (norders,) array of orders
        edgecoeffs : array_like of float
            (norders, 2)
        xranges : array_like of int
            (norders, 2)

        Returns
        -------
        ordermask : numpy.ndarray
            (nrow, ncol) of int
        """
        nrow, ncol = shape
        yy, xx = np.mgrid[:nrow, :ncol]
        fillmask = np.empty(shape, dtype=bool)
        omask = np.zeros(shape, dtype=int)
        for i, order in enumerate(orders):
            fillmask[...] = False
            x = np.arange(xranges[i, 0], xranges[i, 1] + 1)
            botedge = poly1d(x, edgecoeffs[i, 0])
            topedge = poly1d(x, edgecoeffs[i, 1])
            column_ok = topedge <= nrow - 0.5
            column_ok &= botedge >= -0.5
            botedge = np.clip(np.floor(botedge), 0, nrow).astype(int)
            topedge = np.clip(np.ceil(topedge), 0, nrow).astype(int)
            xl, xu = xranges[i]
            fillmask[:, xl:xu + 1] = ((yy[:, xl:xu + 1] <= topedge)
                                      & (yy[:, xl:xu + 1] >= botedge)
                                      & column_ok[None])
            omask[fillmask] = order
        return omask

    def default_guess_position(self):
        """Sets default guess positions for each order

        Notes
        -----
        xranges is also reset to default values
        """
        self.xranges = self._default_xranges.copy()
        guesspos = np.zeros((self.norders, 2), dtype=int)
        for i in range(self.norders):
            guesspos[i, 0] = self.xranges[i].mean()
            botedge = poly1d(guesspos[i, 0], self.edgecoeffs[i, 0])
            topedge = poly1d(guesspos[i, 0], self.edgecoeffs[i, 1])
            guesspos[i, 1] = (topedge + botedge) / 2
        self.guesspos = guesspos
        self._default_guesspos = guesspos.copy()

    def adjust_guess_position(self, image, order, ybuffer=3):
        """
        Updates guess positions and xranges via image correlation

        The correlation occurs only in the spatial dimension (y).

        Parameters
        ----------
        image : array_like of float
            (nrow, ncol) Image with which to perform the correlation.
        order : int
            The order from the ordermask with which to perform the
            correlation.
        ybuffer : int, optional
            The number of pixels to buffer form the top and bottom
            of the array.
        """
        image = np.asarray(image, dtype=float)

        omask = np.equal(self.omask, order)
        if not omask.any():
            raise ValueError("Order %i not present in ordermask" % order)
        oi = np.argwhere(self.orders == order)
        if oi.shape[0] == 0:
            raise ValueError("Order %i not present in orders" % order)
        oi = oi[0, 0]

        x = np.arange(self.xranges[oi, 0], self.xranges[oi, 1] + 1)
        botedge = poly1d(x, self.edgecoeffs[oi, 0])
        topedge = poly1d(x, self.edgecoeffs[oi, 1])
        slith_pix = int(np.ceil(max(topedge - botedge)))

        # Determine the top and bottom row of the subimage to clip out
        topidx = int(np.round(topedge).max()) + slith_pix + 1
        botidx = int(np.round(botedge).min()) - slith_pix
        topidx = np.clip(topidx, 0, self.shape[0])
        botidx = np.clip(botidx, 0, self.shape[0])

        subimg = image[botidx:topidx]
        subomask = omask[botidx:topidx]

        # shifts are in the y-direction only
        subshape = subimg.shape
        nshifts = slith_pix * 2 + 1
        shifts = np.arange(nshifts) - slith_pix
        cross_corr = np.zeros(nshifts)

        for i, s in enumerate(shifts):
            hbot = np.clip(-s, 0, subshape[0])
            htop = np.clip(subshape[0] - s, 0, subshape[0])
            mbot = np.clip(s, 0, subshape[0])
            mtop = np.clip(subshape[0] + s, 0, subshape[0])
            cross_corr[i] = np.sum(subimg[hbot:htop] * subomask[mbot:mtop])
        offset = shifts[np.argmax(cross_corr)]

        self.guesspos = self._default_guesspos.copy()
        self.guesspos[:, 1] -= offset

        # If we shift by this amount then xranges may need to be updated
        self.xranges = self._default_xranges.copy()
        dy = ybuffer - 1
        for oi, order in enumerate(self.orders):
            xrange = self.xranges[oi]
            x = np.arange(xrange[1] - xrange[0] + 1) + xrange[0]
            botedge = poly1d(x, self.edgecoeffs[oi, 0]) - offset
            topedge = poly1d(x, self.edgecoeffs[oi, 1]) - offset
            idx = (botedge > dy) & (topedge < (image.shape[0] - dy))
            if not idx.any():
                log.warning("Order %i shifted past y-buffer" % order)
                xrange[:] = -1, -1
            else:
                xrange[:] = np.min(x[idx]), np.max(x[idx])

class FlatInfo(FlatBase):

    def __init__(self, filename):
        super().__init__(filename)
        self.modename = None
        self.slith_arc = None
        self.slith_pix = None
        self.slith_range = None
        self.rppix = None
        self.ps = None
        self.fixed = None
        self.step = None
        self.flatfrac = None
        self.comwin = None
        self.norm_nxg = None
        self.norm_nyg = None
        self.oversamp = None
        self.ycororder = None

    def parse_info(self):
        self.omask = self._data.astype(int)
        self.shape = self.omask.shape
        h = self._header
        # Standard keywords without logic (name, [rename], type)
        get = [
            ('modename', str),
            ('rotation', int),  # IDL ROTATE value
            ('slth_arc', 'slith_arc', float),  # Slit length in arcseconds
            ('slth_pix', 'slith_pix', float),  # Slit length in pixels
            ('rppix', float),  # Resolving power per pixel
            ('pltscale', 'ps', float),  # Plate scale (arcseconds per pixel)
            ('fixed', bool),
            ('step', int),  # Edge find step size
            ('flatfrac', float),  # Edge find fraction
            ('comwin', int),  # Center-Of-Mass window
            ('norm_nxg', int),  # fiterpolate grid definition
            ('norm_nyg', int),  # fiterpolate grid definition
            ('oversamp', float),  # normspecflat (not actually used)
            ('ybuffer', int),  # buffer pixels (rows)
            ('ycorordr', 'ycororder', int)]

        defaults = {str: '', float: 0.0, int: 0, bool: False}
        for x in get:
            name = x[0] if len(x) == 2 else x[1]
            dtype = type(defaults[x[-1]])
            value = dtype(h.get(x[0], defaults[dtype]))
            setattr(self, name, value)

        if self.rotation is not None:
            # When reading the ordermask from the flatinfo file, rotation
            # should be applied.
            self.omask = rotate90(self.omask, self.rotation)

        # Begin extracting those that require a little parsing
        self.slith_range = np.array(
            [int(x) for x in h.get('SLTH_RNG', '').split(',')])

class Flat(FlatBase):

    def __init__(self, filename):
        self.image = None
        self.variance = None
        self.flags = None
        self.modename = None
        self.slith_arc = None
        self.slith_pix = None
        self.slitw_arc = None
        self.slitw_pix = None
        self.rp = None
        self.ps = None
        self.rms = None
        super().__init__(filename)

    def parse_info(self):
        # do not copy data
        if self._data.ndim == 3:
            ndata = self._data.shape[0]
            self.image = self._data[0]
            self.shape = self.image.shape
            self.variance = self._data[1] if ndata > 1 else None
            self.flags = self._data[2] if ndata > 2 else None
        else:
            self.image = self._data
            self.shape = self.image.shape
            self.variance = self.flags = None

        # Standard keywords without logic (name, [rename], type)
        get = [
            ('modename', str),
            ('rotation', int),  # IDL ROTATE value
            ('slth_arc', 'slith_arc', float),  # Slit length in arcseconds
            ('slth_pix', 'slith_pix', float),  # Slit length in pixels
            ('sltw_arc', 'slitw_arc', float),  # Slit length in arcseconds
            ('sltw_pix', 'slitw_pix', float),  # Slit length in pixels
            ('rp', float),  # Resolving power
            ('pltscale', 'ps', float)]  # Plate scale (arcseconds per pixel)]

        h = self._header
        defaults = {str: '', float: 0.0, int: 0, bool: False}
        for x in get:
            name = x[0] if len(x) == 2 else x[1]
            dtype = type(defaults[x[-1]])
            value = dtype(h.get(x[0], defaults[dtype]))
            setattr(self, name, value)

        prefix = 'OR' if self._ishell else 'ODR'
        self.rms = np.full(self.norders, np.nan)
        for i, order in enumerate(self.orders):
            self.rms[i] = h.get('%s%i' % (prefix, order), np.nan)
        self.omask = self.create_order_mask(
            self.shape, self.orders, self.edgecoeffs, self.xranges)


from . import _ok as base

class Overlay(base.sendhelp):

    method_Disable:str
    method_Enable:str
    method_GetGridHighlightObjectsForTest:str
    method_GetHighlightObjectForTest:str
    method_GetSourceOrderHighlightObjectForTest:str
    method_HideHighlight:str
    method_HighlightNode:str
    method_HighlightQuad:str
    method_HighlightRect:str
    method_HighlightSourceOrder:str
    method_SetInspectMode:str
    method_SetPausedInDebuggerMessage:str
    method_SetShowAdHighlights:str
    method_SetShowContainerQueryOverlays:str
    method_SetShowDebugBorders:str
    method_SetShowFlexOverlays:str
    method_SetShowFPSCounter:str
    method_SetShowGridOverlays:str
    method_SetShowHinge:str
    method_SetShowIsolatedElements:str
    method_SetShowLayoutShiftRegions:str
    method_SetShowPaintRects:str
    method_SetShowScrollBottleneckRects:str
    method_SetShowScrollSnapOverlays:str
    method_SetShowViewportSizeOnResize:str
    method_SetShowWebVitals:str
    method_HighlightFrame:str
    method_SetShowHitTestBorders:str

    event_InspectModeCanceled:str
    event_InspectNodeRequested:str
    event_NodeHighlightRequested:str
    event_ScreenshotRequested:str

    type_BoxStyle:str
    type_ColorFormat:str
    type_ContainerQueryContainerHighlightConfig:str
    type_ContainerQueryHighlightConfig:str
    type_ContrastAlgorithm:str
    type_FlexContainerHighlightConfig:str
    type_FlexItemHighlightConfig:str
    type_FlexNodeHighlightConfig:str
    type_GridHighlightConfig:str
    type_GridNodeHighlightConfig:str
    type_HighlightConfig:str
    type_HingeConfig:str
    type_InspectMode:str
    type_IsolatedElementHighlightConfig:str
    type_IsolationModeHighlightConfig:str
    type_LineStyle:str
    type_ScrollSnapContainerHighlightConfig:str
    type_ScrollSnapHighlightConfig:str
    type_SourceOrderConfig:str

    def __init__(self):
        super().__init__()

domain = Overlay()


# Напиши програм који за тачку у равни задату својим координатама испитује да ли припада задатом кругу и
# задатом правоугаонику чије су странице паралелне са координатним осама.
#
# Улаз: Са стандардног улаза учитавају се следећи реални бројеви (бројеви у истом реду су раздвојени једним
# размаком):
# • x, y - координате тачке,
# • x0, y0 - координате заједничког центра круга и правоугаоника,
# • r - полупречник круга,
# • w, h - дужина и ширина страница правоугаоника.
#
# Излаз: На стандардни излаз исписати два линије текста. У првој линији треба да пише jeste u krugu ако
# тачка (x, y) припада кругу са центром (x0, y0) полупречника r односно nije u krugu ако тачка не припада
# кругу. У другој линији треба да пише jeste u pravougaoniku ако тачка (x, y) припада правоугаонику чији
# је центар (тежиште) у тачки (x0, y0), чије су странице паралелне координатним осама и чија је дужина w тј.
# h, односно nije u pravougaoniku ако тачка не припада унутрашњости тог правоугаоника. Граница круга
# (кружница) и правоугаоника сматрају се њиховим делом.
#
# Пример
# Улаз
# 1 1
# 0 0
# 1
# 2 2
# Излаз
# nije u krugu
# jeste u pravougaoniku
import math

(x,y)  = input("Unesite koordinate ispitne tacke: ").split()
(x0,y0)= input("Unesite koordinate temene tacke kruga: ").split()
r      = int(input("Unesite poluprecnik kruga: "))
(w,h)  = input("Unesite duzinu i sirinu pravougaonika: ").split()

# proracun rastojanja od centra kruga trazene tacke (x-x0)^2 + (y-y0)^2 > r^2

f=pow(abs(int(x)-int(x0)),2)+pow(abs(int(y)-int(y0)),2)

if f >= pow(r,2):
    print("Tacka nije u krugu")
else:
    print("Tacka je u krugu")

if abs(int(x)) < abs(int(w)) and int(x)*int(w)>0 and abs(int(y))<abs(int(h)) and int(y)*int(h)>0:
    print("Tacka je u kvadratu")
else:
    print("Tacka je van kvadrata")


import atexit
import logging
import os
import sys

from datetime import datetime
from typing import Sequence
from pathlib import Path

import bakta
import bakta.constants as bc
import bakta.config as cfg
import bakta.db as db
import bakta.utils as bu
import bakta.expert.amrfinder as exp_amr
import bakta.expert.protein_sequences as exp_aa_seq
import bakta.features.annotation as anno
import bakta.features.orf as orf
import bakta.features.cds as feat_cds
import bakta.io.fasta as fasta
import bakta.io.json as json
import bakta.io.tsv as tsv
import bakta.ups as ups
import bakta.ips as ips
import bakta.psc as psc
import bakta.pscc as pscc

log = logging.getLogger('PROTEINS')

def main():
    # parse options and arguments
    parser = bu.init_parser(sub_command='_proteins')
    parser.add_argument('input', metavar='<input>', help='Protein sequences in (zipped) fasta format')

    arg_group_io = parser.add_argument_group('Input / Output')
    arg_group_io.add_argument('--db', '-d', action='store', default=None, help='Database path (default = <bakta_path>/db). Can also be provided as BAKTA_DB environment variable.')
    arg_group_io.add_argument('--output', '-o', action='store', default=os.getcwd(), help='Output directory (default = current working directory)')
    arg_group_io.add_argument('--prefix', '-p', action='store', default=None, help='Prefix for output files')
    arg_group_io.add_argument('--force', '-f', action='store_true', help='Force overwriting existing output folder')

    arg_group_annotation = parser.add_argument_group('Annotation')
    arg_group_annotation.add_argument('--proteins', action='store', default=None, dest='proteins', help='Fasta file of trusted protein sequences for annotation')

    arg_group_general = parser.add_argument_group('General')
    arg_group_general.add_argument('--help', '-h', action='help', help='Show this help message and exit')
    arg_group_general.add_argument('--verbose', '-v', action='store_true', help='Print verbose information')
    arg_group_general.add_argument('--debug', action='store_true', help='Run Bakta in debug mode. Temp data will not be removed.')
    arg_group_general.add_argument('--threads', '-t', action='store', type=int, default=0, help='Number of threads to use (default = number of available CPUs)')
    arg_group_general.add_argument('--tmp-dir', action='store', default=None, dest='tmp_dir', help='Location for temporary files (default = system dependent auto detection)')
    arg_group_general.add_argument('--version', '-V', action='version', version=f'%(prog)s {bakta.__version__}')
    args = parser.parse_args()

    ############################################################################
    # Setup logging
    ############################################################################
    cfg.prefix = args.prefix if args.prefix else Path(args.input).stem
    output_path = cfg.check_output_path(args.output, args.force)
    cfg.force = args.force
    log.info('force=%s', args.force)

    bu.setup_logger(output_path, cfg.prefix, args)
    log.info('prefix=%s', cfg.prefix)
    log.info('output=%s', output_path)

    ############################################################################
    # Checks and configurations
    # - check parameters and setup global configuration
    # - test database
    # - test binary dependencies
    ############################################################################
    try:
        if(args.input == ''):
            raise ValueError('File path argument must be non-empty')
        aa_path = Path(args.input).resolve()
        cfg.check_readability('proteins', aa_path)
        cfg.check_content_size('proteins', aa_path)
    except:
        log.error('provided input proteins file not valid! path=%s', args.input)
        sys.exit(f'ERROR: input proteins file ({args.input}) not valid!')
    log.info('input-path=%s', aa_path)

    cfg.check_db_path(args)
    cfg.db_info = db.check(cfg.db_path)
    cfg.check_tmp_path(args)
    cfg.check_user_proteins(args)
    cfg.check_threads(args)
    cfg.skip_cds = False  # circumvent main config setup
    cfg.debug = args.debug
    log.info('debug=%s', cfg.debug)
    cfg.verbose = True if cfg.debug else args.verbose
    log.info('verbose=%s', cfg.verbose)

    bu.test_dependencies()
    if(cfg.verbose):
        print(f'Bakta v{bakta.__version__}')
        print('Options and arguments:')
        print(f'\tinput: {aa_path}')
        print(f"\tdb: {cfg.db_path}, version {cfg.db_info['major']}.{cfg.db_info['minor']}")
        print(f'\toutput: {cfg.output_path}')
        if(cfg.force): print(f'\tforce: {cfg.force}')
        print(f'\ttmp directory: {cfg.tmp_path}')
        print(f'\tprefix: {cfg.prefix}')
        print(f'\t# threads: {cfg.threads}')

    if(cfg.debug):
        print(f"\nBakta runs in DEBUG mode! Temporary data will not be destroyed at: {cfg.tmp_path}")
    else:
        atexit.register(bu.cleanup, log, cfg.tmp_path)  # register cleanup exit hook

    ############################################################################
    # Import proteins
    ############################################################################
    try:
        aas = fasta.import_contigs(aa_path, False, False)
        log.info('imported sequences=%i', len(aas))
        print(f'\timported: {len(aas)}')
    except:
        log.error('wrong file format or unallowed characters in amino acid sequences!', exc_info=True)
        sys.exit('ERROR: wrong file format or unallowed characters in amino acid sequences!')
    mock_start = 1
    for aa in aas:  # rename and mock feature attributes to reuse existing functions
        aa['type'] = bc.FEATURE_CDS
        aa['aa'] = aa['sequence']
        aa['locus'] = aa['id']
        aa['contig'] = 'mock'
        aa['start'] = mock_start
        aa['stop'] = -1
        aa['strand'] = bc.STRAND_UNKNOWN
        aa['frame'] = 1
        mock_start += 100
    print('annotate protein sequences...')
    annotate_aa(aas)

    for aa in aas:  # cleanup mock attributes
        aa.pop('contig', None)
        aa.pop('start', None)
        aa.pop('stop', None)
        aa.pop('strand', None)
        aa.pop('frame', None)

    cfg.run_end = datetime.now()
    run_duration = (cfg.run_end - cfg.run_start).total_seconds()

    ############################################################################
    # Write output files
    # - write comprehensive annotation results as JSON
    # - write optional output files in TSV, FAA formats
    # - remove temp directory
    ############################################################################

    print('write results...')
    annotations_path = output_path.joinpath(f'{cfg.prefix}.tsv')
    header_columns = ['ID', 'Length', 'Gene', 'Product', 'EC', 'GO', 'COG', 'RefSeq', 'UniParc', 'UniRef']
    print(f'\tfull annotations (TSV): {annotations_path}')
    tsv.write_features(aas, header_columns, map_aa_columns, annotations_path)
    full_annotations_path = output_path.joinpath(f'{cfg.prefix}.json')
    print(f'\tfull annotations (JSON): {full_annotations_path}')
    json.write_json(None, aas, full_annotations_path)
    hypotheticals_path = output_path.joinpath(f'{cfg.prefix}.hypotheticals.tsv')
    header_columns = ['ID', 'Length', 'Mol Weight [kDa]', 'Iso El. Point', 'Pfam hits']
    hypotheticals = hypotheticals = [aa for aa in aas if 'hypothetical' in aa]
    print(f'\tinformation on hypotheticals (TSV): {hypotheticals_path}')
    tsv.write_features(hypotheticals, header_columns, map_hypothetical_columns, hypotheticals_path)
    aa_output_path = output_path.joinpath(f'{cfg.prefix}.faa')
    print(f'\tannotated sequences (Fasta): {aa_output_path}')
    fasta.write_faa(aas, aa_output_path)

    print(f'\nIf you use these results please cite Bakta: https://doi.org/{bc.BAKTA_DOI}')
    print(f'Annotation successfully finished in {int(run_duration / 60):01}:{int(run_duration % 60):02} [mm:ss].')

def map_aa_columns(feat: dict) -> Sequence[str]:
    gene = feat.get('gene', None)
    if(gene is None):
        gene = ''
    return [
        feat['id'],
        str(feat['length']),
        gene,
        feat['product'],
        ','.join([k.replace('EC:', '') for k in feat['db_xrefs'] if 'EC:' in k]),
        ','.join([k for k in feat['db_xrefs'] if 'GO:' in k]),
        ','.join([k.replace('COG:', '') for k in feat['db_xrefs'] if 'COG:' in k]),
        ','.join([k.replace('RefSeq:', '') for k in feat['db_xrefs'] if 'RefSeq:' in k]),
        ','.join([k.replace('UniParc:', '') for k in feat['db_xrefs'] if 'UniParc:' in k]),
        ','.join([k.replace('UniRef:', '') for k in feat['db_xrefs'] if 'UniRef' in k])
    ]

def map_hypothetical_columns(feat: dict) -> Sequence[str]:
    return [
        feat['id'],
        str(feat['length']),
        f"{(feat['seq_stats']['molecular_weight']/1000):.1f}" if feat['seq_stats']['molecular_weight'] else 'NA'
        f"{feat['seq_stats']['isoelectric_point']:.1f}" if feat['seq_stats']['isoelectric_point'] else 'NA'
        ','.join([k.replace('PFAM:', '') for k in feat['db_xrefs'] if 'PFAM:' in k])
    ]

def annotate_aa(aas: Sequence[dict]):
    for aa in aas:
        aa['aa_digest'], aa['aa_hexdigest'] = bu.calc_aa_hash(aa['sequence'])
    log.debug('lookup AA UPS/IPS')
    aas_ups, aas_not_found = ups.lookup(aas)
    aas_ips, tmp = ips.lookup(aas_ups)
    aas_not_found.extend(tmp)
    print(f'\tdetected IPSs: {len(aas_ips)}')
    if(len(aas_not_found) > 0):
        log.debug('search CDS PSC')
        aas_psc, aas_pscc, aas_not_found = psc.search(aas_not_found)
        print(f'\tfound PSCs: {len(aas_psc)}')
        print(f'\tfound PSCCs: {len(aas_pscc)}')
    print('\tlookup annotations...')
    log.debug('lookup CDS PSCs')
    psc.lookup(aas)  # lookup PSC info
    pscc.lookup(aas)  # lookup PSCC inf
    print('\tconduct expert systems...')  # conduct expert systems annotation
    aa_path = cfg.tmp_path.joinpath('aa.faa')
    orf.write_internal_faa(aas, aa_path)
    log.debug('conduct expert system: amrfinder')
    cfg.translation_table = 11
    expert_amr_found = exp_amr.search(aas, aa_path)
    print(f'\t\tamrfinder: {len(expert_amr_found)}')
    log.debug('conduct expert system: aa seqs')
    diamond_db_path = cfg.db_path.joinpath('expert-protein-sequences.dmnd')
    expert_aa_found = exp_aa_seq.search(aas, aa_path, 'expert_proteins', diamond_db_path)
    print(f'\t\tprotein sequences: {len(expert_aa_found)}')
    if(cfg.user_proteins):
        log.debug('conduct expert system: user aa seqs')
        user_aa_path = cfg.tmp_path.joinpath('user-proteins.faa')
        exp_aa_seq.write_user_protein_sequences(user_aa_path)
        user_aa_found = exp_aa_seq.search(aas, aa_path, 'user_proteins', user_aa_path)
        print(f'\t\tuser protein sequences: {len(user_aa_found)}')
    print('\tcombine annotations and mark hypotheticals...')
    log.debug('combine CDS annotations')
    for aa in aas:
        anno.combine_annotation(aa)  # combine IPS & PSC annotations and mark hypothetical
    log.debug('analyze hypotheticals')
    hypotheticals = [aa for aa in aas if 'hypothetical' in aa]
    if(len(hypotheticals) > 0):
        print(f'\tanalyze hypothetical proteins: {len(hypotheticals)}')
        pfam_hits = feat_cds.predict_pfam(hypotheticals)
        print(f"\tdetected Pfam hits: {len(pfam_hits)}")
        feat_cds.analyze_proteins(hypotheticals)
        print('\tcalculated proteins statistics')

if __name__ == '__main__':
    main()


import torch
from torch import nn

class Encoder(nn.Module):
    def __init__(self, ipt_dim, opt_dim,look_back_window, pre_rnn_dim = 128, hid_dim=128, encoder_rnn_layers=1,dropout=0.0):
        super(Encoder, self).__init__()
        self.ipt_dim = ipt_dim
        self.hid_dim = hid_dim
        self.look_back_window = look_back_window
        self.pre_rnn_dim = pre_rnn_dim
        self.opt_dim = opt_dim
        self.encoder_rnn_layers = encoder_rnn_layers
        self.dropout = dropout

        self.pre_rnn = nn.Sequential(
            nn.Linear(self.ipt_dim, self.pre_rnn_dim)
        )
        self.bn = nn.BatchNorm2d(self.look_back_window)
        self.relu = nn.LeakyReLU()

        self.rnn = nn.GRU(self.pre_rnn_dim, self.hid_dim, self.encoder_rnn_layers,dropout=self.dropout, batch_first = True)

        self.post_rnn = nn.Sequential(
            nn.Linear(self.hid_dim, self.opt_dim))

    def forward(self, x):
        x = self.pre_rnn(x).unsqueeze(3)
        x = self.relu(self.bn(x).squeeze(3))
        output, hn= self.rnn(x)
        out = self.post_rnn(output)
        return {
            'past_ret': out,
            'gru_hidden': hn,
            "gru_output": output
        }

class Decoder(nn.Module):
    def __init__(self, ipt_dim, opt_dim, hid_dim=128, decoder_rnn_layers=1, dropout=0.5):
        super(Decoder, self).__init__()
        self.ipt_dim = ipt_dim
        self.hid_dim = hid_dim
        self.opt_dim = opt_dim
        self.decoder_rnn_layers = decoder_rnn_layers
        self.dropout = dropout

        self.rnn = nn.GRU(self.hid_dim, self.hid_dim, self.decoder_rnn_layers, dropout=self.dropout, batch_first = True)

        self.post_rnn = nn.Sequential(
            nn.Linear(self.hid_dim, int(self.hid_dim/2)),
            nn.LeakyReLU(),
            nn.Linear(int(self.hid_dim/2), self.opt_dim)
        )

    def forward(self, x, hidden):
        x, hn= self.rnn(x, hidden)
        out = self.post_rnn(x)
        return {
            'future_price': out,
            'decoder_gru_hidden': hn,
            'decoder_gru_output': x
        }

class Classifier(nn.Module):
    def __init__(self, ipt_dim, opt_dim=3, hid_dim=32):
        super(Classifier, self).__init__()
        self.ipt_dim = ipt_dim
        self.hid_dim = hid_dim
        self.opt_dim = opt_dim
        self.fc1 = nn.Linear(self.ipt_dim, self.hid_dim)
        self.relu1 = nn.LeakyReLU()
        self.bn1 = nn.BatchNorm1d(self.hid_dim)

        self.fc2 = nn.Linear(self.hid_dim, int(self.hid_dim/2))
        self.relu2 = nn.LeakyReLU()
        self.bn2 = nn.BatchNorm1d(int(self.hid_dim/2))

        self.fc3 = nn.Linear(int(self.hid_dim/2), self.opt_dim)

    def forward(self, x):
        x = self.relu1(self.bn1(self.fc1((x))))
        x = self.relu2(self.bn2(self.fc2((x))))
        output = self.fc3(x)
        return {
            'output': output
        }

class StockNet(nn.Module):
    def __init__(self, encoder, decoder, classifier, future_window, is_gpu=True):
        super(StockNet, self).__init__()
        self.encoder = encoder
        self.decoder = decoder
        self.classifier = classifier
        self.future_window = future_window
        self.is_gpu = is_gpu
        # if(pre_encoder_path != ''):
        #     self.encoder.load_state_dict(torch.load(pre_encoder_path, map_location=torch.device(device)))
        #     print("encoder model loaded")

    def forward(self, data):
        future_seq_len = self.future_window
        batch_size = data.shape[0]

        #outputs: future price
        outputs = torch.zeros(batch_size, future_seq_len)
        if self.is_gpu:
            outputs = outputs.cuda()

        encoder_pred = self.encoder(data) #process encoder
        pred_past_price = encoder_pred['past_ret'].squeeze(2) #[batch_size, past_future_len]
        past_hidden = encoder_pred['gru_hidden'] # [num_layers, batch_size, hidden_dim]
        past_output_sequence = encoder_pred['gru_output'] #[batch_size, past_future_len, hidden_dim]

        output = past_output_sequence[:, -1, :]
        output = output.unsqueeze(1)

        classifier_input = past_output_sequence[:, -1, :]

        for t in range(0, future_seq_len):
            if t == 0:
                prediction = self.decoder(output, past_hidden)
            else:
                prediction = self.decoder(output, hidden)
            outputs[:, t] = prediction['future_price'].squeeze(1).squeeze(1)
            hidden = prediction['decoder_gru_hidden']
            output = prediction['decoder_gru_output']

        classifier_output = self.classifier(classifier_input)['output']
        return {
            'past_ret': pred_past_price,
            'future_ret': outputs.float(),
            'pred_cl': classifier_output
        }


import random

def InsertNumbers(listanum):
    for prob in range(1,127):
        Conjn = []
        while True:
            numbers = random.randint(1,9)
            if numbers not in Conjn:
                Conjn.append(numbers)
                if(len(Conjn) == 5):
                    if Conjn not in listanum:
                        listanum.append(Conjn)
                        break
                    else:
                        Conjn = []
    return list(listanum)

def GeradorEmTxt(NumbersResul):
    LotoMenorResul = open("LotoMinResult.txt", 'w')
    for n in range(126):
        LotoMenorResul.write("\n %s %s" % (n+1, NumbersResul[n]))

NumbersProv = []
InsertNumbers(NumbersProv)
GeradorEmTxt(NumbersProv)
print(NumbersProv[125])

#TO DO: Primeiro, fazer uma lista aninhada recebendo o conjuto de jogos possíveis
    #TO DO: É bom dividir os dados entre menores, medianos e maiores
#TO DO: Segundo, realizar uma comparação entre esse conjunto de jogos para não haver escolhas iguais
#TO DO: (Melhoria)Terceiro, realizar a separação de  menos, medianos e maiores
#TO DO:

#  03 - 06 - 07 - 08 - 09
#  10 - 13 - 14 - 15 - 16
#  18 - 19 - 20 - 21 - 25

#Vamos dividir o jogo da lotofácil na seguinte estratégia- números menores, medianos e maiores
#Menores 1 ao 9
#medianos 10 ao 16
#Maiores 16 a0 25


import streamlit as st
import pandas as pd
import pickle
import time
from app.layout.header import render_header
from app.layout.sidebar import render_sidebar
from app.layout.body import render_body
from app.nlp import sentiment, mlc, ner

def run_app():

    st.set_page_config(layout="wide")

    t = time.time()
    render_header()

    # load_btn, run_btn, save_ckb, config = render_sidebar()
    load_btn, run_btn, config = render_sidebar()

    progress_bar = st.progress(0)
    status_text = st.empty()

    if run_btn:
        progress_bar.progress(20)
        status_text.text("Data loaded")
        df = config["df"]
        col_text = config["col_text"]

        progress_bar.progress(40)
        status_text.text("Sentiment Analysis in progress...")
        df_new = sentiment.run_sentiment_analysis(df, col_text)
        status_text.text("Done perfoming Sentiment Analysis")

        progress_bar.progress(60)
        status_text.text("Multi-label classification in progress...")
        df_new = mlc.run_multi_label_classification(df_new, col_text)
        status_text.text("Done performing Mulit-Label Classification")

        progress_bar.progress(80)
        status_text.text("Entity Recognition in progress...")
        df_preds, df_ents, labels2ents = ner.run_named_entity_recognition(
            df_new, col_text
        )
        status_text.text("Done performing Named Entity Recognition")

        # if save_ckb:
        # df_preds.to_csv("./app/data/df_preds.csv", index=False)
        # df_ents.to_csv("./app/data/df_ents.csv", index=False)
        # with open("./app/data/labels2ents.pickle", "wb") as file:
        #     pickle.dump(labels2ents, file, protocol=4)

        render_body(df_preds, df_ents, labels2ents)
        progress_bar.progress(100)

        elapsed_time = round(time.time() - t, 2)
        time_unit = "seconds"
        if elapsed_time > 60:
            elapsed_time = round(elapsed_time / 60, 2)
            time_unit = "minutes"

        status_text.success(
            f"Done with all tasks! (Elapsed time: {elapsed_time} {time_unit})"
        )

    elif load_btn:
        df_preds = pd.read_csv("./app/data/df_preds.csv")
        df_ents = pd.read_csv("./app/data/df_ents.csv")
        labels2ents = dict()
        with open("./app/data/labels2ents.pickle", "rb") as file:
            labels2ents = pickle.load(file)

        render_body(df_preds, df_ents, labels2ents)
        progress_bar.progress(100)
        status_text.success(f"Loaded previous results: Rows ({len(df_preds)})")


# this is written in python 3.5
# the purpose of this script is to get the result of the gemini or sql
# and then re-import it back to the database
# this is not be used by itself but is a part of the job scheduler.

# geminR will do the checking if the table already exists otherwise
# will continue with the process

import datetime as dat
import pandas as pd
import optparse as opt
from sqlalchemy import create_engine

# get the options here,
# one thing to note here is that we are using the same chunksize to read and
# write to sql so the chunksize should be 1/2 of the max value of the system

parser = opt.OptionParser()

parser.add_option("-f", dest="filename", action="store", type="string")
parser.add_option("-d", dest="database", action="store", type="string")
parser.add_option("-c", dest="chunksize", action="store", type="int")
parser.add_option("-t", dest="tablename", action="store", type="string")
(options, args) = parser.parse_args()

print(dat.datetime.now(), "initializing importer")

print(options.tablename, options.database, options.chunksize, options.filename)

db = "sqlite:///"+options.database

# connect to db otherwise throw a tantrum
try:
    engine = create_engine(db)
    print(dat.datetime.now(), "connected to database")
except ConnectionError:
    print(dat.datetime.now(), "Error connecting to database", options.database)

# need to read and import in chunks
try:
    for chunk in pd.read_csv(options.filename, sep="\t", chunksize=options.chunksize):
        chunk.to_sql(options.tablename, engine, chunksize=options.chunksize)
    print(dat.datetime.now(), "finished writing to", options.tablename)
except Exception:
    print(dat.datetime.now(), "file error") #I can do better than this I might need to call logger in
                                            # other iterations there needs to some error printing when
                                            # it actually fails.

print("Closing importer for", options.database, options.tablename)


#
# simple routine using gmplot to create an html to overplot on google map
#   mkGMap()
# <- Last updated: Sat May  1 16:51:29 2021 -> SGK
#
import os
import numpy as np
import gmplot
from utilslib import formatTime
#
# ------------------------------------------------------------------------
# create an html to overplot on google map, using gmplot
def mkGMap(data, infos, stats,
           color = 'red', velMin = 6.0):
    """
    create an hmlt file to overplot route on a Google Map
      using gmplot module
    """
    #
    # decode infos -> index[] and units[]
    nCols, nLines = data.shape
    index = {}
    units = {}
    i = 0
    for wx in infos.split():
        w = wx.split(':')
        index[w[0]] = i
        units[w[0]] = w[1]
        i += 1
    #
    # lon index -> values
    ix = index['Longitude']
    mLon = np.isfinite(data[ix, :])
    lonList = data[ix, mLon]
    #
    # lat index -> values
    ix = index['Latitude']
    mLat = np.isfinite(data[ix, :])
    latList = data[ix, mLat]
    #
    # get center and borders
    latCntr = sum(latList)/sum(mLat)
    lonCntr = sum(lonList)/sum(mLon)
    #
    (north, south) = (max(latList),  min(latList))
    (east,  west)  = (max(lonList),  min(lonList))
    #
    # widens and shift east by 20%
    dlon = (east-west)*.2
    east -= dlon*2
    # west -= dlon-dlon
    #
    # map bounding box
    bb = {'north': north, 'south': south,
          'east':  east,  'west':  west}
    mapStyle = [ {'featureType': 'all', 'stylers': [
        {'saturation': -80},
        {'lightness': 30}, ] } ]
    #
    zoom = 12
    gmap = gmplot.GoogleMapPlotter(latCntr, lonCntr, zoom,
                                   map_style = mapStyle,
                                   fit_bounds = bb)
    #
    # API KEY from $APIKEY
    apiKey = os.environ.get('APIKEY','none')
    if (apiKey != 'none'):
        gmap.apikey = apiKey
    else:
        print('no APIKEY found, will show a "For development purpose only" watermark')
    #
    # put markers at beg/end
    gmap.scatter( latList[0:1], lonList[0:1], '#00FF00',
                  size = 10, marker = True )
    gmap.scatter( latList[-2:-1], lonList[-2:-1], '#FF0000',
                  size = 10, marker = True )
    # draw the route
    gmap.plot(latList, lonList, 'cornflowerblue', edge_width = 2.5)
    #
    # add some text
    fmtStr = 'Started {}\n' + \
        'Time total:{}, moving:{}, paused:{}\n' + \
        'Distance traveled total:{:.1f}, moving:{:.1f} mi\n' + \
        'Minimun moving velocity {:.1f} mph'
    str = fmtStr.format(stats['startTime'],
                        formatTime(stats['totalTime']),
                        formatTime(stats['movingTime']),
                        formatTime(stats['totalTime']- stats['movingTime']),
                        stats['distance'],  stats['mvgDistance'], velMin)
    #
    fmtStr = '\nVelocity average:{:6.2f} max:{:6.2f} mph\n' + \
        'Cadence average:{:6.2f} max:{:6.2f} rpm\n' + \
        'HR average:{:6.2f} max:{:6.2f} bpm'
    str += fmtStr.format(stats['avgMVel'],      stats['maxMVel'],
                         stats['avgCadence'],   stats['maxCadence'],
                         stats['avgHeartRate'], stats['maxHeartRate'])
    #
    # location of text
    lat = max(latList)
    lon = max(lonList)+0.075
    #
    # must write one string at a time, \n not allowed
    for s in str.split('\n'):
        #
        # the text is center justify, this is a hack to approx left justify
        lx = len(s)*.0019
        gmap.text(lat, lon, s, color = color)
        # move down
        lat -= .009
    #
    # Pass the file path of the html
    gmap.draw( "gmap.html" )
    #
    print('Load \'gmap.html\' in a browser, ' + \
          'map is centered on {:.4f},{:.4f}'.format(latCntr, lonCntr))