import pyaudio
import sqlite3
import wave
import threading
import time

con = sqlite3.connect("record.db")
cur = con.cursor()
cur.executescript(open("setup.sql", "r").read())

recBefore = 5
recAfter = 5
recMax = 600
rate = 44100
audio = pyaudio.PyAudio()
frames = [None]*int(rate / 1024 * recMax)
i = 0
recStop = False

def rec_thread_func():
    global i
    global recStop
    global frames
    global audio
    stream = audio.open(format=pyaudio.paInt16, channels=1, rate=rate, input=True, frames_per_buffer=1024)
    while not recStop:
        while i in range(0, int(rate / 1024 * recMax)):
            frames[i] = stream.read(1024)
            i+=1

    stream.close()

# Setup and start recording thread
rec_thread = threading.Thread(target=rec_thread_func)
rec_thread.start()

while True:
    input("Start")
    startFrame = i
    startTime = int(time.time())
    input("Stop")
    time.sleep(recAfter)
    #recStop = True
    endFrame = i
    endTime = int(time.time())

    outputFile = "out.wav"

    file = wave.open(outputFile, "wb")
    file.setnchannels(1)
    file.setsampwidth(audio.get_sample_size(pyaudio.paInt16))
    file.setframerate(rate)
    if(startFrame == endFrame):
        print("Threading put")
    elif(startFrame < endFrame):
        startFrame = int(startFrame-(rate/1024*recBefore))
        cur.execute("INSERT INTO audio(startT, endT, len, freq, audio) VALUES (?,?,?,?,?);", (startTime, endTime, startTime-endTime, rate, b"".join(frames[startFrame:endFrame])))
        con.commit()
        file.writeframes(b"".join(frames[startFrame:endFrame]))
    elif(startFrame > endFrame):
        file.writeframes(b"".join(frames[startFrame-recBefore:int(rate / 1024 * recMax)]+frames[0:endFrame]))
    else:
        print("dafuq")

    file.close()


import numpy as np

def comp_angle(x,y,z):
    ang=(np.arctan(x/y))*180/3.14

    if(y>0):
        k=90-ang-90
        if(k<0):
            k=360+k
        return k
    elif(y<0):
        k=270-ang-90
        if(k<0):
            k=360+k
        return k
    elif(y==0 and x<0):
        k=90.0
        return k
    else:
        k=270.0
        return k


from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine

menu = Menu()
machine = CoffeeMaker()
money = MoneyMachine()
coin = money.COIN_VALUES
latte = MenuItem(name="latte", cost=2.5, water=200, milk=150, coffee=24)
espresso = MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5)
cappuccino = MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3)

def get_coffee():
    machine.report()

    money.report()

    order = input(f"Hi! What can I get for you today? {menu.get_items()}: ").lower()

    menu.find_drink(order)
    if order == "latte":
        order = latte
    elif order == "espresso":
        order = espresso
    elif order == "cappuccino":
        order = cappuccino

    machine.is_resource_sufficient(order)

    enough = money.make_payment(order.cost)

    if enough:
        machine.make_coffee(order)

    money.report()
    addtl = input("Do you want to order another drink? Yes or No: ").lower()

    if addtl == 'yes':
        get_coffee()

get_coffee()


import matplotlib.pyplot as plt

class MatrixPlotter(object):
    def __init__(self, name, min_row=0, min_col=0, max_row=None, max_col=None):
        self.name = name
        self.t = []

        # min/max values
        self.min_row = min_row
        self.min_col = min_col
        self.max_row = max_row
        self.max_col = max_col

        self._init_matrix()

    def __iter__(self):
        """Make object iterable."""
        for attr, value in self.__dict__.items():
            yield attr, value

    def _init_matrix(self):
        for i in range(self.min_row, self.max_row):
            for j in range(self.min_col, self.max_col):
                self.__dict__[f"a_{i}_{j}"] = []

    def append(self, t, mat):
        self.t.append(t)

        for i in range(self.min_row, self.max_row):
            for j in range(self.min_col, self.max_col):
                self.__dict__[f"a_{i}_{j}"].append(mat[i][j])

    def plot(self, axes=None, min_t=None, max_t=None, index_from_zero=False):
        """Creates a plot of them matrix entries.

        Param:
        * index_from_zero - whether to label matrix entries starting from
                0 or starting from 1
        """

        plot_rows = self.max_row - self.min_row
        plot_cols = self.max_col - self.min_col

        if axes is None:
            fig, axes = plt.subplots(plot_rows, plot_cols)
            fig.tight_layout()
            st = fig.suptitle(self.name, fontsize="x-large")

            # shift subplots down:
            st.set_y(0.95)
            fig.subplots_adjust(top=0.85)

        for row in range(self.min_row, self.max_row):
            plt_row = row - self.min_row

            for col in range(self.min_col, self.max_col):
                plt_col = col - self.min_col

                label = f"a_{row}_{col}"
                latex_label = (
                    f"$a_{{{row}\_{col}}}$"
                    if index_from_zero
                    else f"$a_{{{row+1}\_{col+1}}}$"
                )

                val = self.__dict__[label]
                min_val, max_val = min(val), max(val)
                range_val = max_val - min_val

                # display of very small values
                if range_val < 0.0001:
                    min_val = min_val - 0.002
                    max_val = max_val + 0.002
                else:
                    min_val = min_val - 0.2 * range_val
                    max_val = max_val + 0.2 * range_val

                if plot_rows > 1:
                    ax_obj = axes[plt_row][plt_col]
                else:
                    ax_obj = axes[plt_col]

                ax_obj.plot(self.t, self.__dict__[label])

                ax_obj.set_title(latex_label)
                ax_obj.set_xlim(left=min_t, right=max_t)
                ax_obj.set_ylim(bottom=min_val, top=max_val)
                ax_obj.grid(True)

        return axes


from typing import Mapping, MutableMapping, MutableSequence, Sequence

from .classes import classCastFuncs, classSchema

def setItem(subject, key, item, *, itemCast=None):
    if itemCast is not None:
        item = itemCast(item)
    if isinstance(subject, (MutableMapping, MutableSequence)):
        subject[key] = item
    else:
        setattr(subject, key, item)

def delAttr(subject, key, *, itemCast=None):
    if isinstance(subject, Sequence):
        raise TypeError("can't call delattr on list")
    elif isinstance(subject, MutableMapping):
        del subject[key]
    else:
        delattr(subject, key)

def delItems(subject, index, deleteCount=1, itemCast=None):
    spliceItems(subject, index, deleteCount)

def insertItems(subject, index, *items, itemCast=None):
    spliceItems(subject, index, 0, *items, itemCast=itemCast)

def spliceItems(subject, index, deleteCount, *items, itemCast=None):
    if itemCast is not None:
        items = [itemCast(item) for item in items]
    subject[index : index + deleteCount] = items

baseChangeFunctions = {
    "=": setItem,
    "d": delAttr,
    "-": delItems,
    "+": insertItems,
    ":": spliceItems,
}

# TODO: Refactor. These don't really belong here,
# and should ideally be registered from outside
changeFunctions = {
    **baseChangeFunctions,
    "=xy": lambda path, pointIndex, x, y: path.setPointPosition(pointIndex, x, y),
    "insertContour": lambda path, contourIndex, contour: path.insertContour(
        contourIndex, contour
    ),
    "deleteContour": lambda path, contourIndex: path.deleteContour(contourIndex),
    "deletePoint": lambda path, contourIndex, contourPointIndex: path.deletePoint(
        contourIndex, contourPointIndex
    ),
    "insertPoint": lambda path, contourIndex, contourPointIndex, point: path.insertPoint(
        contourIndex, contourPointIndex, point
    ),
}

#
# A "change" object is a simple JS object containing several
# keys.
#
# "p": an array of path items, eg. ["glyphs", "Aring"]
# Optional: can be omitted if empty.
#
# "f": function name, to be looked up in the changeFunctions dict
# Optional: can be omitted if the change has children
#
# "a": "arguments", an array of arguments for the change function
# Optional: if omitted, defaults to an empty array
#
# "c": Array of child changes. Optional.
#

def applyChange(subject, change):
    """Apply `change` to `subject`."""
    _applyChange(subject, change)

def _applyChange(subject, change, *, itemCast=None):
    path = change.get("p", [])
    functionName = change.get("f")
    children = change.get("c", [])

    for pathElement in path:
        itemCast = None
        if isinstance(subject, (Mapping, Sequence)):
            subject = subject[pathElement]
        else:
            itemCast = getItemCast(subject, pathElement, "subtype")
            subject = getattr(subject, pathElement)

    if functionName is not None:
        changeFunc = changeFunctions[functionName]
        args = change.get("a", [])
        if functionName in baseChangeFunctions:
            if itemCast is None and args:
                itemCast = getItemCast(subject, args[0], "type")
            changeFunc(subject, *args, itemCast=itemCast)
        else:
            changeFunc(subject, *args)

    for subChange in children:
        _applyChange(subject, subChange, itemCast=itemCast)

def getItemCast(subject, attrName, fieldKey):
    classFields = classSchema.get(type(subject))
    if classFields is not None:
        fieldDef = classFields[attrName]
        subtype = fieldDef.get(fieldKey)
        if subtype is not None:
            return classCastFuncs.get(subtype)
    return None

_MISSING = object()

def matchChangePattern(change, matchPattern):
    """Return `True` or `False`, depending on whether the `change` matches
    the `matchPattern`.

    A `matchPattern` is tree in the form of a dict, where keys are change path
    elements, and values are either nested pattern dicts or `None`, to indicate
    a leaf node.
    """
    node = matchPattern
    for pathElement in change.get("p", []):
        childNode = node.get(pathElement, _MISSING)
        if childNode is _MISSING:
            return False
        if childNode is None:
            # leaf node
            return True
        node = childNode

    for childChange in change.get("c", []):
        if matchChangePattern(childChange, node):
            return True

    return False

def filterChangePattern(change, matchPattern, inverse=False):
    """Return a subset of the `change` according to the `matchPattern`, or `None`
    if the `change` doesn't match `matchPattern` at all. If there is a match,
    all parts of the change that do not match are not included in the returned
    change object.

    A `matchPattern` is tree in the form of a dict, where keys are change path
    elements, and values are either nested pattern dicts or `None`, to indicate
    a leaf node.

    If `inverse` is True, `matchPattern` is used to exclude the change items
    that match from the return value.
    """
    node = matchPattern
    for pathElement in change.get("p", []):
        childNode = node.get(pathElement, _MISSING)
        if childNode is _MISSING:
            return change if inverse else None
        if childNode is None:
            # leaf node
            return None if inverse else change
        node = childNode

    filteredChildren = []
    for childChange in change.get("c", []):
        childChange = filterChangePattern(childChange, node, inverse)
        if childChange is not None:
            filteredChildren.append(childChange)

    result = {**change, "c": filteredChildren}
    if not inverse:
        # We've at most matched one or more children, but not the root change
        result.pop("f", None)
        result.pop("a", None)

    return _normalizeChange(result)

def _normalizeChange(change):
    children = change.get("c", ())

    if "f" not in change and len(children) == 1:
        # Turn only child into root change
        result = {**children[0]}
        # Prefix child path with original root path
        result["p"] = change.get("p", []) + result.get("p", [])
    else:
        result = {**change}

    if not result.get("p"):
        # Remove empty path
        result.pop("p", None)

    if not result.get("c"):
        # Remove empty children list
        result.pop("c", None)

    if len(result) == 1 and "p" in result:
        # Nothing left but a path: no-op change
        result.pop("p", None)

    if not result:
        result = None

    return result

def patternFromPath(matchPath):
    """Given a list of path elements, return a pattern dict."""
    pattern = {}
    if matchPath:
        pattern[matchPath[0]] = (
            None if len(matchPath) == 1 else patternFromPath(matchPath[1:])
        )
    return pattern

def patternUnion(patternA, patternB):
    """Return a pattern which is the union of `patternA` and `patternB`:
    the result will match everything from `patternA` and `patternB`.
    """
    result = {**patternA}
    for key, valueB in patternB.items():
        valueA = patternA.get(key, _MISSING)
        if valueA is _MISSING or valueB is None:
            result[key] = valueB
        elif valueA is not None:
            result[key] = patternUnion(valueA, valueB)
        else:
            # valueA is None -- patternA already matches a prefix of
            # patternB: nothing to do
            pass
    return result

def patternDifference(patternA, patternB):
    """Return a pattern which is `patternA` minus `patternB`: the result will
    only match the items from `patternA` that are not included in `patternB`.
    """
    result = {**patternA}
    for key, valueB in patternB.items():
        valueA = patternA.get(key, _MISSING)
        if valueA is _MISSING:
            pass
        elif valueB is None:
            del result[key]
        elif valueA is None:
            pass
        else:
            result[key] = patternDifference(valueA, valueB)
            if not result[key]:
                del result[key]
    return result

def patternIntersect(patternA, patternB):
    """Return the intersection of `patternA` and `patternB`. The resulting pattern
    will only match items that are included in both patterns.
    """
    result = {}
    for key, valueA in patternA.items():
        valueB = patternB.get(key, _MISSING)
        if valueB is _MISSING:
            continue
        if valueA is None:
            result[key] = valueB
        elif valueB is None:
            result[key] = valueA
        else:
            childResult = patternIntersect(valueA, valueB)
            if childResult:
                result[key] = childResult
    return result

def collectChangePaths(change, depth):
    """Return a sorted list of paths of the specified `depth` that the `change`
    includes."""
    return sorted(set(_iterateChangePaths(change, depth)))

def _iterateChangePaths(change, depth, prefix=()):
    path = prefix + tuple(change.get("p", ()))
    if len(path) >= depth:
        yield path[:depth]
        return
    for childChange in change.get("c", []):
        yield from _iterateChangePaths(childChange, depth, path)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 17 17:08:37 2023

@author: edwardbickerton
"""
import pandas as pd

def read_crypto(symbol, name):
    return pd.read_csv(
        "archive/Price-Data/" +
        "_".join([symbol, name]) + ".csv",
        usecols=["Date", "Open"]
    ).rename(columns={"Open": symbol})

index_df = pd.read_csv(
    "archive/Index/Index.csv",
    index_col=0
)
crypto_dfs = []
crypto_symbols = []
for idx, row in index_df.iterrows():
    crypto_symbols.append(row["Symbol"])
    crypto_dfs.append(read_crypto(row["Symbol"], row["Name"]))

crypto_price_data = crypto_dfs[0]
for df in crypto_dfs[1:]:
    crypto_price_data = crypto_price_data.merge(df, on="Date", how="outer")

crypto_price_data.to_csv("cryptocurrency_daily_open.csv")


"""
This is a base service class implementation.
Please override set_cache_xxx methods with extra logic for Redis in the inherited class.
    * xxx - create/update/delete
"""
import typing

import pydantic

from fastapi import BackgroundTasks
from app.repositories.base_db_repository import CRUDBaseRepository, ModelType
from app.repositories.redis_repository import RedisBaseRepository

class BaseService:
    """Base abstract service class."""
    MSG_NOT_IMPLEMENTED = "Method or function hasn't been implemented yet."

    def __init__(self, db: CRUDBaseRepository, redis: RedisBaseRepository, bg_tasks: BackgroundTasks | None = None):
        self.db = db
        self.redis = redis
        self.bg_tasks = bg_tasks

    async def _add_bg_task(self, method, obj: ModelType | list[ModelType]) -> None:
        if obj:
            self.bg_tasks.add_task(method, obj) if self.bg_tasks is not None else await method(obj)

    async def set_cache(self, obj: ModelType | list[ModelType]) -> None:
        if obj:
            await self.redis.set_all(obj) if isinstance(obj, list) else await self.redis.set_obj(obj)

    async def __get(self, method_name: str | None = None, pk: int | None = None) -> ModelType | None:
        obj = (await self.redis.get_all() if pk is None else
               await self.redis.get_obj(pk))
        if obj:
            return obj
        obj = (await self.db.get_all() if pk is None else
               await self.db.__getattribute__(method_name)(pk))
        await self._add_bg_task(self.set_cache, obj)
        return obj

    async def get(self, pk: int) -> ModelType | None:
        return await self.__get('get', pk)

    async def get_or_404(self, pk: int) -> ModelType:
        return await self.__get('get_or_404', pk)

    async def get_all(self, exception: bool = False) -> list[ModelType] | None:
        return await self.__get()

    async def set_cache_create(self, obj) -> None:
        raise NotImplementedError(self.MSG_NOT_IMPLEMENTED)

    async def set_cache_update(self, obj) -> None:
        raise NotImplementedError(self.MSG_NOT_IMPLEMENTED)

    async def set_cache_delete(self, obj) -> None:
        raise NotImplementedError(self.MSG_NOT_IMPLEMENTED)

    async def create(self,
                     payload: pydantic.BaseModel,
                     extra_data: typing.Any | None = None) -> ModelType:
        """Base class provides database create method and put a setting
        cache task to background."""
        obj = await self.db.create(payload, extra_data=extra_data)
        await self._add_bg_task(self.set_cache_create, obj)
        return obj

    async def update(self,
                     pk: int,
                     payload: pydantic.BaseModel) -> ModelType:
        """Base class provides database update method."""
        obj = await self.db.update(pk, payload)
        await self._add_bg_task(self.set_cache_update, obj)
        return obj

    async def delete(self, pk: int) -> ModelType:
        """Base class provides database delete method."""
        obj = await self.db.delete(pk)
        await self._add_bg_task(self.set_cache_delete, obj)
        return obj


import itertools
import logging
from decimal import Decimal
from typing import Iterable, Dict, Set, Optional, List, Any

from abccore.checkpoint_service import CheckpointService
from abcnet.handlers import AbstractItemHandler
from abcnet.structures import Message
from abcnet.timer import SimpleTimer

from abcckpt import ckpt_constants, fast_vrf
from abcckpt.ckptItems import CkptItemType, ValidatorVote, MajorityVotes
from abcckpt.ckptParser import CkptItemsParser
from abcckpt.ckpt_creation_state import StateTransitionObserver
from abcnet.services import ChannelService
from abcckpt.pre_checkpoint import PreCheckpoint, PreCkptItemProcessor, AgentService
from abcckpt.ckpt_creation_state import PreCkptStatus
from abcckpt.vote_cr_handler import VoteCrHandler

logger = logging.getLogger(__name__)

class VoteWrap:

    vote_qualifier: str = None
    voter_info: "VoterInfo" = None
    vote: Optional[ValidatorVote] = None

    is_requested = False
    is_processed = False

    def __eq__(self, other: "VoteWrap"):
        if other is None or not isinstance(other, VoteWrap):
            return False
        return self.vote == other.vote

    def __hash__(self):
        return hash(self.vote)

class VoterInfo:

    validator: bytes = None  # public key of the validator that has voted.

    votes: Set[VoteWrap] = None  # the votes that the public key has casted and signed.

    stake: Decimal = None

    def __init__(self, validator_key: bytes):
        self.validator = validator_key
        self.votes = set()

    @property
    def voted_item_qualifier(self) -> Optional[str]:
        if not self.has_voted:
            # No votes has been casted by this validator which is not possible
            raise ValueError("This object cannot exist with an empty vote set.")
        elif len(self.votes) > 1:
            # Multiple votes are interpreted as None
            return None
        else:
            # If we know who has voted we should know what was voted as both information come in the same item content.
            vote: VoteWrap = next(iter(self.votes))
            assert vote is not None
            return vote.vote.voted_item_id

    @property
    def has_voted(self) -> bool:
        return len(self.votes) > 0

    def get_vote(self, voted_item_id) -> Optional[VoteWrap]:
        for v in self.votes:
            if v.vote is not None and v.vote.voted_item_id == voted_item_id:
                return v
        return None

    def mark_vote_requested(self):
        assert self.has_voted
        voted_item = self.voted_item_qualifier
        vote_wrap = self.get_vote(voted_item)
        if vote_wrap is not None:
            vote_wrap.is_requested = True
        else:
            for vote_wrap in self.votes:
                vote_wrap.is_requested = True

    def incompatible_vote(self, vote_identifier: Optional[str]) -> bool:
        if vote_identifier is None:
            return False
        return vote_identifier != self.voted_item_qualifier

    def __eq__(self, other: "VoterInfo"):
        if other is None or not isinstance(other, VoterInfo):
            return False
        return self.validator == other.validator

    def __hash__(self):
        return hash(self.validator)

class VoteRegistry:

    def __init__(self):
        # Voted items:
        self.item_votes: Dict[str, Set[VoterInfo]] = dict()
        # Voters:
        self.voters: Dict[bytes, VoterInfo] = dict()
        # Vote item ids:
        self.votes: Dict[str, VoteWrap] = dict()

        self.majority_votes: Optional[List[ValidatorVote]] = None

    def has_vote(self, vote_qualifier: str) -> bool:
        return vote_qualifier in self.votes

    def get_or_create_vote(self, vote_qualifier: str) -> VoteWrap:
        assert vote_qualifier is not None
        if vote_qualifier not in self.votes:
            viw = VoteWrap()
            viw.vote_qualifier = vote_qualifier
            self.votes[vote_qualifier] = viw
        return self.votes[vote_qualifier]

    def register_to_voter(self, vw: VoteWrap, vote: ValidatorVote, ckpt_service: CheckpointService) -> bool:
        if vw.vote is not None:
            assert vw.vote is vote
            return False
        assert vw is self.votes[vote.item_qualifier()]
        assert vw.vote is None
        vw.vote = vote
        if vw.vote.pub_key not in self.voters:
            voter_info = VoterInfo(vw.vote.pub_key)
            voter_info.stake = ckpt_service.delegated_stake(vw.vote.pub_key)
            self.voters[vw.vote.pub_key] = voter_info
        else:
            voter_info = self.voters[vw.vote.pub_key]
        vw.voter_info = voter_info
        voter_info.votes.add(vw)
        self.redistribute_vote(voter_info)
        return True

    def redistribute_vote(self, voter_info: VoterInfo):
        voted_item = voter_info.voted_item_qualifier
        if voted_item not in self.item_votes:
            self.item_votes[voted_item] = set()

        self.item_votes[voted_item].add(voter_info)

        for vw in voter_info.votes:
            other_vote = vw.vote.voted_item_id
            if other_vote is voted_item:
                continue
            if other_vote in self.item_votes:
                self.item_votes[other_vote].discard(voter_info)

    def is_emtpy(self):
        return len(self.votes) == 0 and len(self.item_votes) == 0 and len(self.voters) == 0

class Majority:
    voted_item: Optional[str] = None

    transition_buffer_timer: SimpleTimer

    majority_votes_post_timer: SimpleTimer

    def __init__(self, voted_item: Optional[str]):
        self.voted_item = voted_item
        self.transition_buffer_timer = SimpleTimer(ckpt_constants.TRANSITION_BUFFER_TIME, start=True)
        self.majority_votes_post_timer = SimpleTimer(ckpt_constants.MAJORITY_VOTE_POST_PERIOD)

class StabVotingHandler(AbstractItemHandler, StateTransitionObserver):
    """
    Item processor class for processing votes in each step of checkpoint creation. Majority checks and stalemate checks
    are done after evaluating the vote distribution.
    """
    def __init__(self, pc: PreCheckpoint, ckpt_service: CheckpointService,
                 agent_service: Optional[AgentService]=None):
        super().__init__([CkptItemType.VALVOTE, CkptItemType.MAJVOTES], CkptItemsParser())
        self.pc: PreCheckpoint = pc
        self._processors: Dict[PreCkptStatus, PreCkptItemProcessor] = None
        self.vote_cr_handler: Optional[VoteCrHandler] = None
        self.agent_service: Optional[AgentService] = agent_service
        self.ckpt_service: CheckpointService = ckpt_service
        self.prev_registry: VoteRegistry = VoteRegistry()  # Initialize with an empty registry
        self.registry: VoteRegistry = VoteRegistry()

        self.stake_vote_threshold: Optional[Decimal] = None

        self.new_vote_distrib = False
        self.new_vote_found = False
        self.state_transition_performed = False

        self.stalemate_found = False
        self.is_minority_voter = False
        self.stalemate_vote_switch = False
        self.stalemate_timer = SimpleTimer(ckpt_constants.MISSING_VOTES_REQUEST_TIME)

        self.majority: Optional[Majority] = None
        # Timers for maintenance:
        self.timeout_timers = [
            (self.request_missing_votes, SimpleTimer(ckpt_constants.MISSING_VOTES_REQUEST_TIME)),
            (self.share_vote_checklist, SimpleTimer(ckpt_constants.VOTES_CHECKLIST_TIME)),
            (self.share_requested_voted, SimpleTimer(ckpt_constants.REQUESTED_VOTE_RESPONSE_TIME)),
            (self.eval_current_votes_distribution, SimpleTimer(ckpt_constants.VOTE_DISTRIB_EVAL_TIME)),
            (self.prev_state_transition_maj_vote_broadcast, SimpleTimer(ckpt_constants.PREV_VOTES_CHECKLIST_BROADCAST))
        ]

    def set_handlers(self,
                     prio_handler: PreCkptItemProcessor,
                     hash_handler: PreCkptItemProcessor,
                     content_handler: PreCkptItemProcessor,
                     vote_cr_handler: Optional[VoteCrHandler] = None):
        self._processors = {
            PreCkptStatus.AGREE_VALIDATOR: prio_handler,
            PreCkptStatus.AGREE_HASH: hash_handler,
            PreCkptStatus.AGREE_CONTENT: content_handler,
        }
        self.vote_cr_handler = vote_cr_handler

    @property
    def processors(self) -> Dict[PreCkptStatus, PreCkptItemProcessor]:
        if not self._processors:
            raise Exception("Processors not yet initialized. "
                            "Call set_handlers at initialization.")
        return self._processors

    def get_current_processor(self) -> PreCkptItemProcessor:
        if self.current_state.step_status not in self.processors:
            raise Exception("Current step %s does not have a processor.")
        return self.processors[self.current_state.step_status]

    def process_vote(self, vote: ValidatorVote, outside_source=False):
        if vote.state != self.current_state:
            logger.debug("Received a vote from another round. Ignoring vote.. My state: %s\nThe other state: %s",
                           self.current_state, vote.state)
            return

        if vote.signature is None:
            logger.warning("Received a vote with no signature: %s", vote)
            return

        if vote.voted_item_type != self.get_current_vote_item_type():
            logger.debug("Received a vote with an unexpected voted item type: %s", vote)
            return

        vw = self.registry.get_or_create_vote(vote.item_qualifier())
        if vw.is_requested and outside_source:
            logger.debug("Requested vote has been delivered through network. Marking it unrequested: %s", vote)
            vw.is_requested = False
        if vw.is_processed:
            logger.debug("Already processed vote %s. Skipping", vote)
            return

        if not vote.verify_signature():
            logger.debug("A vote received with invalid signature: %s", vote)
            vw.is_processed = True
            return

        new_vote = self.registry.register_to_voter(vw, vote, self.ckpt_service)
        if new_vote:
            if  vote.voted_item_id is not None:
                self.get_current_processor().check_item_exists(vote.voted_item_id)
            self.new_vote_distrib = True
        vw.is_processed = True

    def get_current_vote_item_type(self):
        if self.current_state.step_status == PreCkptStatus.AGREE_VALIDATOR:
            return CkptItemType.PRIORITY
        if self.current_state.step_status == PreCkptStatus.AGREE_HASH:
            return CkptItemType.CKPT_HASH
        if self.current_state.step_status == PreCkptStatus.AGREE_CONTENT:
            return CkptItemType.CKPT_DATA

    def process_majority_votes(self, maj_votes: MajorityVotes, registry: VoteRegistry):
        vote_set = set(maj_votes.votes)
        if len(vote_set) == 0:
            return

        for vote_qualifier in vote_set:
            if registry.has_vote(vote_qualifier):
                vote_wrap = registry.get_or_create_vote(vote_qualifier)
                if vote_wrap.vote is None:
                    continue
                if vote_wrap.voter_info.incompatible_vote(maj_votes.voted_item_qualifier):
                    logger.warning("A majority vote was posted that has incomplete information: %s",
                                   maj_votes.voted_item_qualifier)
                    vote_wrap.voter_info.mark_vote_requested()

    def handle_item_content(self, cs: "ChannelService", msg: Message, item_type: int, item_content: Any):
        if item_type == CkptItemType.MAJVOTES and item_content is not None and isinstance(item_content, MajorityVotes):
            self.process_majority_votes(item_content, self.registry)
            self.process_majority_votes(item_content, self.prev_registry)
        if item_type == CkptItemType.VALVOTE and item_content is not None and isinstance(item_content, ValidatorVote):
            self.process_vote(item_content, outside_source=True)
        logger.debug("Received unexpected item with type: %d, %s", item_type, item_content)

    def handle_item_request(self, cs: "ChannelService", msg: Message, item_type: int, item_qualifier: str):
        if item_type != CkptItemType.VALVOTE:
            logger.debug("Received unexpected item with type: %d, %s", item_type, item_qualifier)
            return
        if self.prev_registry.has_vote(item_qualifier):
            vote = self.prev_registry.get_or_create_vote(item_qualifier)
            if vote.vote is not None:
                logger.debug("Vote %s is requested by the network but it is in the prev registry. "
                             "We will reply to it later.",
                             item_qualifier)
                vote.is_requested = True

        elif self.registry.has_vote(item_qualifier):
            vote_wrap = self.registry.get_or_create_vote(item_qualifier)
            if vote_wrap.vote is not None:
                vote_wrap.is_requested = True
            elif vote_wrap.is_requested:
                logger.debug("Vote %s was requested by the network so we will not send a request ourselves.",
                             item_qualifier)
                vote_wrap.is_requested = False

    def handle_item_checklist(self, cs: "ChannelService", msg: Message, item_type: int, item_qualifier: str):
        if item_type != CkptItemType.VALVOTE:
            logger.debug("Received unexpected item with type: %d, %s", item_type, item_qualifier)
            return
        vw = self.registry.get_or_create_vote(item_qualifier)
        if vw.vote is None:
            self.new_vote_found = True

    def perform_maintenance(self, cs: ChannelService, force_maintenance=False):
        self.check_state_transition()
        for maintenance_method, timer in self.timeout_timers:
            if force_maintenance or timer():
                # Timer of action has reached zero.
                # Perform maintenance action by calling the method that has the action_name.
                maintenance_method(cs)

    def get_missing_votes(self) -> Iterable[VoteWrap]:
        return filter(lambda vw: vw.vote is None, self.registry.votes.values())

    def request_missing_votes(self, cs: ChannelService):
        if not self.new_vote_found:
            # logger.debug("No votes are missing. Not requesting any vote.")
            return
        cs.broadcast_channel().fetch_items([
            (CkptItemType.VALVOTE, vw.vote_qualifier)
            for vw in self.get_missing_votes()
        ])
        self.new_vote_found = False

    def get_present_votes(self) -> Iterable[VoteWrap]:
        return filter(lambda vw: vw.vote is not None, self.registry.votes.values())

    def share_vote_checklist(self, cs: ChannelService):
        vote_checklist = [vw.vote for vw in self.get_present_votes()]
        if vote_checklist:
            cs.broadcast_channel().checklist(vote_checklist)

    def get_requested_votes(self, registry: VoteRegistry) -> Iterable[VoteWrap]:
        return filter(lambda vw: vw.vote is not None and vw.is_requested, registry.votes.values())

    def get_all_requested_votes(self) -> Iterable[VoteWrap]:
        return itertools.chain(self.get_requested_votes(self.registry),
                              self.get_requested_votes(self.prev_registry))

    def share_requested_voted(self, cs: ChannelService):
        requested_votes = list(self.get_all_requested_votes())
        if requested_votes:
            cs.broadcast_channel().items([
                vw.vote for vw in requested_votes
            ])
        for vw in requested_votes:
            vw.is_requested = False

    def eval_current_votes_distribution(self, cs: ChannelService):
        self.find_new_majority()
        if self.majority:
            if not self.state_transition_performed:
                logger.info("Performing state transition from state %s. Majority votes item: %s", self.state,
                            self.majority.voted_item)
                self.ready_transition(cs)
        elif self.stalemate_found:
            if not self.stalemate_vote_switch:
                if self.is_minority_voter or self.stalemate_timer.check():
                    self.switch_vote_to_pass()
            else:
                logger.warning("Stalemate detected but already switched vote.")

    def get_support_of_vote(self, vote_item_qualifier: Optional[str]) -> Decimal:
        if vote_item_qualifier in self.registry.item_votes:
            return sum(map(lambda voter_info: voter_info.stake, self.registry.item_votes[vote_item_qualifier]))
        return Decimal(0.0)

    def get_self_vote_support(self) -> Decimal:
        if self.agent_service is None:
            return Decimal(0)
        max_vote_support = Decimal(0)
        for key in self.agent_service.get_keypairs():
            pub_key = fast_vrf.encode_pub_key(key.public_key())
            if pub_key not in self.registry.voters:
                continue
            voted_item_id = self.registry.voters[pub_key].voted_item_qualifier
            if voted_item_id not in self.registry.item_votes:
                continue
            summed_voting_stake = self.get_support_of_vote(voted_item_id)
            if summed_voting_stake > max_vote_support:
                max_vote_support = summed_voting_stake
        return max_vote_support

    def find_new_majority(self):
        if not self.new_vote_distrib:
            return
        self.new_vote_distrib = False

        majority_voted_item_id: Optional[str] = None
        majority_found = False
        all_votes_stake_sum = Decimal(0.0)
        for voted_item_id in self.registry.item_votes.keys():
            summed_voting_stake = self.get_support_of_vote(voted_item_id)
            all_votes_stake_sum += summed_voting_stake
            if self.is_majority_threshold_surpassed(summed_voting_stake):
                if majority_found:
                    raise Exception("While counting votes two simultaneous majorities. Current state: %s"
                                    "\nVoted item 1:%s"
                                    "\nVoted item 2: %s",
                                    self.current_state, majority_voted_item_id, voted_item_id)
                majority_found = True
                majority_voted_item_id = voted_item_id
        if majority_found:
            self.set_majority(majority_voted_item_id)
            self.stalemate_found = False
            self.is_minority_voter = False
        else:
            self.unset_majority()
            stalemate_condition = self.is_majority_threshold_surpassed(all_votes_stake_sum)
            if stalemate_condition and not self.stalemate_found:
                self.stalemate_found = True
                self.stalemate_timer.reset()
                remaining_votes = self.ckpt_service.stake_sum() - all_votes_stake_sum
                if self.stalemate_found:
                    self.is_minority_voter = not self.is_majority_threshold_surpassed(remaining_votes +
                                                                              self.get_self_vote_support())

    def is_majority_threshold_surpassed(self, vote_stake: Decimal) -> bool:
        try:
            return self.stake_vote_threshold < vote_stake
        except AttributeError:
            return (self.ckpt_service.stake_sum() * Decimal(2 / 3)) < vote_stake # incase of None

    def set_majority(self, voted_item: Optional[str]):
        if self.majority is not None and self.majority.voted_item != voted_item:
            logger.warning("Majority voted item is switched from %s to %s.", self.majority.voted_item, voted_item)
            self.unset_majority()
        logger.info("Found a new majority for voted item %s in state: %s", voted_item, self.current_state)
        self.majority: Optional[Majority] = Majority(voted_item)

    def unset_majority(self):
        if self.majority is not None:
            logger.warning("Majority of votes was found for item id: %s. Unsetting it.", self.majority.voted_item)
            self.majority: Optional[Majority] = None

    def ready_transition(self, cs: ChannelService):
        if not self.majority.transition_buffer_timer.check():
            logger.debug("Majority of votes for item %s  in state %s has been found. Remaining buffer time: %s",
                         self.majority.voted_item, self.current_state, self.majority.transition_buffer_timer)
            self.post_majority_vote(cs)
            return

        if self.majority.voted_item is not None and \
                not self.get_current_processor().check_item_exists(self.majority.voted_item):
            logger.info("The voted item %s in state %s has not been received yet. Waiting..",
                           self.majority.voted_item, self.current_state)
            return

        logger.info("Majority of voted item, %s, has been found and the buffer time has passed. "
                    "Performing transition from state: %s.", self.majority.voted_item, self.current_state)
        self.get_current_processor().transition(self.get_majority_votes(), self.majority.voted_item)
        self.state_transition_performed = True
        self.registry.majority_votes = self.get_majority_votes()

    def switch_vote_to_pass(self):
        assert not self.stalemate_vote_switch
        self.stalemate_vote_switch = True
        if self.vote_cr_handler is not None:
            logger.warning("Switching to pass vote as %sminority voter.", "" if self.is_minority_voter else "non-")
            self.vote_cr_handler.create_vote(None, {
                PreCkptStatus.AGREE_VALIDATOR: CkptItemType.PRIORITY,
                PreCkptStatus.AGREE_HASH: CkptItemType.CKPT_HASH,
                PreCkptStatus.AGREE_CONTENT: CkptItemType.CKPT_DATA,
            }.get(self.pc.state.step_status))

    def post_majority_vote(self, cs: ChannelService):
        if not self.majority.majority_votes_post_timer():
            return
        assert self.majority is not None
        majority_votes = self.get_majority_votes()
        assert len(majority_votes) > 0
        logger.debug("Broadcasting %d many majority votes.", len(majority_votes))
        maj_votes = MajorityVotes(state=self.current_state,
                                  votes=[v.item_qualifier() for v in majority_votes],
                                  voted_item_qualifier=self.majority.voted_item)
        cs.broadcast_channel().items([maj_votes])

    def get_majority_votes(self) -> List[ValidatorVote]:
        majority_voters = filter(lambda vote_info: vote_info.stake > 0,
                                 self.registry.item_votes[self.majority.voted_item])
        votes = list()
        for voter_info in majority_voters:
            assert voter_info.has_voted
            assert voter_info.voted_item_qualifier == self.majority.voted_item
            vote = None
            for voter_vote in voter_info.votes:
                if voter_vote.vote.voted_item_id == self.majority.voted_item:
                    vote = voter_vote.vote
                    break
            if vote is None:
                logger.warning("No pass vote found for a validator. Only multiple different votes: %s",
                               voter_info.votes)
                votes += list(voter_info.votes)
            else:
                votes.append(vote)
        return votes

    def prev_state_transition_maj_vote_broadcast(self, cs: ChannelService):
        # If there is a prev registry post the votes of the previous majority as a checklist so other peers
        # can fetch them and perform the same transition.
        if self.prev_registry is not None and self.prev_registry.majority_votes is not None:
            cs.broadcast_channel().checklist(self.prev_registry.majority_votes)

    def handle_state_transition(self, state):
        self.clear_state()
        if state.is_new_ckpt_round():
            self.stake_vote_threshold = (self.ckpt_service.stake_sum() * Decimal(2 / 3))

    def clear_state(self):
        logger.debug("Cleared vote registry for new state: %s", self.current_state)
        self.prev_registry = self.registry
        self.registry = VoteRegistry()
        self.new_vote_distrib = False
        self.new_vote_found = False
        self.majority: Optional[Majority] = None
        self.state_transition_performed = False

        self.stalemate_found = False
        self.stalemate_vote_switch = False
        self.is_minority_voter = False


from flask import render_template, request, redirect, session, flash, url_for, send_from_directory
import querys, crud_routes
from main import app

#####################
####### ROTAS #######
#####################
@app.route('/')
def mainpage():
    return render_template('login.html', title='Enter with your credentials')

@app.route('/list')
def listar():
    if 'current_user' not in session or session['current_user'] == None:
        return render_template('login.html', title='Enter with your credentials')

    games = querys.games_query()
    return render_template('list.html', title='My new title', jogos=games)

@app.route('/insert')
def insert():
    if 'current_user' not in session or session['current_user'] == None:
        return render_template('login.html', title='Enter with your credentials')

    form = crud_routes.FormJogo()
    return render_template('insert.html', title='Insert a new game', form=form)

@app.post('/auth')
def authenticate():
    users = querys.users_query(request.form['username'])

    if len(users) == 0:
        flash('Nome de usuário e/ou senha não encontrado(s). Tente novamente.')
    else:

        if users[0]['password'] == request.form['user_password']:
            session['current_user'] = users[0]['nickname']
            return redirect(url_for('insert'))

            #return render_template(url_for('listar'))  # not working idkw
        else:
            flash('Nome de usuário e/ou senha não encontrado(s). Tente novamente.')

    return render_template('login.html', title='Enter with your credentials')

@app.route('/logout')
def logout():
    session['current_user'] = None
    flash(f"Usuário deslogado.")
    return redirect(url_for("mainpage"))

@app.route('/edit/<id>')
def edit(id):
    if 'current_user' not in session or session['current_user'] == None:
        return render_template('login.html', title='Enter with your credentials')

    game_info = querys.games_info(id)
    capa_jogo = crud_routes.get_image(id)

    return render_template('edit.html', title='Edit game', name=game_info[0]['name'], category=game_info[0]['category'], platform=game_info[0]['platform'], game_id=id, capa_jogo=capa_jogo)

@app.route('/uploads/<nome_arquivo>')
def imagem(nome_arquivo):
    return send_from_directory('uploads', nome_arquivo)


import contextlib
import io
import os

import pytest

from shop.shop import Item

def test_get_attributes(item):
    """Проверка получения атрибутов экземпляра класса Item"""
    assert item.name == 'товар 1'
    assert item.price == 10000
    assert item.quantity == 20
    assert item.pay_rate == 0.85
    assert len(Item.all) == 1

def test_change_attributes(item):
    """Проверка изменения атрибутов"""
    item.name = 'товар 1_'
    item.price = 10
    item.quantity = 10
    item.pay_rate = 0.5

    assert item.name == 'товар 1_'
    assert item.price == 10
    assert item.quantity == 10
    assert item.pay_rate == 0.5

def test_calculate_total_price(item):
    """Проверка расчета общей стоимости товаров"""
    assert item.calculate_total_price() == 200000

def test_apply_discount(item):
    """Проверка применения скидки на товар"""
    item.pay_rate = 0.8
    assert item.apply_discount() == 8000
    assert item.price == 8000

def test_object_name_str(item):
    """Проверка отображения информации об объекте класса Item для пользователей"""
    assert str(item) == 'товар 1'

def test_object_name_repr(item):
    """Проверка отображения информации об объекте класса Item для разработчиков"""
    assert repr(item) == 'Item(name=товар 1, price=10000, quantity=20)'

def test_exception_long_name(item):
    """Проверка вызова исключения, если название товара будет превышать 10 символов"""
    with pytest.raises(Exception):
        item.name = 'длина названия товара больше 10 символов'

def test_instantiate_from_csv():
    """
    Проверка атрибутов экземпляров, созданных из файла csv.
    Проверка, что создано правильное количество экземпляров.
    """
    Item.instantiate_from_csv(path=os.path.join('tests', 'test.csv'))
    item_1 = Item.all[0]
    item_2 = Item.all[1]
    item_3 = Item.all[2]

    assert len(Item.all) == 3
    assert item_1.name == 'товар 1'
    assert item_1.price == 100
    assert item_1.quantity == 1
    assert item_2.name == 'товар 2'
    assert item_2.price == 55.5
    assert item_2.quantity == 3
    assert item_3.name == 'товар 3'
    assert item_3.price == 2000
    assert item_3.quantity == 6

def test_exception_file_not_found():
    """Проверка вызова исключения, если файл не найден"""
    s = io.StringIO()
    with contextlib.redirect_stdout(s):
        Item.instantiate_from_csv(path=os.path.join('tests', 'file.csv'))
    assert s.getvalue() == 'FileNotFoundError: Отсутствует файл tests\\file.csv\n'

def test_exception_file_damaged_1():
    """Проверка вызова исключения, если файл повреждён"""
    s = io.StringIO()
    with contextlib.redirect_stdout(s):
        Item.instantiate_from_csv(path=os.path.join('tests', 'bad_file_1.csv'))
    assert s.getvalue() == 'InstantiateCSVError: Файл item.csv поврежден\n'

def test_exception_file_damaged_2():
    """Проверка вызова исключения, если файл повреждён"""
    s = io.StringIO()
    with contextlib.redirect_stdout(s):
        Item.instantiate_from_csv(path=os.path.join('tests', 'bad_file_2.csv'))
    assert s.getvalue() == 'InstantiateCSVError: Файл item.csv поврежден\n'

def test_attributes_price_and_quantity():
    """
    Проверка того, что при инициализации объекта класса Item
    нельзя задать атрибуты цена и количество меньше 0
    """
    with pytest.raises(AttributeError):
        Item(name='товар 1', price=-10000, quantity=-1)

def test_add(item):
    """
    Проверка сложения двух экземпляров класса Item.
    Сложение происходит по атрибуту quantity.
    """
    assert item + item == 40

def test_add_exception(item):
    """
    Проверка вызова исключения, если правый операнд не является
    экземпляром класса Item
    """
    with pytest.raises(TypeError):
        result = item + 10


from pyecore.resources.resource import HttpURI, ResourceSet
from pyecore.utils import DynamicEPackage
from pyecore.ecore import EcoreUtils
import pyecore.behavior as behavior

# Load metamodel
rset = ResourceSet()
uri = HttpURI('https://raw.githubusercontent.com/gemoc/ale-lang/master/'
              'examples/minifsm/model/MiniFsm.ecore')
package_root = rset.get_resource(uri).contents[0]
rset.metamodel_registry[package_root.nsURI] = package_root

fsm = DynamicEPackage(package_root)

# Code for each overridden/added method
@fsm.Transition.behavior
def is_activated(self):
    return (self.fsm.currentEvent == self.event
            and self.incoming == self.fsm.currentState)

@fsm.State.behavior
def execute(self):
    print('Execute', self.name)

@fsm.FSM.behavior
def handle(self, event):
    print('Handle', event)
    self.currentEvent = event
    self.currentState = [t for t in self.transitions
                         if t.is_activated()][0].outgoing

@fsm.FSM.behavior
@behavior.main
def entry_point(self):
    print('Start')
    events = ['event1', 'event2']

    self.currentState = [s for s in self.states
                         if isinstance(s, fsm.Initial)][0]
    self.currentState.execute()

    for event in events:
        self.handle(event)
        self.currentState.execute()

    print('End')

# Load the model
uri = HttpURI('https://raw.githubusercontent.com/gemoc/ale-lang/master/'
              'examples/minifsm/model/FSM.xmi')
resource = rset.get_resource(uri)
root = resource.contents[0]

# Execute the model
behavior.run(root)


import re

# -------------------------------------------------------------------------
#
# Gramps modules
#
# -------------------------------------------------------------------------
from ..lib.date import Date
from ._dateparser import DateParser
from ._datedisplay import DateDisplay
from ._datehandler import register_datehandler

# -------------------------------------------------------------------------
#
# Slovenian parser
#
# -------------------------------------------------------------------------
class DateParserSL(DateParser):
    """
    Converts a text string into a Date object
    """

    modifier_to_int = {
        "pred": Date.MOD_BEFORE,
        "pr.": Date.MOD_BEFORE,
        "po": Date.MOD_AFTER,
        "okoli": Date.MOD_ABOUT,
        "okrog": Date.MOD_ABOUT,
        "okr.": Date.MOD_ABOUT,
        "ok.": Date.MOD_ABOUT,
        "cca.": Date.MOD_ABOUT,
        "cca": Date.MOD_ABOUT,
        "circa": Date.MOD_ABOUT,
        "ca.": Date.MOD_ABOUT,
        "približno": Date.MOD_ABOUT,
        "pribl.": Date.MOD_ABOUT,
        "~": Date.MOD_ABOUT,
        "from": Date.MOD_FROM,
        "to": Date.MOD_TO,
    }

    quality_to_int = {
        "ocenjeno": Date.QUAL_ESTIMATED,
        "oc.": Date.QUAL_ESTIMATED,
        "po oceni": Date.QUAL_ESTIMATED,
        "izračunano": Date.QUAL_CALCULATED,
        "izrač.": Date.QUAL_CALCULATED,
        "po izračunu": Date.QUAL_CALCULATED,
    }

    bce = [
        "pred našim štetjem",
        "pred Kristusom",
        "p.n.š.",
        "p. n. š.",
        "pr.Kr.",
        "pr. Kr.",
    ] + DateParser.bce

    def init_strings(self):
        """
        compiles regular expression strings for matching dates
        """

        DateParser.init_strings(self)
        # match 'Day. MONTH year.' format with or without dots
        self._text2 = re.compile(
            r"(\d+)?\.?\s*?%s\.?\s*((\d+)(/\d+)?)?\s*\.?$" % self._mon_str,
            re.IGNORECASE,
        )
        # match Day.Month.Year.
        self._numeric = re.compile(r"((\d+)[/\.-])?\s*((\d+)[/\.-])?\s*(\d+)\.?$")

        self._span = re.compile(
            r"od\s+(?P<start>.+)\s+do\s+(?P<stop>.+)", re.IGNORECASE
        )
        self._range = re.compile(
            r"med\s+(?P<start>.+)\s+in\s+(?P<stop>.+)", re.IGNORECASE
        )
        self._jtext2 = re.compile(
            r"(\d+)?.?\s+?%s\s*((\d+)(/\d+)?)?" % self._jmon_str, re.IGNORECASE
        )

# -------------------------------------------------------------------------
#
# Slovenian display
#
# -------------------------------------------------------------------------
class DateDisplaySL(DateDisplay):
    """
    Slovenian language date display class.
    """

    # TODO fix BUG 7064: non-Gregorian calendars wrongly use BCE notation for negative dates
    # not refactoring _bce_str into base class because it'll be gone under #7064
    _bce_str = "%s pr.Kr."

    display = DateDisplay.display_formatted

# -------------------------------------------------------------------------
#
# Register classes
#
# -------------------------------------------------------------------------
register_datehandler(
    ("sl_SI", "sl", "SL", "slovenščina", "slovenian", "Slovenian", ("%d. %m. %Y",)),
    DateParserSL,
    DateDisplaySL,
)


import sys
import numpy as np
from sklearn import svm
from Ni_ML import *

train_file = sys.argv[1]
test_file = sys.argv[2]
print(train_file,test_file)
#Train ML Model
inputfile=train_file
outfile='feature/train'
#extract feature vector, lables and cooridnates from the input file.
create_input_data(inputfile,outfile)
#build classifier
Ni_model = build_classifier('feature/train_XX.npy','feature/train_YY.npy')
Ni_model.train()

#Test ML Model
#Step 1: extract feature vector, lables and cooridnates from the input file.
inputfile=test_file
outfile='feature/test'
create_input_data(inputfile,outfile)
test_X = np.load('feature/test_XX.npy')
test_Y = np.load('feature/test_YY.npy')
test_pos = np.load('feature/test_pos.npy')
test_Y = test_Y.ravel()
#Step 2: Precit lables of the test data using the build classier
test_1_predict = Ni_model.predict(test_X)
test_1_accuracy = Ni_model.accuracy(test_Y,test_1_predict)
print("Test error: ",np.mean(test_1_accuracy)*100.0)
print("Test accuracy: ",100.00-np.mean(test_1_accuracy)*100.0)
writexyz(len(test_Y),test_pos,test_1_predict,test_Y)


import os
import pandas as pd
from bokeh.plotting import figure, ColumnDataSource
from bokeh.io import curdoc, show, output_file
from bokeh.layouts import column
from bokeh.models.widgets import Tabs, Panel
from bokeh.models import BooleanFilter, CDSView, HoverTool, DatetimeTickFormatter, Slope
from bokeh.palettes import Category20
from bokeh.models.formatters import NumeralTickFormatter
from Harvester.Utils import get_max_min_points
from LoggerApi.Logger import Logger

PATH_FOR_HTML = os.path.dirname(os.getcwd())
PATH_FOR_OTHERS = PATH_FOR_HTML + '/ServiceProvider/static/'
PATH_FOR_HTML += '/ServiceProvider/templates/'

def get_point_data(data_points):
    x = []
    y = []
    for item in data_points:
        x.append(item['x'])
        y.append(item['y'])
    return x, y

class VisualAnalysis(Logger):
    __W_PLOT = 1000
    __H_PLOT = 400
    __TOOLS = 'pan,wheel_zoom,reset,save,box_select,box_zoom'

    __VBAR_WIDTH = 12 * 60 * 60 * 1000
    __RED = Category20[7][6]
    __GREEN = Category20[5][4]
    __BLUE = Category20[3][0]
    __GRAY = Category20[12][11]

    d_formatter = DatetimeTickFormatter(
        hours=["%d %B %Y"],
        days=["%d %B %Y"],
        months=["%d %B %Y"],
        years=["%d %B %Y"],
    )

    def __init__(self, width=1500, height=600, tools=None, bar_width=0):
        super().__init__(VisualAnalysis.__name__, 'VIZ_LOG')
        self.__W_PLOT = width
        self.__H_PLOT = height
        if bar_width != 0:
            self.__VBAR_WIDTH = bar_width
        if tools is not None:
            self.__TOOLS = tools

    @staticmethod
    def __to_col_data_source(data):
        stock_data = ColumnDataSource(data=dict(date=[], open=[], close=[], high=[], low=[], MFI=[], MACD_Hist=[],
                                                MACD=[], MACD_Signal=[], ADX=[], index=[]))
        data['date'] = pd.to_datetime(data['time'], format='%Y-%m-%d')
        stock_data.data = stock_data.from_df(data)

        return stock_data

    def get_candlestick(self, data, show_graph=True, p=None):
        """Candle stick representation of the stock."""
        stock_data = self.__to_col_data_source(data)
        title = "{} Data ({}, Code:{})".format(stock_data.data['security_name'][0],
                                               stock_data.data['symbol'][0], stock_data.data['code'][0])
        if p is None:
            p = figure(x_axis_type="datetime", plot_width=self.__W_PLOT, plot_height=self.__H_PLOT, tools=self.__TOOLS
                       , title=title, toolbar_location='above')

        inc = stock_data.data['close'] > stock_data.data['open']
        dec = stock_data.data['open'] > stock_data.data['close']
        view_inc = CDSView(source=stock_data, filters=[BooleanFilter(inc)])
        view_dec = CDSView(source=stock_data, filters=[BooleanFilter(dec)])

        self.__set_xy_settings(p)

        p.segment(x0='date', x1='date', y0='low', y1='high', color=self.__GREEN, source=stock_data, view=view_inc)
        p.segment(x0='date', x1='date', y0='low', y1='high', color=self.__RED, source=stock_data, view=view_dec)

        main_vbar_green = p.vbar(x='date', width=self.__VBAR_WIDTH, top='open', bottom='close', fill_color=self.__GREEN,
                                 line_color=self.__GREEN, source=stock_data, view=view_inc, name="price")
        main_vbar_red = p.vbar(x='date', width=self.__VBAR_WIDTH, top='open', bottom='close', fill_color=self.__RED,
                               line_color=self.__RED, source=stock_data, view=view_dec, name="price")

        hover_tool = HoverTool(tooltips=[
            ("Date", "@time{%d-%b-%y}"),
            ("Open", "@open{Rs.0,0.00}"),
            ("Close", "@close{Rs.0,0.00}"),
            ("Volume", "@volume{(0.00 a)}")
        ], renderers=[main_vbar_green, main_vbar_red], formatters={"@time": 'datetime'})
        p.tools.append(hover_tool)

        elements = list()
        elements.append(p)
        curdoc().add_root(column(elements))
        curdoc().title = stock_data.data['security_name'][0] + '_CS'
        if show_graph:
            output_file(PATH_FOR_OTHERS + stock_data.data['symbol'][0] + '_CS.html',
                        '{} {}'.format(stock_data.data['security_name'][0], stock_data.data['code'][0]))
            show(p)

        return p

    def get_trend_line(self, data, col_name, show_graph=True, p=None):
        """Close price/ MFI/ ADX in line format"""
        stock_data = self.__to_col_data_source(data)
        max_min_data = self.__to_col_data_source(get_max_min_points(data, 'close'))
        title = "{} Data ({}, Code:{})".format(stock_data.data['security_name'][0],
                                               stock_data.data['symbol'][0], stock_data.data['code'][0])

        if p is None:
            p = figure(x_axis_type="datetime", plot_width=self.__W_PLOT, plot_height=self.__H_PLOT, tools=self.__TOOLS
                       , title=title, toolbar_location='above')

        if col_name == 'close':
            color = self.__BLUE
        elif col_name == 'MFI':
            color = self.__GRAY
        else:
            color = self.__GREEN
        main_line = p.line(x='date', y=col_name, source=stock_data, line_color=color, name=col_name)
        if col_name is 'close':
            p.circle_dot(x='date', y='close', source=max_min_data, line_color=self.__BLUE)

        self.__set_xy_settings(p)

        hover_tool = HoverTool(tooltips=[
            ("Date", "@time{%d-%b-%y}"),
            (col_name.upper(), "@" + col_name + "{0,0.00}"),
            ("Close", "@close{Rs.0,0.00}"),
            ("Volume", "@volume{(0.00 a)}")
        ], renderers=[main_line], formatters={"@time": 'datetime'})
        p.tools.append(hover_tool)

        elements = list()
        elements.append(p)
        curdoc().add_root(column(elements))
        curdoc().title = stock_data.data['security_name'][0] + '_' + col_name

        if show_graph:
            output_file(PATH_FOR_OTHERS + stock_data.data['symbol'][0] + '_{}.html'.format(col_name),
                        '{} {}'.format(stock_data.data['security_name'][0], stock_data.data['code'][0]))
            show(p)

        return p

    def get_macd_plot(self, data, show_graph=False, p=None):
        """MACD indicator plot."""
        stock_data = self.__to_col_data_source(data)

        title = "{} Data ({}, Code:{})".format(stock_data.data['security_name'][0],
                                               stock_data.data['symbol'][0], stock_data.data['code'][0])

        if p is None:
            p = figure(x_axis_type="datetime", plot_width=self.__W_PLOT, plot_height=self.__H_PLOT, tools=self.__TOOLS
                       , title=title, toolbar_location='above')

        macd_hist = p.vbar(x='date', width=self.__VBAR_WIDTH, top='MACD_Hist', fill_color=self.__GRAY,
                           line_color=self.__GRAY, source=stock_data, name="macd_hist")
        macd_line = p.line(x='date', y='MACD', source=stock_data, line_color=self.__BLUE, name="macd_line")
        macd_signal = p.line(x='date', y='MACD_Signal', source=stock_data, line_color=self.__RED, name="macd_signal")

        self.__set_xy_settings(p)

        hover_tool = HoverTool(tooltips=[
            ("Date", "@time{%d-%b-%y}"),
            ("MACD", "@MACD{(0, 0.00)}"),
            ("MACD_S", "@MACD_Signal{(0, 0.00)}"),
            ("MACD_Hist", "@MACD_Hist{(0, 0.00)}")
        ], renderers=[macd_hist, macd_line, macd_signal], formatters={"@time": 'datetime'})
        p.tools.append(hover_tool)

        elements = list()
        elements.append(p)
        curdoc().add_root(column(elements))
        curdoc().title = stock_data.data['security_name'][0] + 'MACD'

        if show_graph:
            output_file(PATH_FOR_OTHERS + stock_data.data['symbol'][0] + '_MACD.html',
                        '{} {}'.format(stock_data.data['security_name'][0], stock_data.data['code'][0]))
            show(p)

        return p

    def get_volume_hist(self, data, show_graph=False, p=None):
        """Volume traded histogram."""
        stock_data = self.__to_col_data_source(data)
        title = "{} Data ({}, Code:{})".format(stock_data.data['security_name'][0],
                                               stock_data.data['symbol'][0], stock_data.data['code'][0])

        if p is None:
            p = figure(x_axis_type="datetime", plot_width=self.__W_PLOT, plot_height=self.__H_PLOT - 200,
                       tools=self.__TOOLS
                       , title=title, toolbar_location='above', y_range=(0, data['volume'].max()))

        main_vbar = p.vbar(x='date', width=self.__VBAR_WIDTH, top='volume', fill_color=self.__GRAY,
                           line_color=self.__GRAY, source=stock_data, name="volume")

        self.__set_xy_settings(p)

        hover_tool = HoverTool(tooltips=[
            ("Date", "@time{%d-%b-%y}"),
            ("Open", "@open{Rs.0,0.00}"),
            ("Close", "@close{Rs.0,0.00}"),
            ("Volume", "@volume{(0.00 a)}")
        ], renderers=[main_vbar], formatters={"@time": 'datetime'})
        p.tools.append(hover_tool)

        elements = list()
        elements.append(p)
        curdoc().add_root(column(elements))
        curdoc().title = stock_data.data['security_name'][0] + 'VOL'

        if show_graph:
            output_file(PATH_FOR_OTHERS + stock_data.data['symbol'][0] + '_VOL.html',
                        '{} {}'.format(stock_data.data['security_name'][0], stock_data.data['code'][0]))
            show(p)

        return p

    def __set_xy_settings(self, p):
        p.xaxis.formatter = self.d_formatter
        p.xaxis.major_label_orientation = 3.14 / 4
        p.grid.grid_line_alpha = 0.3

        p.yaxis.formatter = NumeralTickFormatter(format='0,0[.]000')
        p.x_range.range_padding = 0.05
        p.xaxis.ticker.desired_num_ticks = 40
        p.xaxis.major_label_orientation = 3.14 / 4

    def show_all(self, items, stock_name):
        panels = []
        if 'cd_stick' in items.keys():
            panels.append(Panel(child=column(items['cd_stick'], items['volume']), title='CandleStick/Volume'))
        if 'price' in items.keys():
            panels.append(Panel(child=column(items['price'], items['volume']), title='Price/Volume'))
        if 'MACD' in items.keys():
            panels.append(Panel(child=column(items['MACD'], items['cd_stick']), title='MACD'))
        if 'MFI' in items.keys():
            panels.append(Panel(child=column(items['MFI'], items['cd_stick']), title='MFI'))
        if 'ADX' in items.keys():
            panels.append(Panel(child=column(items['ADX'], items['cd_stick']), title='ADX'))
        if 'PITCH_FORK' in items.keys():
            panels.append(Panel(child=column(items['PITCH_FORK']), title="MOD. SCHIFF'S PITCHFORK"))
        tabs = Tabs(tabs=panels)
        elements = list()
        elements.append(tabs)
        curdoc().add_root(column(elements))
        curdoc().title = stock_name + '_TABS'
        output_file(PATH_FOR_HTML + stock_name + '_TABS.html')
        show(tabs)
        self.add("INFO", "TABS VIEW ON.")

    def get_line(self, point_a, point_b, p=None, colour='gray', show_graph=False):
        """Other util plots"""
        title = 'UTIL_PLOT'

        if p is None:
            p = figure(x_axis_type="datetime", plot_width=self.__W_PLOT, plot_height=self.__H_PLOT - 200,
                       tools=self.__TOOLS
                       , title=title, toolbar_location='above', y_range=(-abs(point_a['y'] + 0.2 * point_a['y']),
                                                                         abs(point_a['y'] + 0.2 * point_a['y'])))

        if colour is 'b':
            color = self.__BLUE
        elif colour is 'g':
            color = self.__GREEN
        elif colour is 'r':
            color = self.__RED
        else:
            color = self.__GRAY
        p.line([point_a['x'], point_b['x']], [point_a['y'], point_b['y']], line_width=4, color=color)
        p.circle([point_a['x'], point_b['x']], [point_a['y'], point_b['y']], size=10, color=color)
        self.__set_xy_settings(p)

        elements = list()
        elements.append(p)
        curdoc().add_root(column(elements))

        if show_graph:
            show(p)

        return p

    def get_slope_for_pitch_fork(self, m, b, plot_data, p=None, show_graph=False, layout=False, debug=False):
        if p is None:
            p = figure(x_axis_type="datetime", plot_width=self.__W_PLOT, plot_height=self.__W_PLOT - 800,
                       tools=self.__TOOLS, toolbar_location='above')

        point_data = {'MID': get_point_data(plot_data['MID']), 'REV': get_point_data(plot_data['REV'])}

        p = self.get_line(plot_data['point_1'], plot_data['point_2'], p=p, colour='b')
        p = self.get_line(plot_data['point_2'], plot_data['point_3'], p=p, colour='b')
        p = self.get_line(plot_data['mid_23'], plot_data['mid_12'], p=p)
        p = self.get_line(plot_data['point_2'], plot_data['GRAD_UP'], p=p)  # UP
        p = self.get_line(plot_data['point_3'], plot_data['GRAD_DN'], p=p)  # DN
        p = self.get_line(plot_data['mid_23'], plot_data['GRAD_MID'], p=p, colour='b')  # MID
        p = self.get_line(plot_data['m1'], plot_data['GRAD_UPM'], p=p, colour='g')  # UPM
        p = self.get_line(plot_data['m2'], plot_data['GRAD_DNM'], p=p, colour='r')  # DNM

        if debug:
            p.circle(x=point_data['MID'][0], y=point_data['MID'][1], size=10, color=self.__GRAY)
            p.circle(x=point_data['REV'][0], y=point_data['REV'][1], size=10, color=self.__RED)

        if layout:
            p.add_layout(Slope(gradient=m, y_intercept=b['UP'], line_color=self.__GRAY))
            p.add_layout(Slope(gradient=m, y_intercept=b['UPM'], line_color=self.__GREEN))
            p.add_layout(Slope(gradient=m, y_intercept=b['MID'], line_color=self.__BLUE))
            p.add_layout(Slope(gradient=m, y_intercept=b['DNM'], line_color=self.__RED))
            p.add_layout(Slope(gradient=m, y_intercept=b['DN'], line_color=self.__GRAY))

        self.__set_xy_settings(p)

        elements = list()
        elements.append(p)
        curdoc().add_root(column(elements))

        if show_graph:
            show(p)

        return p


# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 15:02:49 2019

@author: admin
"""
import pickle
import scipy.io as sio
import scipy.sparse as ss
import numpy as np
from ut import IO, Eval, Misc
from load_dataset import *
DIR = 'data/'+'ml-10m'+'/'
model_pickle = open("./RCE/data/ml-10m/ml-10m32.pkl",'rb')
params = pickle.load(model_pickle, encoding='latin1')
#data_generator = Data(train_file=DIR+'train.mat', test_file=DIR+'test.mat',batch_size=1024,num_neg=5)
train_file=DIR+'train.mat'
test_file=DIR+'test.mat'
R = sio.loadmat(train_file)['train'].tocsr()
test = sio.loadmat(test_file)['test'].tocsr()
U = params[0]
V = params[1]
user_for_test = sio.loadmat("./RCE/data/ml-10m/user.mat")['user'][0]
topk_mat = Eval.topk_search(R[user_for_test,:], U[user_for_test,:], V, 200)
#print(topk_mat.shape)
rerank_mat = np.zeros((69662,100))
user_embed = np.load('./RCE/U_model.npy')
item_embed = np.load('./RCE/V_model.npy')
for id_,u in enumerate(user_for_test):
    user = u
    item = topk_mat[id_,:]
    rerank_score = np.matmul(user_embed[u,:], item_embed[np.squeeze(item),:].T)
    rerank_score = np.squeeze(rerank_score)
#    print(rerank_score.shape)
#    print(rerank_mat[u,:].shape)
#    print(item[(-rerank_score).argsort()[:100]].shape)
    rerank_mat[u,:] = item[(-rerank_score).argsort()[:100]]
rerank = Eval.evaluate_topk(R[user_for_test,:], test[user_for_test,:], rerank_mat[user_for_test,:], 100)
print(Eval.format(rerank))


import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QSpinBox, QLabel, QVBoxLayout
from PyQt5.QtCore import Qt

class QLabeledSpinBox(QWidget):
    def __init__(self, label='label for slider', range=(1,30), initValue:int = 20):
        super().__init__()

        self.SpinBox = QSpinBox()
        self.SpinBox.setFixedSize(70,40)
        font = self.SpinBox.font()
        font.setPointSize(12)
        self.SpinBox.setFont(font)
        self.SpinBox.setRange(*range)
        self.SpinBox.setValue(initValue)
        self.Label = QLabel()
        self.Label.setStyleSheet("""QLabel {
                                    font-size : 10pt;
                                    }""")
        self.Label.setText(label)
        self.Label.setAlignment(Qt.AlignCenter)

        self.Box = QVBoxLayout()
        self.Box.addWidget(self.Label, alignment=Qt.AlignCenter)
        self.Box.addWidget(self.SpinBox, alignment=Qt.AlignBottom | Qt.AlignCenter)

        self.setLayout(self.Box)

    def connect(self, changeValueFunc):
        self.SpinBox.valueChanged.connect(changeValueFunc)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = QLabeledSpinBox()
    ex.show()
    sys.exit(app.exec_())


"""
date.py

This file is a Python module.  You can import this module by saying
import date
at the top of your Python script.
Then in your script, you can use class date.Date
"""

class Date(object):
    """
    Class Date demonstrates class and instance attributes, class and instance methods.
    It is a simple date class, containing year, month, and day integers.
    """

    lengths = [
        None,
        31, #January
        28, #February
        31, #March
        30, #April
        31, #May
        30, #June
        31, #July
        31, #August
        30, #September
        31, #October
        30, #November
        31  #December
    ]

    def __init__(self, month, day, year):
        if not isinstance(year, int):
            raise TypeError(f"year must be int, not {type(year)}")
        if not isinstance(month, int):
            raise TypeError(f"month must be int, not {type(month)}")
        if month < 1 or month > Date.monthsInYear():
            raise ValueError(f"month must be in range 1 to {Date.monthsInYear()} inclusive, not {month}")
        if not isinstance(day, int):
            raise TypeError(f"day must be int, not {type(day)}")
        if day < 1 or day > Date.lengths[month]:
            raise ValueError(f"day must be in range 1 to {Date.lengths[month]} inclusive, not {day}")
        self.year = year
        self.month = month
        self.day = day

    #These three methods are getters.

    def getYear(self):
        "Return my year."
        return self.year

    def getMonth(self):
        "Return the number of my month (1 to 12 inclusive)."
        return self.month

    def getDay(self):
        "Return the number of my day (1 to the length of my month, inclusive)."
        return self.day

    def __str__(self):
        "Return a string that looks like the contents of myself."
        return f"{self.month:02}/{self.day:02}/{self.year:04}"

    def dayOfYear(self):
        "Return my day of the year: a number in the range 1 to 365 inclusive."
        return sum(Date.lengths[1:self.month]) + self.day

    def nextDay(self):
        "Move myself one day into the future."
        if self.day < Date.lengths[self.month]:
            self.day += 1
        else:
            self.day = 1       #Go to the first day of the next month.
            if self.month < len(Date.lengths) - 1:
                self.month += 1
            else:
                self.month = 1 #Go to the first month of the next year.
                self.year += 1

    def nextDays(self, n):
        "Move myself n days into the future."
        if not isinstance(n, int):
            raise TypeError(f"n must be int, not {type(n)}")
        if n < 0:
            raise ValueError(f"n must be nonnegative, not {n}")
        for i in range(n):
            self.nextDay()     #Call the instance method in line 69.

    def monthsInYear():
        "Return the number of months in a year.  This function is selfless."
        return len(Date.lengths) - 1;

    #The definition of class Date ends here.

if __name__ == "__main__":
    import sys
    import datetime
    now = datetime.datetime.now()
    #Create a Date object holding today's date.
    d = Date(now.month, now.day, now.year)
    print(f"Today is {d}.")
    sys.exit(0)


import numpy as np
from splines import latex_matrix

data = np.matrix([(4, 8, 1), (0, 2, -2), (3, 6, 7)])

def qr(A):
    m, n = A.shape

    r = np.zeros((m, n))
    q = np.zeros((n, n))

    for j in range(n):
        y = A[:, j]

        r[j, j] = np.linalg.norm(y.T)
        q[:, j] = (y / r[j, j]).flatten()

        for i in range(j - 1):
            r[j, i] = q[:, j].T * y
            y = y - r[j, i] * q[:, i]

    return q, r

if __name__ == "__main__":
    q, r = qr(data)
    print(latex_matrix(q))
    print(latex_matrix(r))


from walk.config import Config

# BAN_FILE = Config.BAN_FILE
CLIMATES = "CLIMATES"
# CREDITS = Config.CREDITS
EXAMINES = Config.EXAMINES  # Folder
# EXE = Config.EXE
# EXE2 = Config.EXE2
EXITS = "EXITS"
# GWIZ = Config.GWIZ
# HELP1 = Config.HELP1
# HELP2 = Config.HELP2
# HELP3 = Config.HELP3
# LEVELS = Config.LEVELS
LOG = Config.LOG_FILE  # File
# MOTD = Config.MOTD
# NOLOGIN = Config.NOLOGIN
# PFL = Config.PFL
# PFT = Config.PFT
RESET_DATA = Config.RESET_DATA  # Reset Values
RESET_N = Config.RESET_N  # File
RESET_T = Config.RESET_T  # File
ROOMS = Config.ROOMS  # Folder
SNOOP = Config.SNOOP  # Folder
TEXTS = "TEXTS"  # Directories
USERS = Config.UAF_RAND  # File
# WIZLIST = Config.WIZLIST
WORLD = "/usr/tmp/-iy7AM"   # Temp File
ZONES = "ZONES"


import requests
from functools import wraps

from flask import request

from src.config import Config

class TokenValidator:

    def check_token(f):

        @wraps(f)
        def decorated(*args, **kwargs):
            if Config.DENY_ACCESS:
                print('Access denied, API_SECURITY_URL does not exist')
                return '', requests.codes.unauthorized
            token_header = request.headers['authorization']
            print('TOKEN: ' + token_header)
            response = requests.get(Config.API_SECURITY_URL, headers={"Authorization": token_header, "Content-Type": "application/json"})
            if response.status_code != requests.codes.ok:
                print('Access denied, token is invalid')
                return '', requests.codes.unauthorized
            return f(*args, **kwargs)
        return decorated


#!/usr/bin/python3
"""script for finding peak in list of ints, interview prep
"""

"""
Find a peak in a list of unsorted integers.
"""

def find_peak(list_of_integers):
    """BRUTE force implementation for question
    """
    max_i = None
    for i in list_of_integers:
        if max_i is None or max_i < i:
            max_i = i
    return max_i


# This is the Table class originally created for MyPong.
# This class defines a Table that is a 2D rectangle that is a play area.

from tkinter import *

class Table:
    #### constructor
    def __init__(self, window, colour="black", net_colour="green",
                 width=600, height=400, vertical_net=False, horizontal_net=False):
        self.width = width
        self.height = height
        self.colour = colour

        # order a canvas to draw on from tkinter's Canvas class:
        self.canvas = Canvas(window, bg=self.colour, height=self.height, width=self.width)
        self.canvas.pack()

        # add a net to the canvas using its create_line method:
        if(vertical_net):
            self.canvas.create_line(self.width/2, 0, self.width/2, self.height, width=2, fill=net_colour, dash=(15, 23))
        if(horizontal_net):
            self.canvas.create_line(0, self.height/2, self.width, self.height/2, width=2, fill=net_colour, dash=(15, 23))

    #### methods
    # extra tool for adding a rectangle to the canvas
    def draw_rectangle(self, rectangle):
        x1 = rectangle.x_posn
        x2 = rectangle.x_posn + rectangle.width
        y1 = rectangle.y_posn
        y2 = rectangle.y_posn + rectangle.height
        c = rectangle.colour
        return self.canvas.create_rectangle(x1, y1, x2, y2, fill = c)

    # extra tool for adding an oval to the canvas

    # extra tools for manipulating items on the canvas:


from odoo import fields, models

class ResConfigSettings(models.TransientModel):
    _inherit = "res.config.settings"

    donation_credit_transfer_product_id = fields.Many2one(
        related="company_id.donation_credit_transfer_product_id", readonly=False
    )
    donation_account_id = fields.Many2one(
        related="company_id.donation_account_id",
        readonly=False,
        domain="[('reconcile', '=', True), ('deprecated', '=', False), "
        "('company_id', '=', company_id), ('account_type', '=', 'asset_current')]",
    )
    group_donation_check_total = fields.Boolean(
        string="Check Total on Donations",
        implied_group="donation.group_donation_check_total",
    )


import sqlite3
import json

def main():
    allShopInfo = json.load(open('all_shop.json'))

    con = sqlite3.connect('all_shop.sqlite')
    cur = con.cursor()
    cur.execute('''DROP TABLE IF EXISTS `info`''')
    cur.execute('''CREATE TABLE `info` (`version` TEXT)''')
    cur.execute('''INSERT INTO `info` (`version`) VALUES (?)''', (allShopInfo['version'],))
    fieldnames = allShopInfo['shopList'][0].keys()
    shopTableCreateStatement = []
    shopTableCreateStatement.append('CREATE TABLE `shops` (')
    typeMapping = {'px': 'REAL', 'py': 'REAL'}
    prefix = ""
    for fieldname in fieldnames:
        if fieldname[0].isalpha() and fieldname.isalnum():
            shopTableCreateStatement.append(prefix + '`' + fieldname + '` ' + typeMapping.get(fieldname, 'TEXT'))
            prefix = ", "
    shopTableCreateStatement.append(')')
    cur.execute('DROP TABLE IF EXISTS `shops`')
    cur.execute(''.join(shopTableCreateStatement))

    shopInsertData = []
    for shop in allShopInfo['shopList']:
        shopData = []
        for fieldname in fieldnames:
            shopData.append(shop.get(fieldname, ''))
        shopInsertData.append(tuple(shopData))

    shopTableInsertStatement = []
    shopTableInsertStatement.append('INSERT INTO `shops` (')
    prefix = ""
    for fieldname in fieldnames:
        shopTableInsertStatement.append(prefix + '`' + fieldname + '`')
        prefix = ", "
    shopTableInsertStatement.append(') VALUES (')
    shopTableInsertStatement.append('?' + ' ,?' * (len(fieldnames) - 1))
    shopTableInsertStatement.append(')')

    cur.executemany(''.join(shopTableInsertStatement), shopInsertData)

    cur.close()
    con.commit()
    con.close()

if __name__ == '__main__':
    main()


"""
Este é um programa que calcula a raiz de um numero positivo e
mostra a mensagem de invalidez caso ele seja negativo

"""
import math

num1 = 0

while num1 <= 0:

    print('Digite um numero inteiro positivo :')
    num1 = int(input())

    if num1 > 0:
        print(f'A raiz quadrada de {num1} é: {math.sqrt(num1):.2f} ')
    else:
        print('O Número que você digitou é negativo ou inválido.')
    print('Fim do programa')


import json

from django.core.serializers.json import DjangoJSONEncoder
from wagtail.core import blocks

from apps.events.models import EventPage

class EventsTeaserBlock(blocks.StructBlock):
    heading = blocks.CharBlock(required=False)

    def get_context(self, value, parent_context=None):
        context = super().get_context(value, parent_context=parent_context)
        events = EventPage.objects.live()
        js_events = events.values('date', 'title', 'short_description')
        js_data = json.dumps(list(js_events), cls=DjangoJSONEncoder)

        context.update({
            'events': events,
            'js_data': js_data
        })

        return context

    class Meta:
        template = 'events/blocks/eventsteaser_block.html'


from django.shortcuts import render, redirect
from .models import CourseTable, TopicTable
from .form import CourseTableForm, topicform, AssignedCoursesForm
from django.views.generic import DetailView, UpdateView, DeleteView
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from users.models import user

@login_required
def cour(request):
    ku = CourseTable.objects.order_by('id')
    return render(request, 'cours/cours_home.html', {'ku': ku})
@login_required
def user_cours(request):
    ku = CourseTable.objects.order_by('id_course')#TODO: Как правильно?
    return render(request, 'cours/user_cours.html', {'ku': ku})
@login_required
def detail(request, pk):
    ku = list(CourseTable.objects.filter(id=pk).values())
    top = TopicTable.objects.filter(id_course=pk)
    user = auth.get_user(request)
    return render(request, 'cours/datail.html', {'post': ku[0], 'top': top, 'pk': pk, 'user':user})
@login_required
def topic_dateil(request, pk, kk):
    top = TopicTable.objects.filter(id_course=pk)
    ku = list(CourseTable.objects.filter(id=pk).values())
    return render(request, 'cours/topic.html', {'top': top[0], 'pk': pk, 'kk': kk})
@login_required
def my_cours(request): #TODO: Как сделать тут?
    ku = CourseTable.objects.order_by('id')
    return render(request, 'cours/mykurs.html', {'ku': ku})

class kursUpdateView(UpdateView):
    model = CourseTable
    template_name = 'cours/update.html'

    form_class = CourseTableForm

class topicUpdateView(UpdateView):
    model = TopicTable
    template_name = 'cours/update_topic.html'

    form_class = topicform

class kursDeleteView(DeleteView):
    model = CourseTable
    success_url = '/course/'
    template_name = 'cours/cours_delete.html'

class topicDeleteView(DeleteView):
    model = TopicTable
    success_url = '/course/'
    template_name = 'cours/delete_topic.html'

@login_required
def newtopic(request, pk: any):
    error = ''
    if request.method == 'POST':
        form = topicform(request.POST)
        if form.is_valid():
            # form['kursu'] = kursu.objects.filter(id=pk)
            form.save()
            return redirect('kurs')
        else:
            error = 'error'
    form = topicform()
    # form['kursu'] = kursu.objects.filter(id=pk)
    data = {
        'form': form,
        'error': error,
        'pk': pk
    }
    return render(request, 'cours/addTopic.html', data)
@login_required
def adk(request):
    error = ''
    if request.method == 'POST':
        form = CourseTableForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('kurs')
        else:
            error = 'error'
    form = CourseTableForm()
    data = {
        'form': form,
        'error': error
    }
    return render(request, 'cours/addKurs.html', data)
@login_required
def record(request):
    error = ''
    if request.method == 'POST':
        form = AssignedCoursesForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('kurs')
        else:
            error = 'error'
    form = AssignedCoursesForm()
    date = {
           'form': form,
           'error': error
    }
    return render(request, 'cours/RecordToCourse.html', date)


import math
import numpy as np

# PURPOSE: Returns an array representing each rank of each number in given array
def ordArr(arr):
    arr = np.array(arr)
    order = arr.argsort()
    ranks = order.argsort() + 1
    return ranks

def wilcoxon(arr, mean):
    table = []
    yi = []
    abs_yi = []
    rank = []
    signed_rank = []

    # yi row
    for num in arr:
        yi.append(num-mean)
    table.append(yi)

    #abs_yi
    for num in yi:
        abs_yi.append(abs(num))
    table.append(abs_yi)

    # rank
    rank = ordArr(abs_yi)
    table.append(rank)

    # signed_rank
    count = 0
    for num in yi:
        if num < 0:
            signed_rank.append(0 - rank[count])
        else:
            signed_rank.append(rank[count])
        count += 1
    table.append(signed_rank)

    # test statistic
    test_stat = 0 # Placeholder
    for num in signed_rank:
        if num > 0:
            test_stat += num
    print(test_stat)

    return table, test_stat

if __name__ == "__main__":
    arr = [745.5, 1175.0, 1290.0, 1364.5, 1397.5, 1660.0]
    mean = 1386

    results = wilcoxon(arr, mean)
    print(np.matrix(results))


# NIM/Nama : 16521040/Kenneth Ezekiel
# Tanggal : 12/10/2021
# Deskripsi : Program menuliskan bilangan terkecil 10 pangkat x yang lebih dari N

# Algoritma
N = int(input("Masukkan N: "))
condition = True
x = 0
result = 0

while condition:
    if N < (10**x):
        result = (10**x)
        break
    x += 1

print(result)


# author : Philippe Vo
# date   : Mon 02 May 2022 07:24:29 PM

# 3rd party imports
import logging
import os

logger = logging.getLogger(__name__)

def get_user_choice(options: list, msg: str):
    """show list of options for user and ask them to choose an option
    """
    validIdxs = []
    for idx, val in enumerate(options):
        print("{} : {}".format(idx, val))
        validIdxs.append(idx)

    validChoice = False
    while not validChoice:
        try:
            idxChoose = int(input(msg))
            logging.info("selected : {}".format(options[idxChoose]))
            validChoice = True

        except (ValueError, IndexError):
            logging.warning("invalid choice")

    return idxChoose


def solution(s):
    num_dict = {
        "one": "1",
        "two": "2",
        "three": "3",
        "four": "4",
        "five": "5",
        "six": "6",
        "seven": "7",
        "eight": "8",
        "nine": "9",
        "zero": "0",
    }

    while not s.isdigit():
        for key in num_dict.keys():
            if s.find(key) >= 0:
                s = s.replace(key, num_dict[key])

    answer = int(s)

    return answer

if __name__ == "__main__":
    s = "one4seveneight"

    print(solution(s))

숫자문자열과영단어.py

숫자문자열과영단어.py


import json

if __name__ == '__main__':
    test_movie_ids = json.load(open('data/test.json'))
    data = json.load(open('data/features.json'))

    data_to_submit = {}
    for movie_id in test_movie_ids:
        data_to_submit[movie_id] = data[str(movie_id)]

    with open('data/data.json', 'w') as outfile:
        outfile.write(json.dumps(data_to_submit, indent=4, encoding="utf-8"))


from fastapi import APIRouter
from apis.schemas.requests.label_studio.project_request import (
    TransformAnnotation,
)
from apis.schemas.response.label_studio.project_response import (
    TransformAnnotationResponse,
)
from controllers.label_studio.label_studio_controller import ProjectController

project_router = APIRouter()

@project_router.post(
    "/label_studio/transform_annotations", response_model=TransformAnnotationResponse
)
def transform_annotations(transform_annotation_request: TransformAnnotation):
    response = ProjectController().transform_annotations_controller(
        transform_annotation_request
    )
    return TransformAnnotationResponse(**response)


#__init__ config might missing,
# so the parent module was not able to found,
# many exceptions had been raised,
# absolute and realtive import did not work neither,
# so this solution was the only one that actually worked
import sys
import sqlalchemy as db
import pandas as pd
import psycopg2
import sqlite3
import numpy as np
sys.path.append('/Users/attilakiss/Desktop/project_HaHU_KA/Project-HaHU_KA/module1_data_download')
import catalog_collect_class
import SQL_load_class
import URL_validation_class

#creating the list of the missing catalogURLs
missing_catalog_df = pd.DataFrame()
missing_catalog_df = pd.read_excel(
    '/Users/attilakiss/Desktop/project_HaHU_KA/Project-HaHU_KA/ad_id.xlsx',
    'missing_catalogs',
    header = None)

sql_database = '/Users/attilakiss/Desktop/project_HaHU_KA/Project-HaHU_KA/DB/test_db.db'
conn = sqlite3.connect(sql_database)
cur = conn.cursor()

missing_catalogs = missing_catalog_df.iloc[:,0].to_list()  #creating a list from the df
#catalog_validation = True  #manual input for the function / otherwise it would be evaluated
url_validation = URL_validation_class.URL_Validation()
for catalog in missing_catalogs:
    #validating the missing URL
    url_validation.catalog_url_validation(catalog, cur)

    #gathering the catalog data
    car_catalog = catalog_collect_class.CatalogDownload()
    # downloading the raw catalog data
    car_catalog.catalog_raw_download(catalog, url_validation.catalog_validation)
    car_catalog.catalog_data_retrive(cur, catalog)

    #compiling the catalog data
    car_catalog.catalog_attributes['catalog_url'] = catalog

    #loading the cleaned catalog data into the SQL DB
    sql_load = SQL_load_class.SQL_load()
    sql_load.sql_load_catalog(car_catalog.catalog_attributes,
                              cur,
                              url_validation.catalog_validation)
    conn.commit()


# The contents of this file are taken and modified from https://github.com/ialhashim/DenseDepth.
# pylint: disable=missing-function-docstring
from typing import Tuple
import torch
import torch.nn.functional as F
import torchvision.models as M  # type: ignore
from torch import nn

class DenseDepthEncoder(nn.Module):
    """
    The DenseDepth encoder uses DenseNet to obtain an encoding of shape [dim, 320, 240] from an
    input of size [3, 640, 480] for a given output dimension.
    """

    def __init__(self, out_dim: int, *, dropout: float = 0.0):
        super().__init__()
        self.feature_extractor = FeatureExtractor()

        in_features = 2208
        out_features = in_features // 2
        self.conv_in = nn.Sequential(
            nn.Conv2d(in_features, out_features, kernel_size=1, stride=1, padding=1),
            nn.Dropout2d(dropout),
        )
        self.up1 = Upsample(out_features + 384, out_features // 2, dropout=dropout)
        self.up2 = Upsample(out_features // 2 + 192, out_features // 4, dropout=dropout)
        self.up3 = Upsample(out_features // 4 + 96, out_features // 8, dropout=dropout)
        self.up4 = Upsample(out_features // 8 + 96, out_dim)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        block0, block1, block2, block3, block4 = self.feature_extractor(x)
        x0 = self.conv_in(block4)
        x1 = self.up1(x0, block3)
        x2 = self.up2(x1, block2)
        x3 = self.up3(x2, block1)
        return self.up4(x3, block0)

class FeatureExtractor(nn.Module):
    """
    The feature extractor of the DenseDepth encoder, based on DenseNet.
    """

    def __init__(self):
        super().__init__()
        densenet = M.densenet161(pretrained=True)
        features = densenet.features
        self.encoder0 = nn.Sequential(
            features.conv0, features.norm0, features.relu0  # type: ignore
        )
        self.encoder1 = nn.Sequential(features.pool0)  # type: ignore
        self.encoder2 = nn.Sequential(features.denseblock1, features.transition1)  # type: ignore
        self.encoder3 = nn.Sequential(features.denseblock2, features.transition2)  # type: ignore
        self.encoder4 = nn.Sequential(
            features.denseblock3, features.transition3, features.denseblock4  # type: ignore
        )

    def forward(
        self, x: torch.Tensor
    ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
        block0 = self.encoder0(x)
        block1 = self.encoder1(block0)
        block2 = self.encoder2(block1)
        block3 = self.encoder3(block2)
        block4 = self.encoder4(block3)
        return block0, block1, block2, block3, block4

class Upsample(nn.Module):
    """
    The upsample module increases the size of an image.
    """

    def __init__(self, in_channels: int, out_channels: int, dropout: float = 0.0):
        super().__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1),
            nn.LeakyReLU(0.2),
            nn.Dropout2d(dropout),
            nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1),
            nn.LeakyReLU(0.2),
            nn.Dropout2d(dropout),
        )

    def forward(self, x: torch.Tensor, concat: torch.Tensor) -> torch.Tensor:
        z = F.interpolate(
            x, size=[concat.size(2), concat.size(3)], mode="bilinear", align_corners=True
        )
        z = torch.cat([z, concat], dim=1)
        return self.conv(z)