 # Computer Project #11

  #  Algorithm

  #  Design a calendar that records and updates events for the user.

  #  Create a Class P11_Event which contains different functions on the event

  #  Create the functions init, get_date, get_time, get_time_range, str, repr, lt, and eq.

  #  Create the Class P11_Calendar which contains different functions for the events

  #  Create the functions init, add_event, delete_event, day_schedule, str, repr

  #  Create a function( check_time) to check if the time and duration are valid.

  #  Create another function event_prompt to prompt for the event.

  #  In the main function, call the other functions in a loop and display function to perform each task .

  #  If the user input 'q', quit the function.

from p11_calendar import P11_Calendar
from p11_event import P11_Event

CAL_TYPE = ['meeting','event','appointment','other']

MENU = '''Welcome to your own personal calender.
  Available options:
    (A)dd an event to calender
    (D)elete an event
    (L)ist the events of a particular date
    (Q)uit'''

def check_time(time,duration):
    ''' This function returns True if the time and duration are valid and False if otherwise.
    A valid time must start at 6AM and end at 5PM.'''

    try :
        h, m = map(int, time.split(':')) # converting to int and splitting the values
        start_time = h * 60 + m
        if duration == 0: # condition for valid duration
            return False
        else:
            end_time = start_time + duration

        if 360 <= start_time <= end_time <= 1020: # condition to check if the time is valid
            return True
        else:
            return False
    except :
        return False

def event_prompt():
    ''' This function prompts an event, re-prompt until a valid event is entered. Returns the
    event, Prompt for date, time, duration, and cal_tpe.'''

    while True: # it will keep prompting until a valid event is entered.
        date = input("Enter a date (mm/dd/yyyy): ")
        time = input("Enter a start time (hh:mm): ")
        duration = int(input("Enter the duration in minutes (int): "))
        cal_type = input("Enter event type ['meeting','event','appointment','other']: ")

        a = check_time(time, duration) # to check if the time and duration are valid

        event = P11_Event(date,time,duration,cal_type) # to build the event

        if event.valid == True and a == True: # event.valid from valid being an attribute of event
            return event

        else:
            print("Invalid event. Please try again.")
            continue

def main():

    thecalender = P11_Calendar()

    print(MENU)
    Options = ['a','d','l','q']
    Opt = input("Select an option: ").lower()

    while Opt not in Options:
        print("Invalid option. Please try again.") # if the option entered is not amongst the options
        Opt = input("Select an option: ").lower()

    while Opt != 'q':

        if Opt == 'a':
            event = event_prompt()
            print("Add Event")
            b = thecalender.add_event(event)
            if b == True: # if the output of add_event is True
                print("Event successfully added.")
            else:
                print("Event was not added.")

        if Opt == 'd':
            print("Delete Event")
            date = input("Enter a date (mm/dd/yyyy): ")
            time = input("Enter a start time (hh:mm): ")
            d = thecalender.delete_event( date, time)
            if d == True: # if the output of delete_event is True
                print("Event successfully deleted.")
            else:
                print("Event was not deleted.")

        if Opt == 'l':
            print("List Events")
            date = input("Enter a date (mm/dd/yyyy): ")
            c_e = thecalender.day_schedule(date) # using the day_schedule to get the events at a
            for i in c_e:   # particular date
                print(i)
            if c_e == []: # if the list is empty it should print this statement
                print("No events to list on ", date)

        print(MENU)
        Opt = input("Select an option: ").lower()

if __name__ == '__main__':
     main()


# 1154. Day of the Year

class Solution:
    def dayOfYear(self, date: str) -> int:
        year = int(date[:4])
        month = int(date[5:7])
        day = int(date[8:])
        days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
            days[1] += 1
        result = day
        for i in range(month-1):
            result += days[i]
        return result


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

import ecache.db as db
from tests.conftest import engines

def test_session_stack():
    DBSession = db.make_session(engines, force_scope=True)
    session1 = DBSession()

    with db.session_stack():
        session2 = DBSession()
        session2.close()
        with db.session_stack():
            session3 = DBSession()
            session3.close()
        session1.close()

    assert not (session1 is session2 is session3)


from tkinter import *
import tkinter.ttk as ttk
root = Tk()

root.title("test GUI")  # 실행창 이름
root.geometry("640x480")# 창 크기 // 가로x세로 + x좌표 + y좌표
root.resizable(1,0)     # 창 가로,세로 값변경 (허용1 , 불허0)

# values = list(range(1,32))
values = [str(i)+"일" for i in range(1,32)]

combobox = ttk.Combobox(root, height = 5, values = values, state="readonly" ) # state 옵션으로 값을 변경 못하게
combobox.set("카드 결제일")
combobox.current(0)

combobox.pack()

def btncmd():
    print(combobox.get())

btn = Button(root, text="클릭", command=btncmd)
btn.pack()

root.mainloop()


#!/usr/bin/env python3

"""An automatic engine for Python releases

Original code by Pablo Galindo
"""

import argparse
import asyncio
import builtins
import contextlib
import functools
import getpass
import itertools
import os
import pathlib
import re
import shelve
import shutil
import subprocess
import tempfile
import time
import urllib.request
import sys
from dataclasses import dataclass
from shelve import DbfilenameShelf
from typing import Callable, Iterator, List, Optional, final

import aiohttp
import gnupg
import paramiko
import sigstore.oidc
from alive_progress import alive_bar

import release as release_mod
from buildbotapi import BuildBotAPI

API_KEY_REGEXP = re.compile(r"(?P<major>\w+):(?P<minor>\w+)")

RELEASE_REGEXP = re.compile(
    r"(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)\.?(?P<extra>.*)?"
)

DOWNLOADS_SERVER = "downloads.nyc1.psf.io"
DOCS_SERVER = "docs.nyc1.psf.io"

WHATS_NEW_TEMPLATE = """
****************************
  What's New In Python {version}
****************************

:Editor: TBD

.. Rules for maintenance:

   * Anyone can add text to this document.  Do not spend very much time
   on the wording of your changes, because your text will probably
   get rewritten to some degree.

   * The maintainer will go through Misc/NEWS periodically and add
   changes; it's therefore more important to add your changes to
   Misc/NEWS than to this file.

   * This is not a complete list of every single change; completeness
   is the purpose of Misc/NEWS.  Some changes I consider too small
   or esoteric to include.  If such a change is added to the text,
   I'll just remove it.  (This is another reason you shouldn't spend
   too much time on writing your addition.)

   * If you want to draw your new text to the attention of the
   maintainer, add 'XXX' to the beginning of the paragraph or
   section.

   * It's OK to just add a fragmentary note about a change.  For
   example: "XXX Describe the transmogrify() function added to the
   socket module."  The maintainer will research the change and
   write the necessary text.

   * You can comment out your additions if you like, but it's not
   necessary (especially when a final release is some months away).

   * Credit the author of a patch or bugfix.   Just the name is
   sufficient; the e-mail address isn't necessary.

   * It's helpful to add the issue number as a comment:

   XXX Describe the transmogrify() function added to the socket
   module.
   (Contributed by P.Y. Developer in :gh:`12345`.)

   This saves the maintainer the effort of going through the VCS log
   when researching a change.

This article explains the new features in Python {version}, compared to {prev_version}.

For full details, see the :ref:`changelog <changelog>`.

.. note::

   Prerelease users should be aware that this document is currently in draft
   form. It will be updated substantially as Python {version} moves towards release,
   so it's worth checking back even after reading earlier versions.

Summary -- Release highlights
=============================

.. This section singles out the most important changes in Python {version}.
   Brevity is key.

.. PEP-sized items next.

New Features
============

Other Language Changes
======================

New Modules
===========

* None yet.

Improved Modules
================

Optimizations
=============

Deprecated
==========

Removed
=======

Porting to Python {version}
======================

This section lists previously described changes and other bugfixes
that may require changes to your code.

Build Changes
=============

C API Changes
=============

New Features
------------

Porting to Python {version}
----------------------

Deprecated
----------

Removed
-------

"""

@dataclass
class Task:
    function: Callable[[DbfilenameShelf], None]
    description: str

    def __call__(self, db: DbfilenameShelf) -> None:
        return getattr(self, "function")(db)

class ReleaseException(Exception):
    """An error happened in the release process"""

class ReleaseDriver:
    def __init__(
        self,
        tasks: List[Task],
        *,
        release_tag: release_mod.Tag,
        git_repo: str,
        api_key: str,
        ssh_user: str,
        first_state: Optional[Task] = None,
    ) -> None:
        self.tasks = tasks
        dbfile = pathlib.Path.home() / ".python_release"
        self.db = shelve.open(str(dbfile), "c")
        if not self.db.get("finished"):
            self.db["finished"] = False
        else:
            self.db.close()
            self.db = shelve.open(str(dbfile), "n")

        self.current_task: Optional[Task] = first_state
        self.completed_tasks = self.db.get("completed_tasks", [])
        self.remaining_tasks = iter(tasks[len(self.completed_tasks) :])
        if self.db.get("gpg_key"):
            os.environ["GPG_KEY_FOR_RELEASE"] = self.db["gpg_key"]
        if not self.db.get("git_repo"):
            self.db["git_repo"] = pathlib.Path(git_repo)
        if not self.db.get("auth_info"):
            self.db["auth_info"] = api_key
        if not self.db.get("ssh_user"):
            self.db["ssh_user"] = ssh_user

        if not self.db.get("release"):
            self.db["release"] = release_tag

        print("Release data: ")
        print(f"- Branch: {release_tag.branch}")
        print(f"- Release tag: {self.db['release']}")
        print(f"- Normalized release tag: {release_tag.normalized()}")
        print(f"- Git repo: {self.db['git_repo']}")
        print(f"- SSH username: {self.db['ssh_user']}")
        print(f"- python.org API key : {self.db['auth_info']}")
        print()

    def checkpoint(self) -> None:
        self.db["completed_tasks"] = self.completed_tasks

    def run(self) -> None:
        for task in self.completed_tasks:
            print(f"тЬЕ  {task.description}")

        self.current_task = next(self.remaining_tasks, None)
        while self.current_task is not None:
            self.checkpoint()
            try:
                self.current_task(self.db)
            except Exception as e:
                print(f"\rЁЯТе  {self.current_task.description}")
                raise e from None
            print(f"\rтЬЕ  {self.current_task.description}")
            self.completed_tasks.append(self.current_task)
            self.current_task = next(self.remaining_tasks, None)
        self.db["finished"] = True
        print()
        print(f"Congratulations, Python {self.db['release']} is released ЁЯОЙЁЯОЙЁЯОЙ")

def ask_question(question: str) -> bool:
    answer = ""
    print(question)
    while answer not in ("yes", "no"):
        answer = input("Enter yes or no: ")
        if answer == "yes":
            return True
        elif answer == "no":
            return False
        else:
            print("Please enter yes or no.")
    return True

@contextlib.contextmanager
def cd(path: str) -> Iterator[None]:
    current_path = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(current_path)

@contextlib.contextmanager
def supress_print():
    print_func = builtins.print
    builtins.print = lambda *args, **kwargs: None
    yield
    builtins.print = print_func

def check_tool(db: DbfilenameShelf, tool: str) -> None:
    if shutil.which(tool) is None:
        raise ReleaseException(f"{tool} is not available")

check_git = functools.partial(check_tool, tool="git")
check_latexmk = functools.partial(check_tool, tool="latexmk")
check_make = functools.partial(check_tool, tool="make")
check_blurb = functools.partial(check_tool, tool="blurb")
check_autoconf = functools.partial(check_tool, tool="autoconf")
check_docker = functools.partial(check_tool, tool="docker")

def check_gpg_keys(db: DbfilenameShelf) -> None:
    pg = gnupg.GPG()
    keys = pg.list_keys(secret=True)
    if not keys:
        raise ReleaseException("There are no valid GPG keys for release")
    for index, key in enumerate(keys):
        print(f"{index} - {key['keyid']}: {key['uids']}")
    selected_key_index = -1
    while not (0 <= selected_key_index < len(keys)):
        with contextlib.suppress(ValueError):
            selected_key_index = int(
                input("Select one GPG key for release (by index):")
            )
    selected_key = keys[selected_key_index]["keyid"]
    os.environ["GPG_KEY_FOR_db['release']"] = selected_key
    if selected_key not in {key["keyid"] for key in keys}:
        raise ReleaseException("Invalid GPG key selected")
    db["gpg_key"] = selected_key
    os.environ["GPG_KEY_FOR_RELEASE"] = db["gpg_key"]

def check_ssh_connection(db: DbfilenameShelf) -> None:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy)
    client.connect(DOWNLOADS_SERVER, port=22, username=db["ssh_user"])
    client.exec_command("pwd")
    client.connect(DOCS_SERVER, port=22, username=db["ssh_user"])
    client.exec_command("pwd")

def check_buildbots(db: DbfilenameShelf) -> None:
    async def _check():
        async def _get_builder_status(buildbot_api, the_builder):
            return the_builder, await buildbot_api.is_builder_failing_currently(
                the_builder
            )

        async with aiohttp.ClientSession() as session:
            api = BuildBotAPI(session)
            await api.authenticate(token="")
            release_branch = db["release"].branch
            stable_builders = await api.stable_builders(branch=release_branch)
            if not stable_builders:
                release_branch = "3.x"
                stable_builders = await api.stable_builders(branch="3.x")
            if not stable_builders:
                raise ReleaseException(
                    f"Failed to get the stable buildbots for the {release_branch} tag"
                )
            builders = await asyncio.gather(
                *[
                    _get_builder_status(api, the_builder)
                    for the_builder in stable_builders.values()
                ]
            )
            return {the_builder for (the_builder, is_failing) in builders if is_failing}

    failing_builders = asyncio.run(_check())
    if not failing_builders:
        return
    print()
    print("The following buildbots are failing:")
    for builder in failing_builders:
        print(f"- {builder.name}")
    print()
    print("Check https://buildbot.python.org/all/#/release_status for more information")
    print()
    if not ask_question("Do you want to continue even if these builders are failing?"):
        raise ReleaseException("Buildbots are failing!")

def run_blurb_release(db: DbfilenameShelf) -> None:
    subprocess.check_call(["blurb", "release", str(db["release"])], cwd=db["git_repo"])
    subprocess.check_call(
        ["git", "commit", "-m", f"Python {db['release']}"],
        cwd=db["git_repo"],
    )

def check_cpython_repo_is_clean(db: DbfilenameShelf) -> None:
    if subprocess.check_output(["git", "status", "--porcelain"], cwd=db["git_repo"]):
        raise ReleaseException("Git repository is not clean")

def preapre_temporary_branch(db: DbfilenameShelf) -> None:
    subprocess.check_call(
        ["git", "checkout", "-b", f"branch-{db['release']}"], cwd=db["git_repo"]
    )

def remove_temporary_branch(db: DbfilenameShelf) -> None:
    subprocess.check_call(
        ["git", "branch", "-D", f"branch-{db['release']}"], cwd=db["git_repo"]
    )

def prepare_pydoc_topics(db: DbfilenameShelf) -> None:
    subprocess.check_call(["make", "pydoc-topics"], cwd=db["git_repo"] / "Doc")
    shutil.copy2(
        db["git_repo"] / "Doc" / "build" / "pydoc-topics" / "topics.py",
        db["git_repo"] / "Lib" / "pydoc_data" / "topics.py",
    )
    subprocess.check_call(
        ["git", "commit", "-a", "--amend", "--no-edit"], cwd=db["git_repo"]
    )

def run_autoconf(db: DbfilenameShelf) -> None:
    subprocess.check_call(
        [
            "docker",
            "run",
            "--rm",
            "--pull=always",
            f"-v{db['git_repo']}:/src",
            "quay.io/tiran/cpython_autoconf:cp311",
        ],
        cwd=db["git_repo"],
    )
    subprocess.check_call(["docker", "rmi", "quay.io/tiran/cpython_autoconf", "-f"])
    subprocess.check_call(
        ["git", "commit", "-a", "--amend", "--no-edit"], cwd=db["git_repo"]
    )

def check_pyspecific(db):
    with open(
        db["git_repo"] / "Doc" / "tools" / "extensions" / "pyspecific.py", "r"
    ) as pyspecific:
        for line in pyspecific:
            if "SOURCE_URI =" in line:
                break
    expected_branch = db["release"].branch
    expected = (
        f"SOURCE_URI = 'https://github.com/python/cpython/tree/{expected_branch}/%s'"
    )
    if expected != line.strip():
        raise ReleaseException("SOURCE_URI is incorrect")

def bump_version(db: DbfilenameShelf) -> None:
    with cd(db["git_repo"]):
        release_mod.bump(db["release"])
    subprocess.check_call(
        ["git", "commit", "-a", "--amend", "--no-edit"], cwd=db["git_repo"]
    )

def create_tag(db: DbfilenameShelf) -> None:
    with cd(db["git_repo"]):
        if not release_mod.make_tag(db["release"]):
            raise ReleaseException("Error when creating tag")
    subprocess.check_call(
        ["git", "commit", "-a", "--amend", "--no-edit"], cwd=db["git_repo"]
    )

def build_release_artifacts(db: DbfilenameShelf) -> None:
    with cd(db["git_repo"]):
        release_mod.export(db["release"])

def test_release_artifacts(db: DbfilenameShelf) -> None:
    with tempfile.TemporaryDirectory() as tmppath:
        the_dir = pathlib.Path(tmppath)
        the_dir.mkdir(exist_ok=True)
        filename = f"Python-{db['release']}"
        tarball = f"Python-{db['release']}.tgz"
        shutil.copy2(
            db["git_repo"] / str(db["release"]) / "src" / tarball,
            the_dir / tarball,
        )
        subprocess.check_call(["tar", "xvf", tarball], cwd=the_dir)
        subprocess.check_call(
            ["./configure", "--prefix", str(the_dir / "installation")],
            cwd=the_dir / filename,
        )
        subprocess.check_call(["make", "-j"], cwd=the_dir / filename)
        subprocess.check_call(["make", "install", "-j"], cwd=the_dir / filename)
        process = subprocess.run(
            ["./bin/python3", "-m", "test", "-uall"],
            cwd=str(the_dir / "installation"),
            text=True,
        )

    if process.returncode == 0:
        return

    if not ask_question("Some test_failed! Do you want to continue?"):
        raise ReleaseException("Test failed!")

class MySFTPClient(paramiko.SFTPClient):
    def put_dir(self, source, target, progress=None):
        for item in os.listdir(source):
            if os.path.isfile(os.path.join(source, item)):
                progress.text(item)
                self.put(os.path.join(source, item), "%s/%s" % (target, item))
                progress()
            else:
                self.mkdir("%s/%s" % (target, item), ignore_existing=True)
                self.put_dir(
                    os.path.join(source, item),
                    "%s/%s" % (target, item),
                    progress=progress,
                )

    def mkdir(self, path, mode=511, ignore_existing=False):
        try:
            super().mkdir(path, mode)
        except IOError:
            if ignore_existing:
                pass
            else:
                raise

def upload_files_to_server(db: DbfilenameShelf) -> None:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy)
    client.connect(DOWNLOADS_SERVER, port=22, username=db["ssh_user"])

    destination = pathlib.Path(f"/home/psf-users/{db['ssh_user']}/{db['release']}")
    ftp_client = MySFTPClient.from_transport(client.get_transport())

    client.exec_command(f"rm -rf {destination}")

    with contextlib.suppress(OSError):
        ftp_client.mkdir(str(destination))

    artifacts_path = pathlib.Path(db["git_repo"] / str(db["release"]))

    shutil.rmtree(artifacts_path / f"Python-{db['release']}", ignore_errors=True)

    def upload_subdir(subdir):
        with contextlib.suppress(OSError):
            ftp_client.mkdir(str(destination / subdir))
        with alive_bar(len(tuple((artifacts_path / subdir).glob("**/*")))) as progress:
            ftp_client.put_dir(
                artifacts_path / subdir,
                str(destination / subdir),
                progress=progress,
            )

    upload_subdir("src")
    if (artifacts_path / "docs").exists():
        upload_subdir("docs")
    ftp_client.close()

def place_files_in_download_folder(db: DbfilenameShelf) -> None:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy)
    client.connect(DOWNLOADS_SERVER, port=22, username=db["ssh_user"])

    # Sources

    source = f"/home/psf-users/{db['ssh_user']}/{db['release']}"
    destination = f"/srv/www.python.org/ftp/python/{db['release'].normalized()}"

    def execute_command(command):
        channel = client.get_transport().open_session()
        channel.exec_command(command)
        if channel.recv_exit_status() != 0:
            raise ReleaseException(channel.recv_stderr(1000))

    execute_command(f"mkdir -p {destination}")
    execute_command(f"cp {source}/src/* {destination}")
    execute_command(f"chgrp downloads {destination}")
    execute_command(f"chmod 775 {destination}")
    execute_command(f"find {destination} -type f -exec chmod 664 {{}} \\;")

    # Docs

    release_tag: release_mod.Tag = db["release"]
    if release_tag.is_final or release_tag.is_release_candiate:
        source = f"/home/psf-users/{db['ssh_user']}/{db['release']}"
        destination = f"/srv/www.python.org/ftp/python/doc/{release_tag}"

        def execute_command(command):
            channel = client.get_transport().open_session()
            channel.exec_command(command)
            if channel.recv_exit_status() != 0:
                raise ReleaseException(channel.recv_stderr(1000))

        execute_command(f"mkdir -p {destination}")
        execute_command(f"cp {source}/docs/* {destination}")
        execute_command(f"chgrp downloads {destination}")
        execute_command(f"chmod 775 {destination}")
        execute_command(f"find {destination} -type f -exec chmod 664 {{}} \\;")

def upload_docs_to_the_docs_server(db: DbfilenameShelf) -> None:
    release_tag: release_mod.Tag = db["release"]
    if not (release_tag.is_final or release_tag.is_release_candiate):
        return

    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy)
    client.connect(DOCS_SERVER, port=22, username=db["ssh_user"])

    destination = pathlib.Path(f"/home/psf-users/{db['ssh_user']}/{db['release']}")
    ftp_client = MySFTPClient.from_transport(client.get_transport())

    client.exec_command(f"rm -rf {destination}")

    with contextlib.suppress(OSError):
        ftp_client.mkdir(str(destination))

    artifacts_path = pathlib.Path(db["git_repo"] / str(db["release"]))

    shutil.rmtree(artifacts_path / f"Python-{db['release']}", ignore_errors=True)

    def upload_subdir(subdir):
        with contextlib.suppress(OSError):
            ftp_client.mkdir(str(destination / subdir))
        with alive_bar(len(tuple((artifacts_path / subdir).glob("**/*")))) as progress:
            ftp_client.put_dir(
                artifacts_path / subdir,
                str(destination / subdir),
                progress=progress,
            )

    upload_subdir("docs")
    ftp_client.close()

def unpack_docs_in_the_docs_server(db: DbfilenameShelf) -> None:
    release_tag: release_mod.Tag = db["release"]
    if not (release_tag.is_final or release_tag.is_release_candiate):
        return

    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy)
    client.connect(DOCS_SERVER, port=22, username=db["ssh_user"])

    # Sources

    source = f"/home/psf-users/{db['ssh_user']}/{db['release']}"
    destination = f"/srv/docs.python.org/release/{release_tag}"

    def execute_command(command):
        channel = client.get_transport().open_session()
        channel.exec_command(command)
        if channel.recv_exit_status() != 0:
            raise ReleaseException(channel.recv_stderr(1000))

    docs_filename = f"python-{release_tag}-docs-html"
    execute_command(f"mkdir -p {destination}")
    execute_command(f"unzip {source}/docs/{docs_filename}.zip -d {destination}")
    execute_command(f"mv /{destination}/{docs_filename}/* {destination}")
    execute_command(f"rm -rf /{destination}/{docs_filename}")
    execute_command(f"chgrp -R docs {destination}")
    execute_command(f"chmod -R 775 {destination}")
    execute_command(f"find {destination} -type f -exec chmod 664 {{}} \\;")

def send_email_to_platform_release_managers(db: DbfilenameShelf) -> None:
    if not ask_question(
        "Have you notified the platform release managers about the availability of artifacts?"
    ):
        raise ReleaseException("Platform release managers muy be notified")

def create_release_object_in_db(db: DbfilenameShelf) -> None:
    print(
        "Go to https://www.python.org/admin/downloads/release/add/ and create a new release"
    )
    if not ask_question(f"Have you already created a new release for {db['release']}"):
        raise ReleaseException("The django release object has not been created")

def wait_util_all_files_are_in_folder(db: DbfilenameShelf) -> None:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy)
    client.connect(DOWNLOADS_SERVER, port=22, username=db["ssh_user"])
    ftp_client = client.open_sftp()

    destination = f"/srv/www.python.org/ftp/python/{db['release'].normalized()}"

    are_all_files_there = False
    release = str(db["release"])
    print()
    while not are_all_files_there:
        try:
            all_files = set(ftp_client.listdir(destination))
        except FileNotFoundError:
            raise FileNotFoundError(
                f"The release folder in {destination} has not been created"
            ) from None
        are_windows_files_there = f"python-{release}.exe" in all_files
        are_macos_files_there = f"python-{release}-macos11.pkg" in all_files
        are_linux_files_there = f"Python-{release}.tgz" in all_files
        are_all_files_there = (
            are_linux_files_there and are_windows_files_there and are_macos_files_there
        )
        if not are_all_files_there:
            linux_tick = "тЬЕ" if are_linux_files_there else "тЭО"
            windows_tick = "тЬЕ" if are_windows_files_there else "тЭО"
            macos_tick = "тЬЕ" if are_macos_files_there else "тЭО"
            print(
                f"\rWaiting for files: Linux {linux_tick} Windows {windows_tick} Mac {macos_tick}",
                flush=True,
                end="",
            )
            time.sleep(1)
    print()

def run_add_to_python_dot_org(db: DbfilenameShelf) -> None:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy)
    client.connect(DOWNLOADS_SERVER, port=22, username=db["ssh_user"])

    # Ensure the file is there
    source = pathlib.Path(__file__).parent / "add-to-pydotorg.py"
    destination = pathlib.Path(f"/home/psf-users/{db['ssh_user']}/add-to-pydotorg.py")
    ftp_client = MySFTPClient.from_transport(client.get_transport())
    ftp_client.put(str(source), str(destination))
    ftp_client.close()

    auth_info = db["auth_info"]
    assert auth_info is not None

    # Do the interactive flow to get an identity for Sigstore
    issuer = sigstore.oidc.Issuer(sigstore.oidc.DEFAULT_OAUTH_ISSUER_URL)
    identity_token = issuer.identity_token()

    stdin, stdout, stderr = client.exec_command(
        f"AUTH_INFO={auth_info} SIGSTORE_IDENTITY_TOKEN={identity_token} python3 add-to-pydotorg.py {db['release']}"
    )
    stderr_text = stderr.read().decode()
    if stderr_text:
        raise paramiko.SSHException(f"Failed to execute the command: {stderr_text}")
    stdout_text = stdout.read().decode()
    print("-- Command output --")
    print(stdout_text)
    print("-- End of command output --")

def purge_the_cdn(db: DbfilenameShelf) -> None:
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6"
    }
    normalized_release = db["release"].normalized()
    urls = [
        f"https://www.python.org/downloads/release/python-{str(db['release']).replace('.', '')}/",
        f"https://docs.python.org/release/{db['release']}/",
        f"https://www.python.org/ftp/python/{normalized_release}/",
        f"https://www.python.org/ftp/python/{normalized_release}/Python-{db['release']}.tgz",
        f"https://www.python.org/ftp/python/{normalized_release}/Python-{db['release']}.tgz.asc",
        f"https://www.python.org/ftp/python/{normalized_release}/Python-{db['release']}.tar.xz",
        f"https://www.python.org/ftp/python/{normalized_release}/Python-{db['release']}.tar.xz.asc",
        f"https://docs.python.org/release/{normalized_release}/",
        "https://www.python.org/downloads/",
        "https://www.python.org/downloads/windows/",
        "https://www.python.org/downloads/macos/",
    ]
    for url in urls:
        req = urllib.request.Request(url=url, headers=headers, method="PURGE")
        # try:
        response = urllib.request.urlopen(req)
        if response.code != 200:
            raise RuntimeError("Failed to purge the python.org/downloads CDN")

def modify_the_release_to_the_prerelease_pages(db: DbfilenameShelf) -> None:
    pre_release_tags = {"rc", "b", "a"}
    if any(tag in str(db["release"]) for tag in pre_release_tags):
        if not ask_question(
            "Have you already added the release to https://www.python.org/download/pre-releases/"
        ):
            raise ReleaseException(
                "The release has not been added to the pre-release page"
            )
    else:
        if not ask_question(
            "Have you already removed the release from https://www.python.org/download/pre-releases/"
        ):
            raise ReleaseException(
                "The release has not been removed from the pre-release page"
            )

def post_release_merge(db: DbfilenameShelf) -> None:
    release_tag: release_mod.Tag = db["release"]

    subprocess.check_call(
        ["git", "fetch", "--all"],
        cwd=db["git_repo"],
    )

    release_tag: release_mod.Tag = db["release"]
    if release_tag.is_feature_freeze_release:
        subprocess.check_call(
            ["git", "checkout", "main"],
            cwd=db["git_repo"],
        )
    else:
        subprocess.check_call(
            ["git", "checkout", release_tag.branch],
            cwd=db["git_repo"],
        )

    subprocess.check_call(
        ["git", "merge", "--no-squash", f"v{db['release']}"],
        cwd=db["git_repo"],
    )

def post_release_tagging(db: DbfilenameShelf) -> None:
    release_tag: release_mod.Tag = db["release"]

    subprocess.check_call(
        ["git", "fetch", "--all"],
        cwd=db["git_repo"],
    )

    subprocess.check_call(
        ["git", "checkout", release_tag.branch],
        cwd=db["git_repo"],
    )

    with cd(db["git_repo"]):
        release_mod.done(db["release"])

    subprocess.check_call(
        ["git", "commit", "-a", "-m", f"Post {db['release']}"],
        cwd=db["git_repo"],
    )

def maybe_prepare_new_main_branch(db: DbfilenameShelf) -> None:
    release_tag: release_mod.Tag = db["release"]

    if not release_tag.is_feature_freeze_release:
        return

    subprocess.check_call(
        ["git", "checkout", "main"],
        cwd=db["git_repo"],
    )

    new_release = release_tag.next_minor_release()
    with cd(db["git_repo"]):
        release_mod.bump(new_release)

    prev_branch = f"{release_tag.major}.{release_tag.minor}"
    new_branch = f"{release_tag.major}.{int(release_tag.minor)+1}"
    whatsnew_file = f"Doc/whatsnew/{new_branch}"
    with cd(db["git_repo"]), open(whatsnew_file, "w") as f:
        f.write(WHATS_NEW_TEMPLATE.format(version=new_branch, prev_version=prev_branch))

    subprocess.check_call(
        ["git", "add", whatsnew_file],
        cwd=db["git_repo"],
    )

    subprocess.check_call(
        ["git", "commit", "-a", "-m", f"Python {new_release}"],
        cwd=db["git_repo"],
    )

def branch_new_versions(db: DbfilenameShelf) -> None:
    release_tag: release_mod.Tag = db["release"]

    if not release_tag.is_feature_freeze_release:
        return

    subprocess.check_call(["git", "checkout", "main"], cwd=db["git_repo"])

    subprocess.check_call(
        ["git", "checkout", "-b", release_tag.branch],
        cwd=db["git_repo"],
    )

def push_to_local_fork(db: DbfilenameShelf) -> None:
    def _push_to_local(dry_run=False):
        git_command = ["git", "push"]
        if dry_run:
            git_command.append("--dry-run")

        subprocess.check_call(
            git_command + ["origin", "HEAD", "--tags"],
            cwd=db["git_repo"],
        )

    _push_to_local(dry_run=True)
    if not ask_question(
        "Does these operations look reasonable? тЪая╕ПтЪая╕ПтЪая╕П Answering 'yes' will push to your origin remote тЪая╕ПтЪая╕ПтЪая╕П"
    ):
        raise ReleaseException("Something is wrong - Push to remote aborted")
    _push_to_local(dry_run=False)

def push_to_upstream(db: DbfilenameShelf) -> None:
    release_tag: release_mod.Tag = db["release"]

    def _push_to_upstream(dry_run=False):
        branch = f"{release_tag.major}.{release_tag.minor}"
        git_command = ["git", "push"]
        if dry_run:
            git_command.append("--dry-run")

        if release_tag.is_alpha_release:
            subprocess.check_call(
                git_command + ["--tags", "git@github.com:python/cpython.git", "main"],
                cwd=db["git_repo"],
            )
        elif release_tag.is_feature_freeze_release:
            subprocess.check_call(
                git_command + ["--tags", "git@github.com:python/cpython.git", branch],
                cwd=db["git_repo"],
            )
            subprocess.check_call(
                git_command + ["--tags", "git@github.com:python/cpython.git", "main"],
                cwd=db["git_repo"],
            )
        else:
            subprocess.check_call(
                git_command + ["--tags", "git@github.com:python/cpython.git", branch],
                cwd=db["git_repo"],
            )

    _push_to_upstream(dry_run=True)
    if not ask_question(
        "Does these operations look reasonable? тЪая╕ПтЪая╕ПтЪая╕П Answering 'yes' will push to the upstream repository тЪая╕ПтЪая╕ПтЪая╕П"
    ):
        raise ReleaseException("Something is wrong - Push to upstream aborted")
    if not ask_question("Is the target branch unprotected for your user?"):
        raise ReleaseException("The target branch is not unprotected for your user")
    _push_to_upstream(dry_run=False)

def main() -> None:

    if "linux" not in sys.platform:
        print(
            """\
WARNING! This script has not been tested on a platform other than Linux.

Although it should work correctly as long as you have all the dependencies,
some things may not work as expected. As a release manager, you should try to
fix these things in this script so it also support your platform.
"""
        )
        if not ask_question("Do you want to continue?"):
            raise ReleaseException(
                "This release script is not compatible with the running platform"
            )

    parser = argparse.ArgumentParser(description="Process some integers.")

    def _release_type(release):
        if not RELEASE_REGEXP.match(release):
            raise argparse.ArgumentTypeError("Invalid release string")
        return release

    parser.add_argument(
        "--release",
        dest="release",
        help="Release tag",
        required=True,
        type=_release_type,
    )
    parser.add_argument(
        "--repository",
        dest="repo",
        help="Location of the cpython repository",
        required=True,
        type=str,
    )

    def _api_key(api_key):
        if not API_KEY_REGEXP.match(api_key):
            raise argparse.ArgumentTypeError(
                "Invalid api key format. It must be on the form USER:API_KEY"
            )
        return api_key

    parser.add_argument(
        "--auth-key",
        dest="auth_key",
        help="API key for python.org in the form 'USER:API_KEY'",
        type=_api_key,
    )
    parser.add_argument(
        "--ssh-user",
        dest="ssh_user",
        default=getpass.getuser(),
        help="Username to be used when authenticating via ssh",
        type=str,
    )
    args = parser.parse_args()
    auth_key = args.auth_key or os.getenv("AUTH_INFO")
    tasks = [
        Task(check_git, "Checking git is available"),
        Task(check_latexmk, "Checking latexmk is available"),
        Task(check_make, "Checking make is available"),
        Task(check_blurb, "Checking blurb is available"),
        Task(check_docker, "Checking docker is available"),
        Task(check_autoconf, "Checking autoconf is available"),
        Task(check_gpg_keys, "Checking GPG keys"),
        Task(check_ssh_connection, f"Validating ssh connection to {DOWNLOADS_SERVER}"),
        Task(check_buildbots, "Check buildbots are good"),
        Task(check_cpython_repo_is_clean, "Checking git repository is clean"),
        Task(preapre_temporary_branch, "Checking out a temporary release branch"),
        Task(run_blurb_release, "Run blurb release"),
        Task(check_cpython_repo_is_clean, "Checking git repository is clean"),
        Task(prepare_pydoc_topics, "Preparing pydoc topics"),
        Task(run_autoconf, "Running autoconf"),
        Task(check_cpython_repo_is_clean, "Checking git repository is clean"),
        Task(check_pyspecific, "Chech pyspecific"),
        Task(bump_version, "Bump version"),
        Task(check_cpython_repo_is_clean, "Checking git repository is clean"),
        Task(create_tag, "Create tag"),
        Task(build_release_artifacts, "Building release artifacts"),
        Task(test_release_artifacts, "Test release artifacts"),
        Task(upload_files_to_server, "Upload files to the PSF server"),
        Task(place_files_in_download_folder, "Place files in the download folder"),
        Task(upload_docs_to_the_docs_server, "Upload docs to the PSF docs server"),
        Task(unpack_docs_in_the_docs_server, "Place docs files in the docs folder"),
        Task(push_to_local_fork, "Push new tags and branches to private fork"),
        Task(
            send_email_to_platform_release_managers,
            "Platform release managers have been notified of the release artifacts",
        ),
        Task(wait_util_all_files_are_in_folder, "Wait until all files are ready"),
        Task(create_release_object_in_db, "The django release object has been created"),
        Task(post_release_merge, "Merge the tag into the release branch"),
        Task(branch_new_versions, "Branch out new versions and prepare main branch"),
        Task(post_release_tagging, "Final touches for the release"),
        Task(
            maybe_prepare_new_main_branch,
            "prepare new main branch for feature freeze",
        ),
        Task(push_to_upstream, "Push new tags and branches to upstream"),
        Task(remove_temporary_branch, "Removing temporary release branch"),
        Task(run_add_to_python_dot_org, "Add files to python.org download page"),
        Task(purge_the_cdn, "Purge the CDN of python.org/downloads"),
        Task(modify_the_release_to_the_prerelease_pages, "Modify the pre-release page"),
    ]
    automata = ReleaseDriver(
        git_repo=args.repo,
        release_tag=release_mod.Tag(args.release),
        api_key=auth_key,
        ssh_user=args.ssh_user,
        tasks=tasks,
    )
    automata.run()

if __name__ == "__main__":
    main()


"""
This module contains the following classes:
- RedisDoubleHash: Represents a two-way hash map stored in Redis.
"""

from typing import Awaitable, List, Set, Union
# Aliasing this to avoid confusion with the `set` function below.
from builtins import set as builtin_set
from aioredis import Redis
from .redis_model import RedisModel
from .redis_client import RedisClient
from .redis_key import RedisKey
from .redis_set import RedisSet

class RedisDoubleHash(RedisModel):
    """
    Represents a two-way hash map stored in Redis. Each field can be associated with multiple
    values and each value can be associated with multiple fields. The structure allows for
    getting all the values for a field and all the fields for a given value. The values are
    thus referred to as inverted fields. Since this class manages more than one Redis structure,
    some of the methods here are not completely atomic and most of them cannot participate in
    transactions.
    """

    def __init__(
        self,
        redis: Union[Redis, RedisClient],  # pylint:disable=unsubscriptable-object
        key: str, inverse_key: str
    ):
        """
        Creates an instance of `RedisDoubleHash`.

        Args:
            redis (Redis): The Redis instance to use to connect to Redis.
            key (str): The key to use for forward hash map.
            inverse_key (str): The key to use for inverted hash map.
        """

        super().__init__(redis)
        self._key = key
        self._inverse_key = inverse_key

    async def fields(self) -> Awaitable[Set]:
        """
        Gets all the fields in the hash map.

        Returns:
            Awaitable[Set]: The fields in the hash map.
        """

        return builtin_set(
            self._extract_field_name(redis_key, self._key) \
                for redis_key in await self._fields_generic()
        )

    async def fields_inverted(self) -> Awaitable[Set]:
        """
        Gets all the inverted fields (values) in the hash map.

        Returns:
            Awaitable[Set]: The inverted fields (values) in the hash map.
        """

        return builtin_set(
            self._extract_field_name(redis_key, self._inverse_key) \
                for redis_key in await self._fields_generic(inverse=True)
        )

    def get(self, field: str) -> Awaitable[List]:
        """
        Gets the inverted fields associated with the given field.

        Args:
            field (str): The field to get.

        Returns:
            Awaitable[List]: The list of all inverted fields associated with the given field.
        """

        return self._get_field_value(self._key, field)

    def get_inverted(self, field: str) -> Awaitable[List]:
        """
        Gets the fields associated with the given inverted field (value).

        Args:
            field (str): The inverted field to get.

        Returns:
            Awaitable[List]: The list of all fields associated with the given inverted field.
        """

        return self._get_field_value(self._inverse_key, field)

    async def set(self, field: str, value: str):
        """
        Associates the given value with the given field.

        Args:
            field (str): The name of the field.
            value (str): The value to associate.
        """

        if value is None:
            return

        async with self.begin_transaction() as transaction:
            transaction.add_operation(
                self._set_field(self._key, field, value),
                self._set_field(self._inverse_key, value, field)
            )

    async def unset(self, field: str, value: str):
        """
        Dissociates the given value with the given field.

        Args:
            field (str): The name of the field.
            value (str): The name of the value to dissociate.
        """

        if value is None:
            return

        async with self.begin_transaction() as transaction:
            transaction.add_operation(
                self._unset_field(self._key, field, value),
                self._unset_field(self._inverse_key, value, field)
            )

    async def set_inverted(self, field: str, value: str):
        """
        Associates the given value with the inverted field.

        Args:
            field (str): The name of the inverted field.
            value (str): The value to associate.
        """

        if value is None:
            return
        return await self.set(field=value, value=field)

    async def remove(self, field: str):
        """
        Removes the given field from both sides of the hash map.

        Args:
            field (str): The field to remove.
        """

        return await self._remove_generic(self._key, self._inverse_key, field)

    async def remove_inverted(self, field: str):
        """
        Removes the given inverted field from both sides of the hash map.

        Args:
            field (str): The inverted field to remove.
        """

        return await self._remove_generic(self._inverse_key, self._key, field)

    async def delete(self):
        """
        Deletes all mappings from both sides of the hash map.
        """

        all_keys = builtin_set()

        async with self.begin_transaction() as transaction:
            transaction.add_operation(
                self._fields_generic(),
                self._fields_generic(inverse=True)
            )
            transaction.set_result_callback(
                lambda *result: all_keys.update(
                    key for keys in result for key in keys
                )
            )

        async with self.begin_transaction() as transaction:
            transaction.add_operation(*(
                RedisKey(self.get_connection(), key).delete() for key in all_keys
            ))

    def _fields_generic(self, inverse: bool=False) -> Awaitable[List]:
        return self.get_connection().keys(self._get_field_name(
            self._inverse_key if inverse else self._key,
            '*'
        ), encoding='utf-8')

    def _get_field_value(self, key: str, field: str) -> Awaitable[List]:
        sub_set = self._get_redis_set(key, field)
        return sub_set.get_all()

    def _set_field(self, key: str, field: str, value: str):
        sub_set = self._get_redis_set(key, field)
        return sub_set.add(value)

    def _unset_field(self, key: str, field: str, value: str):
        sub_set = self._get_redis_set(key, field)
        return sub_set.remove(value)

    async def _remove_generic(self, key: str, inverse_key: str, field: str):
        sub_set = self._get_redis_set(key, field)
        values = await sub_set.get_all()
        async with self.begin_transaction() as transaction:
            transaction.add_operation(sub_set.delete())
            for value in values:
                value_set = RedisSet(self._redis, self._get_field_name(inverse_key, value))
                transaction.add_operation(value_set.remove(field))

    def _get_redis_set(self, key: str, field: str) -> RedisSet:
        return RedisSet(self._redis, self._get_field_name(key, field))

    @staticmethod
    def _get_field_name(key: str, field: str) -> str:
        return f'{key}:{field}'

    @staticmethod
    def _extract_field_name(redis_key: str, key: str) -> str:
        return redis_key.removeprefix(key + ':')


import re

# Markdown escape code copied from https://github.com/Rapptz/discord.py/blob/master/discord/utils.py

_MARKDOWN_ESCAPE_SUBREGEX = '|'.join(r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(c)
                                     for c in ('*', '`', '_', '~', '|'))

_MARKDOWN_ESCAPE_COMMON = r'^>(?:>>)?\s|\[.+\]\(.+\)'

_MARKDOWN_ESCAPE_REGEX = re.compile(r'(?P<markdown>%s|%s)' % (_MARKDOWN_ESCAPE_SUBREGEX, _MARKDOWN_ESCAPE_COMMON))

def escape_markdown(text, *, as_needed=False, ignore_links=True):
    r"""A helper function that escapes Discord's markdown.

    Parameters
    -----------
    text: :class:`str`
        The text to escape markdown from.
    as_needed: :class:`bool`
        Whether to escape the markdown characters as needed. This
        means that it does not escape extraneous characters if it's
        not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**``
        instead of ``\*\*hello\*\*``. Note however that this can open
        you up to some clever syntax abuse. Defaults to ``False``.
    ignore_links: :class:`bool`
        Whether to leave links alone when escaping markdown. For example,
        if a URL in the text contains characters such as ``_`` then it will
        be left alone. This option is not supported with ``as_needed``.
        Defaults to ``True``.

    Returns
    --------
    :class:`str`
        The text with the markdown special characters escaped with a slash.
    """

    if not as_needed:
        url_regex = r'(?P<url><[^: >]+:\/[^ >]+>|(?:https?|steam):\/\/[^\s<]+[^<.,:;\"\'\]\s])'

        def replacement(match):
            groupdict = match.groupdict()
            is_url = groupdict.get('url')
            if is_url:
                return is_url
            return '\\' + groupdict['markdown']

        regex = r'(?P<markdown>[_\\~|\*`]|%s)' % _MARKDOWN_ESCAPE_COMMON
        if ignore_links:
            regex = '(?:%s|%s)' % (url_regex, regex)
        return re.sub(regex, replacement, text)
    else:
        text = re.sub(r'\\', r'\\\\', text)
        return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text)


mo,h=list(map(str,input().split()))
count=0
for i in range(0,len(mo)):
    if(mo[i]!=h[i]):
        count+=1
if(count==1):
    print("yes")
else:
    print("no")


import datetime
import numpy as np
import pandas as pd
import jobs.JobBase as j
import HexoGenerator

class StocksStatJob(j.JobBase):
    def __init__(self, post_path, stocks_file_path):
        self.post_path = post_path
        self.stocks_file_path = stocks_file_path

    def run(self):
        df = pd.read_csv(self.stocks_file_path)

        self.stat_stocks(df)
        self.generate_post(df)

    def stat_stocks(self, df):
        if 'above_ma42' not in list(df.columns):
            df['above_ma42'] = (df['close'] / df['ma42'] - 1) * 100
            df['above_ma120'] = (df['close'] / df['ma120'] - 1) * 100
            df['above_ma250'] = (df['close'] / df['ma250'] - 1) * 100
            df['above_min10'] = (df['close'] / df['min10'] - 1) * 100
            df['below_max10'] = (df['max10'] / df['close'] - 1) * 100
            df['below_max10_atr'] = (df['max10'] - df['close']) / df['atr10']
            df['peg'] = df['pe'] / df['iop']
            df['ret_r'] = df['ret'].rank(ascending = True, method = 'max', pct=True)
            df['var_r'] = df['var'].rank(ascending = True, method = 'max', pct=True)
            df['mc_r'] = df['mc'].rank(ascending = True, method = 'max', pct=True)
            df['cmc_r'] = df['cmc'].rank(ascending = True, method = 'max', pct=True)
            df['pe_r'] = df['pe'].where(df['pe'] >=0, 100000).rank(ascending = True, method = 'max', pct=True)
            df['peg_r'] = df['peg'].where(((df['pe'] >=0) & (df['iop'] >=0)), 100000).rank(ascending = True, method = 'max', pct=True)
            df['pe_lyr_r'] = df['pe_lyr'].where(df['pe_lyr'] >=0, 100000).rank(ascending = True, method = 'max', pct=True)
            df['pb_r'] = df['pb'].where(df['pb'] >=0, 100000).rank(ascending = True, method = 'max', pct=True)
            df['ps_r'] = df['ps'].where(df['ps'] >=0, 100000).rank(ascending = True, method = 'max', pct=True)
            df['pcf_r'] = df['pcf'].where(df['pcf'] >=0, 100000).rank(ascending = True, method = 'max', pct=True)
            df['roe_r'] = df['roe'].rank(ascending = True, method = 'max', pct=True)
            df['roa_r'] = df['roa'].rank(ascending = True, method = 'max', pct=True)
            df['itr_r'] = df['itr'].rank(ascending = True, method = 'max', pct=True)
            df['ir_r'] = df['ir'].rank(ascending = True, method = 'max', pct=True)
            df['inp_r'] = df['inp'].rank(ascending = True, method = 'max', pct=True)
            df['iop_r'] = df['iop'].rank(ascending = True, method = 'max', pct=True)
            df['inps_r'] = df['inps'].rank(ascending = True, method = 'max', pct=True)
            df['roic_r'] = df['roic'].rank(ascending = True, method = 'max', pct=True)
            df['gpm_r'] = df['gpm'].rank(ascending = True, method = 'max', pct=True)
            df['score'] = df.apply(self.rate_stock, axis=1)
            df['score_r'] = df['score'].rank(ascending = True, method = 'max', pct=True)

            df.set_index('code', inplace=True)
            df.to_csv(self.stocks_file_path, encoding='utf-8')
            df.reset_index(inplace=True)

    def generate_post(self, df):
        blog_generator = HexoGenerator.HexoGenerator(self.post_path, '所有股票多因子排序 - {}'.format(j.JobBase.get_today_str()), tags=['数据统计'])

        df['code'] = df['code'].str.slice(0, 6)
        df.sort_values(by=['score', 'l_slop'], ascending=False, inplace=True)

        df.loc[(df['l_pvalue'] > 0.001) | (df['l_stderror'] > 7), 'l_slop'] = np.nan

        filterd_names = df.loc[(df['close'] > df['ma42']) & (df['l_slop']> 0) & (df['above_min10'] + df['below_max10'] > 5) & (df['above_min10'] < 1), 'name']
        df.loc[(df['close'] > df['ma42']) & (df['l_slop']> 0) & (df['above_min10'] + df['below_max10'] > 5) & (df['above_min10'] < 1), 'name'] = '**' + filterd_names + ' +++**'
        df.loc[(df['var_r'] >= 0.8) , 'name'] = df.loc[(df['var_r'] >= 0.8) , 'name'] + ' ---'

        df.loc[:,'name'] = [blog_generator.get_url_str(name, 'http://finance.sina.com.cn/realstock/company/' + ('sh' if code.startswith('6') else 'sz') + code + '/nc.shtml' )
                                for (code, name) in zip(df['code'], df['name'])]
        df.loc[:,'code'] = df['code'].map(lambda x: blog_generator.get_url_str(x, '/stocks/?code=' + x))
        # df.loc[:,'code'] = df['code'].map(lambda x: blog_generator.get_url_str(x, '/stocks/?code=' + x) + '

')

        df['ret'] = df['ret'] * 100
        blog_generator.data_frame(df[['code', 'name', 'score', 'l_slop', 'ret', 'above_ma42', 'above_ma120', 'above_ma250', 'below_max10_atr', 'pb_r', 'iop_r', 'iop', 'iop_p', 'pe']],
            headers=[
                'Code', 'Name', 'Score', 'Slop', 'Ret', 'MA 42', 'MA 120', 'MA 250', 'ATR', 'PB Rank', 'IOP Rank', 'IOP', 'Prev IOP', 'PE'
            ])

        blog_generator.css('../../lib/stocks/datatables.css')
        blog_generator.js('../../lib/stocks/lodash.js')
        blog_generator.js('../../lib/stocks/all_stocks.js')

        blog_generator.write()

    def rate_stock(self, stock):
        score = 0

        if 0.2 < stock['var_r'] < 0.7:
            score = score + 2

        if stock['pb_r'] < 0.1:
            score = score + 2
        elif stock['pb_r'] < 0.6:
            score = score + 1

        if stock['ps_r'] < 0.4:
            score = score + 1
        elif stock['ps_r'] > 0.9:
            score = score - 1

        if stock['pcf_r'] < 0.6 and stock['pcf'] > 0:
            score = score + 1

        if stock['peg_r'] < 0.4:
            score = score + 1

        if stock['iop_r'] > 0.8:
            score = score + 2
        elif stock['iop_r'] > 0.6:
            score = score + 1

        if stock['roe_r'] > 0.9:
            score = score + 1.5
        elif stock['roe_r'] > 0.5:
            score = score + 1

        if 0.4 < stock['roic_r'] < 0.8:
            score = score + 1.5

        if stock['gpm_r'] > 0.5:
            score = score + 1

        return score


class Pol:
    def __init__(self,co:list):
        self.co=co

    def __len__(self):
        return len(self.co)

    def __getitem__(self, item):
        return self.co[item]
    def __setitem__(self, key, value):
        self.co[key]=value
    def __str__(self):
        return ",".join([str(x) for x in self.co])

    def str(self,x:str="x"):
        re=''
        for i in range(len(self)-1):
            if self[i]!=0:
                if self[i]>0:
                    re+='+'
                re+=str(self[i]) + x + '^' + str(len(self) - i - 1)
        if self[-1]>0:
            re+="+"+str(self[-1])
        elif self[-1]<0:
            re += str(self[-1])
        return re

    def adjust_co(self, other):
        self.co=[0]*(len(other)-len(self))+self.co
        other.co=[0]*(len(self)-len(other))+other.co
        return self,other

    def __add__(self, other):
        l1,l2=self.adjust_co(other)
        result = Pol([0] * len(l1))
        for i in range(len(l1)):
            result[i]=l1[i]+l2[i]
        return result

    def __sub__(self,other):
        l1, l2 = self.adjust_co(other)
        result = Pol([0] * len(l1))
        for i in range(len(l1)):
            result[i] = l1[i] - l2[i]
        return result

    def __mul__(self, other):
        if not isinstance(other,Pol):
            other2=Pol([other])
        else:
            other2=other
        if not isinstance(self,Pol):
            other2=Pol([self])
        result=Pol([0]*(len(self)+len(other2)))
        for i in range(len(self)):
            for i2 in range(len(other2)):
                result[-(i+i2+1)]+=self[-(i+1)]*other2[-(i2+1)]
        return result

    def div(self, other,result=[],remainder=[]):
        self_=Pol(self.co)
        if result==[]:
            global z
            z=len(self_)
        if len(self_)>=len(other):
            r=self_[0]/other[0]
            subtracted=Pol(remov_((other*Pol([r])).co))
            if len(self_)-len(other)>0:
                subtracted.co = subtracted.co + [0] * (len(self_) - len(other))
                result+=[0]*(len(self_) - len(other))
            if len(subtracted)<len(self_):
                subtracted.co=subtracted.co+[0]*(len(self_)-len(subtracted))
            self_=Pol(remov_((self-subtracted).co))
            result.append(r)

        else:
            remainder=self_
            result = remov_(result)
            if len(result) <= (z - len(other)):
                z2 = z+1 - (len(other) + len(result))
                result+=[0]*z2
            if remainder==[]:
                return Pol(result)
            return (Pol(result), remainder)
        return self_.div(other,result)

    def __truediv__(self, other):
        return self.div(other)

    def evaluate(self,x=1):
        result=0
        for (k,v) in enumerate(reversed(self.co)):
            result+=v*x**(k)
        return result
    def diff(self,value=None):
        result = []
        for (k, v) in enumerate(reversed(self.co)):
            result.append(v * k)
        if value==None:
            return Pol(list(reversed(result))[:-1])
        else:
            return Pol(list(reversed(result))[:-1]).evaluate(value)

    def integral(self,to=None,from_=0):
        result = [0]
        for (k, v) in enumerate(reversed(self.co)):
            result.append(v / (k+1))
        if to == None:
            return Pol(list(reversed(result)))
        else:
            return Pol(list(reversed(result))).evaluate(to)-Pol(list(reversed(result))).evaluate(from_)

a=Pol([1,0,-5])
b=(a*a).diff()
print(a)


import sys
from collections import defaultdict
import re

lines = sys.stdin.readlines()

mol = "CRnCaCaCaSiRnBPTiMgArSiRnSiRnMgArSiRnCaFArTiTiBSiThFYCaFArCaCaSiThCaPBSiThSiThCaCaPTiRnPBSiThRnFArArCaCaSiThCaSiThSiRnMgArCaPTiBPRnFArSiThCaSiRnFArBCaSiRnCaPRnFArPMgYCaFArCaPTiTiTiBPBSiThCaPTiBPBSiRnFArBPBSiRnCaFArBPRnSiRnFArRnSiRnBFArCaFArCaCaCaSiThSiThCaCaPBPTiTiRnFArCaPTiBSiAlArPBCaCaCaCaCaSiRnMgArCaSiThFArThCaSiThCaSiRnCaFYCaSiRnFYFArFArCaSiRnFYFArCaSiRnBPMgArSiThPRnFArCaSiRnFArTiRnSiRnFYFArCaSiRnBFArCaSiRnTiMgArSiThCaSiThCaFArPRnFArSiRnFArTiTiTiTiBCaCaSiRnCaCaFYFArSiThCaPTiBPTiBCaSiThSiRnMgArCaF"

def applyRule(rule, mol):
    blah = set()
    for (res) in re.finditer(rule[0], mol):
        news = mol[:res.start()] + rule[1].strip() + mol[res.end():]
        #print(news)
        blah.add(news)
    return blah

def applyBackward(right, left, mol):
    return mol.replace(right, left)

backrules = defaultdict(list)
onestep = set()
count = 0

for line in lines:
    rule = line.split(' => ')
    backrules[rule[1].strip()] = rule[0].strip()

while 'Ca' in mol:
    for r in backrules.keys():
        if 'Ca' in r and r in mol:
            mol = applyBackward(r, backrules[r], mol)
            count += 1
print("No ca ", mol)
ArRules = ['SiRnFAr', 'CRnMgAr', 'NRnMgAr', 'ThRnFAr', 'TiRnFAr', 'CRnMgYFAr', 'CRnAlAr',
'CRnFYFAr', 'CRnFYFYFAr', 'CRnFYMgAr', 'NRnFYFAr', 'ORnFAr', 'CRnFAr', 'CRnMgAr', 'NRnFAr']

print(ArRules)

startcount = 0
while startcount != count:
    startcount = count
    for r in ArRules:
        if r in mol:
            mol = applyBackward(r, backrules[r], mol)
            print(mol)
            count += 1

print('count' , count)
print(mol)
#print(len(onestep))


import bpy, bmesh
obj = bpy.context.active_object

if obj.mode == 'EDIT':
    bm = bmesh.from_edit_mesh(obj.data)
    vertices = bm.verts

else:
    vertices = obj.data.vertices

print(obj)
verts = [obj.matrix_world @ vert.co for vert in vertices]

# coordinates as tuples
plain_verts = [vert.to_tuple() for vert in verts]
print(len(plain_verts))


'''
__author__: Federico Pretini
'''
from PyQt5.QtWidgets import QMainWindow, QTableWidgetItem, QMessageBox
from PyQt5 import QtGui, QtCore

from bar.view.Ui_AggiornaListinoView import Ui_AggiornaListinoView

class AggiornaListinoView(QMainWindow, Ui_AggiornaListinoView):
    def __init__(self, log, controller, callback, parent=None):
        super(AggiornaListinoView, self).__init__(parent)
        self.setupUi(self)
        self.log = log
        self.controller = controller
        self.callback = callback
        self.listino_bar=[]
        self.update_tableBar()
        self.update_cB_categoria()
        self.connect_all()

    def connect_all(self):
        self.pB_aggiungi.clicked.connect(lambda: self.aggiungi_consumazione())
        self.pB_elimina.clicked.connect(lambda: self.elimina_consumazione())
        self.pB_annulla.clicked.connect(lambda: self.annulla_consumazione())
        self.tableWidget_ListinoBar.itemSelectionChanged.connect(lambda: self.table_selected())

    def update_listinoBar(self):
        self.controller.update_liste()
        self.listino_bar = [self.controller.get_lista_alcolici(), self.controller.get_lista_analcolici(), self.controller.get_lista_bibite(),
                            self.controller.get_lista_caffetteria(), self.controller.get_lista_aperitivi(), self.controller.get_lista_vini(),
                            self.controller.get_lista_liquori(), self.controller.get_lista_pasticceria()]

    def update_tableBar(self):
        def get_item(info):
            item = QTableWidgetItem(str(info))
            font = QtGui.QFont()
            font.setBold(False)
            font.setFamily("Arial")
            font.setPointSize(12)
            item.setFont(font)
            item.setTextAlignment(QtCore.Qt.AlignCenter)
            return item

        self.update_listinoBar()
        self.tableWidget_ListinoBar.setRowCount(0)
        self.listino_bar.reverse()  #Aggiorna la tabella a partire dagli alcolici
        for categoria in self.listino_bar:
            i = 0
            for consumazione in categoria:
                self.tableWidget_ListinoBar.insertRow(i)
                j = 0
                for info in consumazione:
                    self.tableWidget_ListinoBar.setItem(i,j, get_item(info))
                    j+=1
                i+=1

    def update_cB_categoria(self):
        lista_categoria = set([""]) #Utlizzo il tipo set che non può avere duplicati al suo interno
        for categoria in self.listino_bar:
            for consumazione in categoria:
                lista_categoria.add(consumazione[1])
        self.cB_categoria.addItems(lista_categoria)

    def table_selected(self):
        if len(self.tableWidget_ListinoBar.selectionModel().selectedRows()) > 0:
            self.pB_elimina.setEnabled(True)
        else:
            self.pB_elimina.setEnabled(False)

    def aggiungi_consumazione(self):
        nome_consumazione = self.lineE_nome.text()
        categoria = self.cB_categoria.currentText()
        prezzo = self.spinB_prezzo.value()
        if nome_consumazione == "" or categoria == "" or prezzo == 0:
            QMessageBox.critical(self, "Errore", "Inserisci tutti i dati richiesti prima di premere aggiungi")
            return
        self.controller.aggiungi_consumazione([nome_consumazione, categoria, prezzo])
        self.log.print_log_add("aggiunta consumazione bar")
        self.callback() #Aggiorna le comboBox sull'altra interfaccia
        self.update_tableBar() #Aggiorna la lista della mio listino bar
        self.annulla_consumazione()

    def elimina_consumazione(self):
        item = self.tableWidget_ListinoBar.selectedItems()
        lista_nomi = []
        contatore = 0
        for info in item:
            if contatore%3 == 0:
              lista_nomi.append(info.text())
            contatore+=1
        self.controller.elimina_consumazione(lista_nomi)
        self.log.print_log_delete("eliminata consumazione bar")
        self.callback()
        self.update_tableBar()

    def annulla_consumazione(self):
        self.cB_categoria.setCurrentIndex(0)
        self.lineE_nome.clear()
        self.spinB_prezzo.setValue(0)


import torch
import torchvision
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms

model = torchvision.models.segmentation.deeplabv3_resnet101(pretrained=True)
model.eval()

# get image from the data-animalpose/images/train/ directory
image = Image.open('../output/cropped_3_0.jpg')

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

# Convert cropped_image to a PyTorch tensor and normalize
input_tensor = transform(image)
input_tensor = input_tensor.unsqueeze(0)

output = model(input_tensor)['out']

# Convert output to a binary mask (assuming the animal class is 1)
mask = torch.argmax(output, dim=1) == 1
foreground = input_tensor * mask.numpy()

# Save the cropped image
plt.imsave('test.jpg', foreground)
# save the output
plt.imsave('output.jpg', output[0, 1, :, :].detach().numpy())


#Imports
from my_package.model import ObjectDetectionModel
from my_package.data import Dataset
from my_package.analysis.visualize import plot_boxes
from my_package.data.transforms import FlipImage, RescaleImage, BlurImage, CropImage, RotateImage
from PIL import Image
def experiment(annotation_file, detector, transforms, outputs):
    '''
        Function to perform the desired experiments

        Arguments:
        annotation_file: Path to annotation file
        detector: The object detector
        transforms: List of transformation classes
        outputs: path of the output folder to store the images
    '''

    #Create the instance of the dataset.
    data_set=Dataset(annotation_file,[])

    #Iterate over all data items.
    l=len(data_set)
    for i in range(len(data_set)):
        img=data_set[i]["image"]
        var=detector(img)
        plot_boxes(img,var,outputs+str(i)+".png")

    #Get the predictions from the detector.
    #done above

    #Draw the boxes on the image and save them.
    #done above

    #Do the required analysis experiments.
    an_op_filepath = "analytics_output/"

    img=data_set[9]['image']
    var=detector(img)
    plot_boxes(img,var,an_op_filepath+"original.png")

    data_set = Dataset(annotation_file,[FlipImage('horizontal')])

    img =data_set[9]['image']
    var=detector(img)
    plot_boxes(img,var,an_op_filepath+"flip_horizontal.png")

    data_set= Dataset(annotation_file,[BlurImage(2)])

    img=data_set[9]['image']
    var=detector(img)
    plot_boxes(img,var,an_op_filepath+"blurred.png")

    data_set= Dataset(annotation_file,[RescaleImage([2*img.shape[2],2*img.shape[1]])])

    img=data_set[9]['image']
    var=detector(img)
    plot_boxes(img,var,an_op_filepath+"twicex.png")
    shape = [round(0.5*img.shape[2]),round(0.5*img.shape[1])]

    data_set= Dataset(annotation_file,[RescaleImage(shape)])

    img=data_set[9]['image']
    var=detector(img)
    plot_boxes(img,var,an_op_filepath+"halfx.png")

    data_set= Dataset(annotation_file,[RotateImage(270)])

    img=data_set[9]['image']
    var=detector(img)
    plot_boxes(img,var,an_op_filepath+"90degreeright.png")

    data_set= Dataset(annotation_file,[RotateImage(45)])

    img=data_set[9]['image']
    var=detector(img)
    plot_boxes(img,var,an_op_filepath+"45degreeleft.png")

def main():
    detector = ObjectDetectionModel()
    experiment('./data/annotations.jsonl', detector, [FlipImage(), BlurImage()],"./output_imgs/") # Sample arguments to call experiment()

if __name__ == '__main__':
    main()


#
# Utility to unpack all data from old data structure.
# Data structure as:
#   e.g.,   completed/2-1/1/info/1-info.out
#           completed/2-1/1/input/1-big.in
#           completed/2-1/1/planets/1/planet1.aei
#

import os
import argparse
import shutil
import re

parser = argparse.ArgumentParser()
parser.add_argument('--completed_old', '-old',
                    action='store',
                    dest='path_old')
parser.add_argument('--completed_new', '-new',
                    action='store',
                    dest='path_new')
parser.add_argument('--resonance', '-res',
                    action='store',
                    dest='res_str_old')
args = parser.parse_args()

path_old = args.path_old
path_new = args.path_new
resonance =  args.res_str_old
res_str_old = '-'.join((resonance[0], resonance[-1]))
res_str_new = ''.join((resonance[0], resonance[-1]))
three_dirs = ['info', 'input', 'planets']

os.mkdir(path_new)
if not os.path.exists('{}/{}'.format(path_new, res_str_new)):
    os.mkdir('{}/{}'.format(path_new, res_str_new))
    for _dir in three_dirs:
        os.mkdir('{}/{}/{}'.format(path_new, res_str_new, _dir))

res_dirs = [d for d in os.listdir('{}/{}'.format(path_old, res_str_old)) if re.match('^[0-9]+$', d)]
for res_dir in res_dirs:
    print(res_dir)
    N_old = len(os.listdir('{}/{}/{}/info/'.format(path_old, res_str_old, res_dir)))
    N_new = len(os.listdir('{}/{}/info/'.format(path_new, res_str_new)))
    for n in range(1, N_old+1):
        shutil.copy('{}/{}/{}/info/{}-info.out'.format(path_old, res_str_old, res_dir, n),
                '{}/{}/info/{}-info.out'.format(path_new, res_str_new, N_new))
        shutil.copy('{}/{}/{}/input/{}-big.in'.format(path_old, res_str_old, res_dir, n),
                '{}/{}/input/{}-big.in'.format(path_new, res_str_new, N_new))
        try:
            shutil.copy('{}/{}/{}/planets/{}/planet1.aei'.format(path_old, res_str_old, res_dir, n),
                    '{}/{}/planets/{}-planet1.aei'.format(path_new, res_str_new, N_new))
        except FileNotFoundError:
            open('{}/{}/planets/{}-planet1_empty.aei'.format(path_new, res_str_new, N_new), 'a').close()
        try:
            shutil.copy('{}/{}/{}/planets/{}/planet2.aei'.format(path_old, res_str_old, res_dir, n),
                '{}/{}/planets/{}-planet2.aei'.format(path_new, res_str_new, N_new))
        except FileNotFoundError:
            open('{}/{}/planets/{}-planet2_empty.aei'.format(path_new, res_str_new, N_new), 'a').close()

        N_new += 1


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import csv
import networkx as nx
import random
import argparse
from utilities import helper as h
import pprint
import os
import glob
import time
import random
from scipy import stats
import seaborn as sns
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

def plot_pull_residual(pull_data, labels, truth, axis_lims, bins, bw):
    sns.set()
    for p, l, a, b, w in zip(pull_data, labels, axis_lims, bins, bw):
        df = pd.DataFrame({l: p, 'truth': truth})
        correct = df.loc[df['truth'] == 1]
        incorrect = df.loc[df['truth'] == 0]

        # plot histogram
        fig, ax1 = plt.subplots(figsize=(8, 6))
        sns.distplot(correct[l], hist=True, kde=False, bins=b, ax=ax1, color="orange", norm_hist=False,
                            hist_kws={"lw":2, "label": "truth 1"})
        ax2 = ax1.twinx()
        sns.distplot(correct[l], hist=False, kde=True, ax=ax2, color="orange",
                            kde_kws={"lw": 2, "label": "KDE bw: " + str(w), "clip": a, "bw_adjust": w})

        ax1.set_ylabel("Frequency")
        ax2.set_ylabel("PDF")
        ax1.grid(False)
        ax2.grid(False)
        plt.xlim(a)

        # combine legends
        h1, l1 = ax1.get_legend_handles_labels()
        h2, l2 = ax2.get_legend_handles_labels()
        ax1.legend(h1+h2, l1+l2, loc=2)

        # FWHM
        kde_curve = ax2.lines[0]
        x = kde_curve.get_xdata()
        y = kde_curve.get_ydata()
        halfmax = y.max() / 2
        maxpos = y.argmax()
        leftpos = (np.abs(y[:maxpos] - halfmax)).argmin()
        rightpos = (np.abs(y[maxpos:] - halfmax)).argmin() + maxpos
        fullwidthathalfmax = x[rightpos] - x[leftpos]
        ax2.hlines(halfmax, x[leftpos], x[rightpos], color='purple', ls=':')
        ax2.text(x[maxpos], halfmax, f'{fullwidthathalfmax:.3f}\n', color='purple', ha='center', va='center')

        plt.title('Stage 1: Pull residual for parameter ' + l)
        plt.show()

def main():

    parser = argparse.ArgumentParser(description='Convert trackml csv to GNN')
    parser.add_argument('-i', '--inputDir', help="Full directory path of graph networks")
    args = parser.parse_args()
    inputDir = args.inputDir

    # read in subgraph data
    subGraphs = []
    i = 0
    subgraph_path = "_subgraph.gpickle"
    path = inputDir + str(i) + subgraph_path
    while os.path.isfile(path):
        sub = nx.read_gpickle(path)
        subGraphs.append(sub)
        i += 1
        path = inputDir + str(i) + subgraph_path

    # extract the state and covariance metadata
    truth = []
    pull_a, pull_b = [], []
    pull_c, pull_tau = [], []
    pull_theta_1, pull_theta_2 = [], []
    for i, subGraph in enumerate(subGraphs):
        num_nodes = len(subGraph.nodes())

        if num_nodes > 1:
            for node in subGraph.nodes(data=True):
                node_num = node[0]
                node_attr = node[1]

                track_state_estimates = node_attr["track_state_estimates"]
                node_keys = list(track_state_estimates.keys())
                for j in range(len(track_state_estimates) - 1):
                    for k in range(j):
                        if j == k: continue

                        n1, n2 = node_keys[j], node_keys[k]
                        sv1 = track_state_estimates[n1]["edge_state_vector"]
                        cov1 = track_state_estimates[n1]["edge_covariance"]
                        sv2 = track_state_estimates[n2]["edge_state_vector"]
                        cov2 = track_state_estimates[n2]["edge_covariance"]

                        jv1 = np.array(track_state_estimates[n1]["joint_vector"])
                        jcov1 = track_state_estimates[n1]["joint_vector_covariance"]
                        jv2 = np.array(track_state_estimates[n2]["joint_vector"])
                        jcov2 = track_state_estimates[n2]["joint_vector_covariance"]

                        theta_1 = track_state_estimates[n1]["theta"]
                        theta2_1 = track_state_estimates[n1]["theta2"]
                        var_theta_1 = track_state_estimates[n1]["variance_theta"]

                        theta_2 = track_state_estimates[n2]["theta"]
                        theta2_2 = track_state_estimates[n2]["theta2"]
                        var_theta_2 = track_state_estimates[n2]["variance_theta"]

                        # calculate the pull residuals
                        diffs = sv1 - sv2
                        sum_cov = cov1 + cov2
                        jdiffs = jv1 - jv2
                        jsum_cov = jcov1 + jcov2

                        pa = diffs[0] / np.sqrt(sum_cov[0][0])
                        pb = diffs[1] / np.sqrt(sum_cov[1][1])
                        pc = diffs[2] / np.sqrt(sum_cov[2][2])
                        ptau = jdiffs[2] / np.sqrt(jsum_cov[2][2])

                        pull_a.append(pa)
                        pull_b.append(pb)
                        pull_c.append(pc)
                        pull_tau.append(ptau)

                        diff_theta_1 = theta_1 - theta_2
                        diff_theta_2 = theta2_1 - theta2_2
                        sum_cov_theta = var_theta_1 + var_theta_2
                        ptheta_1 = diff_theta_1 / np.sqrt(sum_cov_theta)
                        ptheta_2 = diff_theta_2 / np.sqrt(sum_cov_theta)
                        pull_theta_1.append(ptheta_1)
                        pull_theta_2.append(ptheta_2)

                        # store MC truth
                        t1 = subGraph.nodes[node_num]["truth_particle"]
                        t2 = subGraph.nodes[n1]["truth_particle"]
                        t3 = subGraph.nodes[n2]["truth_particle"]
                        if (t1 == t2) and (t2 == t3) and (t1 == t3): truth.append(1)
                        else: truth.append(0)

    # # pull residuals for [a, b, tau]
    # pull_data = [np.array(pull_a), np.array(pull_b), np.array(pull_tau)]
    # labels = ["a", "b", "tau"]
    # axis_lims = [(-0.25, 0.25), (-0.5, 0.5), (-50, 50)]
    # bins = [5000, 5000, 10000]
    # bw = [0.05, 0.05, 0.001]
    # plot_pull_residual(pull_data, labels, truth, axis_lims, bins, bw)

    # # pull residuals for theta
    pull_data = [np.array(pull_theta_1), np.array(pull_theta_2)]
    labels = ["theta1", "theta2"]
    axis_lims = [(-1000, 1000), (-1000, 1000)]
    bins = [5000, 10000]
    bw = [0.01, 0.01]
    plot_pull_residual(pull_data, labels, truth, axis_lims, bins, bw)

if __name__ == "__main__":
    main()


#root.val = min(root.right.val,root.left.val) is been followed
def findSecondMinimumValue(self, root) -> int:
        self.ans = float('inf')
        first_minimum = root.val
        def ordering(root):
            if(root):
                if(first_minimum<root.val<self.ans):
                    self.ans = root.val
                ordering(root.left)
                ordering(root.right)
        ordering(root)

        return self.ans if self.ans < float('inf') else -1

Trees/finding second minimum element in a BT.py


#! /usr/bin/python

import rospy
import configparser
import time
import os
from tqdm import tqdm

from models.ros import UAV
from models import Environment
from tools import utils

import warnings
from sklearn.exceptions import ConvergenceWarning

def main():
    # Initializing ROS node.
    rospy.init_node("drone_controller" + rospy.get_namespace().replace('/', ''), anonymous=True)

    # Example usage
    size = 50
    grid_resolution = 1
    drone_count = 8
    formation_pattern = "circle"
    # weed_centers = [[-size/4, size/4], [size/4, -size/4]]
    # weed_centers = [[-15, 15], [10, -10]]
    # weed_centers = [[-8, -15], [15, 15]] # 16 Drones
    weed_centers = [[-8, -5], [20, 22]] # 8 Drones
    weed_cov = [[5, 0], [0, 5]]
    iterations = 10
    sampling_time = 30
    disable_warnings = True

    if disable_warnings:
        warnings.filterwarnings("ignore", category=ConvergenceWarning)

    planner_config = {
        # "reordermode": "SpiralOutward", # Doesen't Work. Need more proper TSP solver, planning
        # "reordermode": "SpiralOutSimple",
        # "reordermode":"NearestNeighbor",
        # "reordermode": "SpiralOutA*",
        "reordermode": None,
        "formation_pattern": formation_pattern
    }

    estimator_config = {
        # "weigh_uncertainity":"individually",
        # "weigh_uncertainity":"partitionwise",
        "weigh_uncertainity":None,

        # "name": "Particle Filter",
        # "num_particles":2000,
        # "temperature": 1.0,
        # "cooling": 0.99,

        "name": "GPR",
        "kernel": "C(1.0, (1e-2, 1e2)) * RBF(10, (1e-2, 1e2))"
    }

    EXPERIMENT_LOGGING_DIR = '/home/invisible23man/Robotics/Simulations/decentralised-adaptive-coverage-with-voronoi-partitioning/src/decentralised_adaptive_coverage/outputs/experiment_logging_ros'
    EXPERIMENT_TIMESTAMP = ''
    EXPERIMENT_FILTERTAG = f's-{sampling_time}-it{iterations}-{utils.generate_experiment_tag(estimator_config)}'
    EXPERIMENT_FILENAME = os.path.join(EXPERIMENT_LOGGING_DIR,EXPERIMENT_TIMESTAMP,
                                       f'{EXPERIMENT_FILTERTAG}-data.pkl')
    ANIMATION2D_FILENAME = os.path.join(EXPERIMENT_LOGGING_DIR,EXPERIMENT_TIMESTAMP,
                                        f'{EXPERIMENT_FILTERTAG}-animation2d.gif')
    ANIMATION3D_FILENAME = os.path.join(EXPERIMENT_LOGGING_DIR,EXPERIMENT_TIMESTAMP,
                                        f'{EXPERIMENT_FILTERTAG}-animation3d.gif')

    field = Environment.Field(size, grid_resolution, drone_count, formation_pattern, weed_centers, weed_cov, sampling_time)
    # field.plot_field()

    # Initlialize the Drone
    drone = UAV.Drone(field, planner_config, estimator_config)

    # while not rospy.is_shutdown():
    for iteration in tqdm(range(iterations)):
        rospy.loginfo(f"\nIteration {iteration+1}, Drone {drone.drone_id+1}")

        drone.initialize_iteration(iteration)
        drone.compute_voronoi(plot=False)
        drone.plan(plot=False)

        if len(drone.lawnmower_path) == 0:
            drone.voronoi_center_tracker.append(drone.voronoi_center)
            drone.measurements = []
            drone.publisher.publish_payload(drone.voronoi_center)
            continue

        # rospy.loginfo(f"Started movement and sensing:drone{drone.id}, iter:{iteration}")
        drone.sense()

        drone.estimate()

        # rospy.loginfo(f"Calculating New Center:drone{drone.drone_id}, iter:{i}")
        drone.update_voronoi()

        drone.service.wait_for_update_voronoi_for_all_drones()
        field.update_drone_positions(drone.drone_positions)

    # if drone.enable_physics_simulation:
    #     drone.drone.land()

    # Save data
    if drone.drone_id == 0:
        field.save_data(EXPERIMENT_FILENAME)

        field.animate_field_2d(plot_voronoi=True, filename=ANIMATION2D_FILENAME)
        field.animate_field_3d(plot_voronoi=True, filename=ANIMATION3D_FILENAME)

    # # Add a delay before shutdown to ensure that all service calls have been made
    # rospy.sleep(10)

    # rospy.signal_shutdown(reason="Completed Run")
    rospy.loginfo(f"{drone.drone_id} completed run.")
    # while True:
        # rospy.sleep(1)

if __name__ == '__main__':
    try:
        main()
    except rospy.ROSException:
        print("Service not available after waiting for 5 seconds.")
    except KeyboardInterrupt:
        exit()


from django.shortcuts import render
from rest_framework.response import Response
from .models import *
from .serializers import *
from rest_framework.decorators import api_view
# Create your views here.

@api_view(['GET'])
def getcontactus(request):
    obj = contact_us.objects.all()
    print(obj)
    objser = ContactSerializers(obj,many=True)
    return Response(objser.data)

@api_view(['GET'])
def getaboutus(request):
    obj = about_us.objects.all()
    print(obj)
    objser = AboutSerializers(obj,many=True)
    return Response(objser.data)

@api_view(['GET'])
def getservice_sub_category(request):
    obj = service_sub_category.objects.all()
    print(obj)
    objser = Service_sub_categorySerializers(obj,many=True)
    return Response(objser.data)

@api_view(['GET'])
def getservice_category(request):
    obj = service_category.objects.all()
    print(obj)
    objser = Service_categorySerializers(obj,many=True)
    return Response(objser.data)

@api_view(['GET'])
def gettestimonials(request):
    obj = testimonials.objects.all()
    print(obj)
    objser = TestimonialsSerializers(obj,many=True)
    return Response(objser.data)

@api_view(['GET'])
def getfeedback(request):
    obj = feedback.objects.all()
    print(obj)
    objser = FeedbackSerializers(obj,many=True)
    return Response(objser.data)

@api_view(['GET'])
def getteam(request):
    obj = team.objects.all()
    print(obj)
    objser = FeedbackSerializers(obj,many=True)
    return Response(objser.data)


import tkinter as tk
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.neural_network import MLPClassifier

models = [('LogReg', LogisticRegression(solver='lbfgs', max_iter=1000)),
          ('SVM', SVC()),
          ('DecTree', DecisionTreeClassifier()),
          ('KNN', KNeighborsClassifier(n_neighbors=15)),
          ('LinDisc', LinearDiscriminantAnalysis()),
          ('MLPC', MLPClassifier(activation='relu', solver='adam', max_iter=500))
         ]
features = ['RMS', 'MAV', 'IAV', 'VAR', 'WL', 'MF', 'PF', 'MP', 'TP', 'SM']

def on_select():
    subject = subject_var.get()
    exercise = exercise_var.get()
    print("Selected Subject: ", subject)
    print("Selected Exercise: ", exercise)
    selected_models = [model[0] for model in models if model[0] in [var.get() for var in model_vars]]
    selected_features = [var.get() for var in feature_vars if var.get()]
    print("Selected Models: ", selected_models)
    print("Selected Features: ", selected_features)
    message = tk.Label(root, text="Dataset Selected", fg="green")
    message.grid(row=4, column=3, columnspan=2)

def display_text():
    message2 = tk.Label(root, text="Dataset Selected", fg="green")
    message2.grid(row=0, column=7, columnspan=2)

root = tk.Tk()
root.title("Subject and Exercise Selector")

subject_var = tk.IntVar(value=1)
exercise_var = tk.IntVar(value=1)
find_best_var = tk.StringVar(value="features")

subject_label = tk.Label(root, text="Select Subject:")
subject_label.grid(row=0, column=0)

subject_menu = tk.OptionMenu(root, subject_var, *range(1, 11))
subject_menu.grid(row=0, column=1)

exercise_label = tk.Label(root, text="Select Exercise:")
exercise_label.grid(row=1, column=0)

exercise_menu = tk.OptionMenu(root, exercise_var, *range(1, 4))
exercise_menu.grid(row=1, column=1)

select_button = tk.Button(root, text="Select", command=on_select)
select_button.grid(row=2, column=0, columnspan=2)

model_frame = tk.LabelFrame(root, text="Select Models")
model_frame.grid(row=0, column=2, rowspan=3)

model_vars = [tk.StringVar() for _ in range(len(models))]
for var in model_vars:
    var.set(False)
for i, (name, model) in enumerate(models):
    tk.Checkbutton(model_frame, text=name, variable=model_vars[i]).pack()

feature_frame = tk.LabelFrame(root, text="Select Features")
feature_frame.grid(row=4, column=2, columnspan=2)

feature_vars = [tk.StringVar() for _ in range(len(features))]
for var in feature_vars:
    var.set(False)
for i, feature in enumerate(features):
    tk.Checkbutton(feature_frame, text=feature, variable=feature_vars[i]).pack()

find_best_frame = tk.LabelFrame(root, text="Find Best")
find_best_frame.grid(row=0, column=4, columnspan=2)

tk.Radiobutton(find_best_frame, text="Features", variable=find_best_var, value="features").pack()
tk.Radiobutton(find_best_frame, text="Model", variable=find_best_var, value="model").pack()
tk.Radiobutton(find_best_frame, text="Features and Model", variable=find_best_var, value="features and model").pack()

root.mainloop()


from google.cloud import bigquery
# import os
client = bigquery.Client()

# query = (
#     "SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` "
#     'WHERE state = "TX" '
#     "LIMIT 100"
# )

query = (
    'SELECT tags, title, id FROM `bigquery-public-data.stackoverflow.stackoverflow_posts` '
    'WHERE tags LIKE "%java"'
    'LIMIT 10'
)

query_job = client.query(
    query,
    # Location must match that of the dataset(s) referenced in the query.
    location="US",
)  # API request - starts the query

for row in query_job:  # API request - fetches results
    # Row values can be accessed by field name or index
    # assert row[0] == row.name == row["name"]
    print(row['title'])
    print(row['id'])
    print(row['tags'])
    # print('')
    # print('')


import pygame
import Button
import os

class Question:
    def __init__(self,gameDisplay,screenWidth,screenHeight):
        #kleuren
        self.colorRed = (255,00,00)
        self.colorBlack = (00,00,00)

        #vars om te kaart te tonen
        self.currentRedCard = 0
        self.currentGreenCard = 0
        self.currentBlueCard = 0
        self.currentYellowCard = 0
        self.currentQuestion = None
        self.questionAwnser = None
        self.questionAsked = False
        self.playerAnswer = None
        self.question = ''
        self.awnser = ''
        self.correctAnswer = ""
        self.screenWidth = screenWidth
        self.screenHeight = screenHeight
        self.gameDisplay = gameDisplay
        #button instants
        self.Button = Button.Button
        #postions bepalen van de buttons om de image
        self.questionButtonWidth = 750 #button code same as in controller
        self.questionButtonHeight = 25

        self.buttonSize = (self.questionButtonWidth,self.questionButtonHeight)

        self.x_postionButton1 = ((self.screenWidth / 100) * 25)
        self.y_postionButton1 = ((self.screenHeight / 100) * 25) + 28

        self.x_postionButton2 = ((self.screenWidth / 100) * 25)
        self.y_postionButton2 = ((self.screenHeight / 100) * 25)  + 52

        self.x_postionButton3 = ((self.screenWidth / 100) * 25)
        self.y_postionButton3 = ((self.screenHeight / 100) * 25) + 79

        self. x_postionButton4 = ((self.screenWidth / 100) * 25)
        self.y_postionButton4 = ((self.screenHeight / 100) * 25) + 100
    def SetQuestion(self,category):

        if category == 'blue': #if player is on a blue space
            path = 'img/cards/blue'
            amountOfBlueCards = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
            blueCards = [f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]
            if amountOfBlueCards == self.currentBlueCard: # if all blue cards are used
                self.currentBlueCard = 0
                self.currentQuestion =  'img/cards/blue/' + blueCards[self.currentBlueCard]
                self.questionAwnser = blueCards[self.currentBlueCard] # zorgt dat de kaarten niet opraken tijdens het testen
                self.currentBlueCard += 1
                #return False # als de kaarten op zijn
            else:
                self.currentQuestion =  'img/cards/blue/' + blueCards[self.currentBlueCard]
                self.questionAwnser = blueCards[self.currentBlueCard]
                self.currentBlueCard += 1 #the next time on starts on a blue space it will have the next question
        elif category == 'red': #if player is on a red space
            path = 'img/cards/red'
            amountOfRedCards = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
            redCards =[f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]
            if amountOfRedCards == self.currentRedCard: #if player is on a red space
                self.currentRedCard = 0
                self.currentQuestion = 'img/cards/red/' + redCards[self.currentRedCard] # zorgt dat de kaarten niet opraken tijdens het testen
                self.questionAwnser = redCards[self.currentRedCard]
                self.currentRedCard += 1
                #return False # als de kaarten op zijn
            else:
                self.currentQuestion = 'img/cards/red/' + redCards[self.currentRedCard]
                self.questionAwnser = redCards[self.currentRedCard]
                self.currentRedCard += 1 #the next time on starts on a red space it will have the next question
        elif category == 'yellow': #if player is on a yellow space
            path = 'img/cards/yellow'
            amountOfYellowCards = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
            yellowCards =[f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]
            if amountOfYellowCards == self.currentYellowCard: #if player is on a yellow space
                self.currentYellowCard = 0
                self.currentQuestion = 'img/cards/yellow/' + yellowCards[self.currentYellowCard] # zorgt dat de kaarten niet opraken tijdens het testen
                self.questionAwnser = yellowCards[self.currentYellowCard]
                self.currentYellowCard += 1
                #return False # als de kaarten op zijn
            else:
                self.currentQuestion = 'img/cards/yellow/' + yellowCards[self.currentYellowCard]
                self.questionAwnser = yellowCards[self.currentYellowCard]
                self.currentYellowCard += 1 #the next time on starts on a yellow space it will have the next question
        elif category == 'green': #if player is on a green space
            path = 'img/cards/Green'
            amountOfGreenCards = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
            greenCards =[f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]
            if amountOfGreenCards == self.currentGreenCard: #if player is on a green space
                self.currentGreenCard = 0
                self.currentQuestion = 'img/cards/Green/' + greenCards[self.currentGreenCard] # zorgt dat de kaarten niet opraken tijdens het testen
                self.questionAwnser = greenCards[self.currentGreenCard]
                self.currentGreenCard += 1
                #return False # als de kaarten op zijn
            else:
                self.currentQuestion = 'img/cards/Green/' + greenCards[self.currentGreenCard]
                self.questionAwnser = greenCards[self.currentGreenCard]
                self.currentGreenCard += 1 #the next time on starts on a green space it will have the next question
        self.questionAsked = True

    def showQuestion(self):
        question_image = pygame.image.load(self.currentQuestion)
        question_image_x_position = ((self.screenWidth / 100) * 25)
        question_image_y_position = (self.screenHeight / 100) * 25

        self.gameDisplay.blit(question_image, (question_image_x_position, question_image_y_position))

    def getAnswerForAI(self):
        if self.questionAwnser.endswith('A.jpg') == True:
            self.correctAnswer = "A"
            return "A"
        elif self.questionAwnser.endswith('B.jpg') == True:
            self.correctAnswer = "B"
            return "B"
        elif self.questionAwnser.endswith('C.jpg') == True:
            self.correctAnswer = "C"
            return "C"
        elif self.questionAwnser.endswith('D.jpg') == True:
            self.correctAnswer = "D"
            return "D"
    def IfAnswerIsCorrect(self):
        if self.questionAwnser.endswith('A.jpg') == True:
            self.correctAnswer = "A"
        elif self.questionAwnser.endswith('B.jpg') == True:
            self.correctAnswer = "B"
        elif self.questionAwnser.endswith('C.jpg') == True:
            self.correctAnswer = "C"
        elif self.questionAwnser.endswith('D.jpg') == True:
            self.correctAnswer = "D"

        if self.correctAnswer == self.playerAnswer:
            return True
        else:
            return False
    def QuestionButton(self):
        for events in pygame.event.get():
            if events.type == pygame.MOUSEBUTTONUP:
                xMousePos, yMousePos = pygame.mouse.get_pos()
                if xMousePos > self.x_postionButton1 and yMousePos > self.y_postionButton1 and xMousePos < (self.x_postionButton1 + self.questionButtonWidth) and yMousePos < (self.y_postionButton1 + self.questionButtonHeight) : #makes button work
                    self.playerAnswer = "A"
                    print('A')
                    return True
                elif xMousePos > self.x_postionButton2 and yMousePos > self.y_postionButton2 and xMousePos < (self.x_postionButton2 + self.questionButtonWidth) and yMousePos < (self.y_postionButton2 + self.questionButtonHeight):
                    self.playerAnswer = "B"
                    print('B')
                    return True
                elif xMousePos > self.x_postionButton3 and yMousePos > self.y_postionButton3 and xMousePos < (self.x_postionButton3 + self.questionButtonWidth) and yMousePos < (self.y_postionButton3 + self.questionButtonHeight):
                    self.playerAnswer = "C"
                    print('C')
                    return True
                elif xMousePos > self.x_postionButton4 and yMousePos > self.y_postionButton4 and xMousePos < (self.x_postionButton4 + self.questionButtonWidth) and yMousePos < (self.y_postionButton4 + self.questionButtonHeight):
                    self.playerAnswer = "D"
                    print('D')
                    return True
                #shortcuts
            if events.type == pygame.KEYDOWN:
                if events.key == pygame.K_a:
                    self.playerAnswer = "A"
                    return True
                elif events.key == pygame.K_b:
                    self.playerAnswer = "B"
                    return True
                elif events.key == pygame.K_c:
                    self.playerAnswer = "C"
                    return True
                elif events.key == pygame.K_d:
                    self.playerAnswer = "D"
                    return True
            if events.type == pygame.QUIT:
               pygame.quit()
               quit() #overbodig?
        return False

The Euromast/Game versie 0.1/Question.py