import sys

input = sys.stdin.readline
road = int(input())
ml, mk = map(int, input().split())
c = int(input())
bomb = [0] * (road + 1)
ans = "YES"

for i in range(1, 1 + road):
  z = int(input())
  if bomb[i - 1] - bomb[max(0, i - ml)]  + mk < z:
    if c > 0:
      c -= 1
      bomb[i] = bomb[i - 1]
    else:
      ans = "NO"
      break
  else:
    bomb[i] = bomb[i - 1] + mk

print(ans)


from evdev import InputDevice, categorize, ecodes
from select import select
import RPi.GPIO as GPIO
import os
import sys
from time import sleep
LPWM = 35 #Left Motor
REN = 10
RPWM = 12 #Right Motor
LEN = 16
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(RPWM, GPIO.OUT, initial = GPIO.LOW)
GPIO.setup(REN, GPIO.OUT, initial = GPIO.LOW)
GPIO.setup(LPWM, GPIO.OUT, initial = GPIO.LOW)
GPIO.setup(LEN, GPIO.OUT, initial = GPIO.LOW)
GPIO.setup(40, GPIO.OUT, initial = GPIO.LOW)
GPIO.setup(38, GPIO.OUT, initial = GPIO.LOW)

gamepad = InputDevice('/dev/input/event0')
gamepad.capabilities()
pwm1 = GPIO.PWM(RPWM, 20000) #Right Motor
pwm1.start(0)
pwm1r = GPIO.PWM(38, 20000) #Right Motor, Reverse
pwm1r.start(0)
pwm2 = GPIO.PWM(LPWM, 20000) #Left Motor
pwm2.start(0)
pwm2r = GPIO.PWM(40, 20000) #Left Motor, Reverse
pwm2r.start(0)

while True:

    r,w,x = select([gamepad], [], [])
    for event in gamepad.read():
        if event.type == ecodes.EV_KEY:
            keyevent = categorize(event)
            if keyevent.scancode == 304:
                print('Back')
            elif keyevent.scancode == 305:
                print('Right')

                if keyevent.keystate == 1:
                    pwm2.ChangeDutyCycle(0)
                    pwm1r.ChangeDutyCycle(0)
                    GPIO.output(REN, True) # Always set before driving motors
                    d = 10 # duty cycle

                    for i in range (8):
                        pwm1.ChangeDutyCycle(d)

                        pwm2r.ChangeDutyCycle(d)
                        d = d + 10 # increase speed over time
                        sleep(0.1)

                elif keyevent.keystate == 0:
                    d = 0
                    for i in range (10):
                        d = d + 10
                        pwm1.ChangeDutyCycle(100-d)
                        pwm2r.ChangeDutyCycle(100-d)
                        sleep(0.1)
                    GPIO.output(REN, False) # Set after no longer running motors

            elif keyevent.scancode == 308:
                print('Forward')

                if keyevent.keystate == 1:
                    pwm1r.ChangeDutyCycle(0)
                    pwm2r.ChangeDutyCycle(0)
                    GPIO.output(REN, True)

                    d = 10
                    for i in range (8):
                        pwm1.ChangeDutyCycle(d)
                        pwm2.ChangeDutyCycle(d)
                        d = d + 10
                        sleep(0.1)

                elif keyevent.keystate == 0:
                    d = 0
                    for i in range (10):
                        d = d + 10
                        pwm1.ChangeDutyCycle(100-d)
                        pwm2.ChangeDutyCycle(100-d)
                        sleep(0.1)
                    GPIO.output(REN, False)

            elif keyevent.scancode == 307:
                print('Left')
                if keyevent.keystate == 1:
                    pwm1.ChangeDutyCycle(0)
                    pwm2r.ChangeDutyCycle(0)
                    GPIO.output(REN, True)
                    d = 10
                    for i in range (8):
                        pwm2.ChangeDutyCycle(d)
                        pwm1r.ChangeDutyCycle(d)
                        d = d + 10
                        sleep(0.1)

                elif keyevent.keystate == 0:
                    d = 0
                    for i in range (10):
                        d = d + 10
                        pwm2.ChangeDutyCycle(100-d)
                        pwm1r.ChangeDutyCycle(100-d)
                        sleep(0.1)
                    GPIO.output(REN, False)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Description: Create a text file in the same directory containing all CJK
#              unified characters (87870) except 12 ones in the block named
#              CJK Compatibility Ideographs according to Unicode 10.0.
#              Tested under Python 3.5 on Ubuntu 16.04.
# Author: Yongzhen Ren
# Credits: Lin Lyu & Lulu Wang
# Date created: 2018-03-06

OUTPUT_FILE = "CJK_Unified_Characters.txt"

CJK_UI = (0x4E00, 0x9FEA)
CJK_UI_EX_A = (0x3400, 0x4DB5)
CJK_UI_EX_B = (0x20000, 0x2A6D6)
CJK_UI_EX_C = (0x2A700, 0x2B734)
CJK_UI_EX_D = (0x2B740, 0x2B81D)
CJK_UI_EX_E = (0x2B820, 0x2CEA1)
CJK_UI_EX_F = (0x2CEB0, 0x2EBE0)
BLOCKS = [CJK_UI, CJK_UI_EX_A, CJK_UI_EX_B, CJK_UI_EX_C, CJK_UI_EX_D, CJK_UI_EX_E, CJK_UI_EX_F]

if __name__ == "__main__":
	with open(OUTPUT_FILE, "w") as fp:
		for block in BLOCKS:
			for code_point in range(block[0], block[1] + 1):
			# Inclusive.
				fp.write(chr(code_point) + "\n")


from __future__ import annotations

from abc import ABCMeta
from logging import getLogger, Logger
from threading import Event, Lock
from typing import cast, ClassVar

from ..file_management import ScratchFile, FileManager
from ..metadata import MediaMetadata
from ..middlewares import Middleware

class Uploader(metaclass=ABCMeta):
    """
    Base class for all uploaders. Uploaders are responsible for uploading media to social media platforms.
    They are a thread to allow the execution of background tasks.
    """

    # This is necessary to reduce the chance of too many connections to the internet being opened in parallel and
    # causing a timeout error, connection ended error, or other similar error.
    glock: ClassVar[Lock] = Lock()

    def __init__(
        self, name: str, preprocessors: list[Middleware], *, run_concurrently: bool = False, **config
    ) -> None:
        self.name = f"{self.__class__.__name__}-{name.title().replace(' ', '-')}"

        self._shutdown_event: Event | None = None
        self._file_manager: FileManager | None = None
        self._run_concurrently = run_concurrently
        self.preprocessors = preprocessors

    @property
    def logger(self) -> Logger:
        return getLogger(self.name)

    @property
    def ready(self) -> bool:
        return (
            self._shutdown_event is not None
            and self._file_manager is not None
            and all(middleware.ready for middleware in self.preprocessors)
        )

    def prepare(self, **kwargs) -> None:
        assert not self.ready, "Uploader is already ready!"

        self.logger.debug(f"Preparing uploader {self.name}...")

        self._shutdown_event = kwargs["shutdown_event"]
        self._file_manager = kwargs["file_manager"]

        for middleware in self.preprocessors:
            middleware.prepare(**kwargs)

        assert self.ready, "Uploader failed to prepare."

    def upload(
        self, medias: list[tuple[ScratchFile, MediaMetadata]]
    ) -> list[tuple[ScratchFile, MediaMetadata | None]]:
        raise NotImplementedError

    def upload_and_preprocess(
        self, medias: list[tuple[ScratchFile, MediaMetadata | None]]
    ) -> list[tuple[ScratchFile, MediaMetadata | None]]:
        for middleware in self.preprocessors:
            medias = middleware.process_many(medias)
        try:
            uploaded: list[tuple[ScratchFile, MediaMetadata | None]] = []

            # Add the "real" uploads
            valid_medias: list[tuple[ScratchFile, MediaMetadata]] = cast(
                "list[tuple[ScratchFile, MediaMetadata]]",
                # mypy also fucks up this cast
                [media for media in medias if media[1] is not None],
            )

            if valid_medias:
                if self._run_concurrently:
                    real_uploads = self.upload(valid_medias)
                else:
                    with self.glock:
                        real_uploads = self.upload(valid_medias)

                uploaded.extend(real_uploads)

            # Add the leftovers
            uploaded.extend(media for media in medias if media[1] is None)

            return uploaded
        except Exception as e:
            self.logger.exception(f"Failed to upload media: {e}")
            return []

    def close(self) -> None:
        self.logger.debug(f"Closing uploader {self.name}...")

        for middleware in self.preprocessors:
            middleware.close()

__all__ = ("Uploader",)


import logging

logging.basicConfig(filename='log.txt',filemode='w',level=logging.DEBUG)
logging.debug('this is a debug message')
logging.warning('this is warning')
logging.error('this is error')
logger = logging.getLogger(__name__)
with open('log.txt', "rb") as f:
    for line in f:
        stripped_line=line.strip()
        print(stripped_line)

logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)


import heapq

a = [[int(j) for j in input().split()] for i in range(int(input()))]

ans, n, vis, pq, i = 0, len(a), set([0]), [], 0
rem = set(range(1, n))
while len(vis) < n:
    for j in rem: heappush(pq, (abs(a[i][0]-a[j][0]) + abs(a[i][1] - a[j][1]), j))
    while pq[0][1] in vis: heappop(pq)
    val, i = heappop(pq)
    vis.add(i); rem.discard(i)
    ans += val

print(ans)


import zmq, json, string, sys
sys.path.append('../../../src/LMCP/py')
from lmcp import LMCPFactory

if __name__ == '__main__':

    # prepare LMCP factory
    factory = LMCPFactory.LMCPFactory();

    # Socket to talk to server
    context = zmq.Context()
    socket_sub = context.socket(zmq.SUB)
    socket_sub.connect("tcp://127.0.0.1:5560")

    # subscribe to all possible messages
    # duplicate of UxAS config file, but necessary
    for c in string.ascii_letters:
        if (sys.version_info > (3, 0)):
            socket_sub.setsockopt_string(zmq.SUBSCRIBE, c)
        else:
            socket_sub.setsockopt_string(zmq.SUBSCRIBE, c.decode('ascii'))

    socket_send = context.socket(zmq.PUSH)
    socket_send.connect("tcp://127.0.0.1:5561")

    # main loop: receive a message, then process it
    while True:

        # raw bytes from socket
        data = bytearray(socket_sub.recv())

        # messages are single part with a header followed by
        # serialized LMCP
        # header format: [address]$[format]|[type]|[group]|[entity]|[service]$
        address, attributes, msg = data.split(bytearray('$','ascii'), 2)
        msg_format, msg_type, msg_group, entityid, serviceid = attributes.split(bytearray('|','ascii'),4)

        obj = factory.getObject(msg)

        # CreateServiceMessage currently has xml parsing problems, so remove
        if obj.FULL_LMCP_TYPE_NAME == "uxas.messages.uxnative.CreateNewService":
            continue

        print("Received: " + obj.FULL_LMCP_TYPE_NAME)

        # convert to XML
        xmlStr = obj.toXMLStr("")

        # convert from XML
        obj = factory.unpackFromXMLString(xmlStr)[0]

        # convert to JSON
        d = obj.toDict()
        j = json.dumps(d)
        #print("obj.toDict(): '%r'\n" % d)
        #print("JSON 'dumps' from dict: '%r'\n\n" % j)

	    # convert from JSON
        d2 = json.loads(j)
        obj2 = factory.unpackFromDict(d2)
        #print("dict loaded from json: '%r'\n" % d2)
        #print("type(obj): %r" % type(obj2))
        #print("obj unpacked from dict: '%r'\n\n" % obj2)

        print("JSON conversion successful? %r" % (d == d2,))
        if not (obj == obj2):
            #print("obj = '%s'" % obj.toString())
            #print("obj2 = '%s'" % obj2.toString())
            dd1 = obj.toDict()
            dd2 = obj2.toDict()
            # exporting back to dicts, to see whether the DATA really is different (not just listed as diff b/c diff subobjects)
            print("Dictionary conversion successful? %r" % (dd1 == dd2,))
            if not (dd1 == dd2):
                print("obj2 not same as original obj and dicts show different data, too (yikes!!)")
                print("dict obj = '%s'" % str(dd1))
                print("dict obj2 = '%s'" % str(dd2))

        # syntax to create an object from scratch
        obj = factory.createObjectByName("CMASI", "KeyValuePair")
        obj.set_Key("Hello")
        obj.set_Value("World")

        # syntax to send back to UxAS
        smsg = bytearray(str(obj.FULL_LMCP_TYPE_NAME) + "$lmcp|" + str(obj.FULL_LMCP_TYPE_NAME) + "||0|0$",'ascii')
        smsg.extend(LMCPFactory.packMessage(obj, True))
        socket_send.send(smsg)
        print("  Sent:   " + obj.FULL_LMCP_TYPE_NAME)


from Utils import Utils
class POMDP(object):
    '''class for the pomdp model'''
    def __init__(self):
        '''constructor for the model'''
        self.stateVariables=None
        self.states=None
        self.factoredStates=None
        self.stateFacts=None
        self.observations=None
        self.observationModel=None
        self.actions=None
        self.transitionMatrix=None
        self.immediateRewards=None
        self.beliefState=None
        self.horizon=None
        self.discountFactor=None

    def readModel(self,file):
        '''reads the pomdp model file'''
        model = Utils.readFile(file)
        self.getStates(model)
        self.getObservationModel(model)
        self.getActions(model)
        self.getTransitionMatrix(model)
        self.getImmediateRewards(model)
        self.getInitialBelief(model)
        self.getHorizon(model)
        self.getDiscountFactor(model)

    def getHorizon(self,model):
        '''returns the horizon length'''
        for line in model:
            if "horizon" in line:
                self.horizon = float(line.split("=")[1].strip())
                break
    def getDiscountFactor(self,model):
        '''returns discount factor'''
        for line in model:
            if "discountFactor" in line:
                self.discountFactor = float(line.split("=")[1].strip())
                break

    def getInitialBelief(self,model):
        '''returns the initial belief of the model'''
        self.beliefState = {}
        for line in model:
            if "initialBelief" in line:
                beliefs = line.split("=")[1].strip()[1:-1].split(",")
                break
        for state in self.states:
            self.beliefState[self.factoredStates[state]] = float(beliefs[self.states.index(state)])

    def getImmediateRewards(self,model):
        '''returns the immediate reward model'''
        self.immediateRewards = {}
        for line in model:
            if "reward:" in line:
                state = line.split(":")[1].strip().split("(")[1].split(",")[0]
                reward = float(line.split(":")[1].strip().split("(")[1].split(",")[1][:-1])
                self.immediateRewards[state] = reward

    def getActions(self,model):
        '''returns the actions possible in the model'''
        for line in model:
            if "actions = " in line:
                self.actions = line.split("=")[1].strip()[1:-1].split(",")
                break

    def getTransProbFromLine(self,line):
        '''returns transition probability from a transition line in the model'''
        return float(line.split(" ")[2].strip())

    def getActionFromLine(self,line):
        '''returns action from a transition line in the model'''
        return line.split("^")[1].split("(")[0]

    def getStateOneFromLine(self,line):
        '''returns state1 from a transition line in the model'''
        return line.split(" ")[1].split("^")[0][2:-1].split(",")[0]

    def getStateTwoFromLine(self,line):
        '''returns state2 from a transition line in the model'''
        return line.split("^")[0][2:-1].split(",")[1]

    def getTransitionMatrix(self,model):
        '''returns the transition matrix per action'''
        self.transitionMatrix = {}
        for action in self.actions:
            self.transitionMatrix[action] = {}
            for state1 in self.states:
                self.transitionMatrix[action][state1] = {}
                for state2 in self.states:
                    self.transitionMatrix[action][state1][state2] = False
        for line in model:
            if "transition:" in line:
                transProb = self.getTransProbFromLine(line)
                action = self.getActionFromLine(line)
                state1 = self.getStateOneFromLine(line)
                state2 = self.getStateTwoFromLine(line)
                self.transitionMatrix[action][state1][state2] = transProb
        for action in self.transitionMatrix.keys():
            for state1 in self.transitionMatrix[action].keys():
                missingStates = []
                for state2 in self.states:
                    if self.transitionMatrix[action][state1][state2] == False:
                        missingStates.append(state2)
                numberOfMissingStates = len(missingStates)
                total = sum([item for item in  self.transitionMatrix[action][state1].values() if item])
                for state in missingStates:
                    self.transitionMatrix[action][state1][state] = (1 - total)/float(numberOfMissingStates)

    def getStateVariables(self,model):
        '''returns the state variables used to describe a state'''
        for line in model:
            if "stateVariables" in line:
                return line.split("=")[1].strip()[1:-1].split(",")

    def getStateFacts(self,model):
        '''returns the facts of the states described by the state variables'''
        for line in model:
            if "stateFacts" in line:
                return line.split("=")[1].strip()[1:-1].split(",")

    def getFactoredState(self,state,stateFacts,model):
        '''returns the factored state as supported by the state facts'''
        factoredState = ""
        for variable in self.stateVariables:
            fact = variable+"("+state+")"
            if fact in stateFacts:
                factoredState += fact+"^"
            else:
                factoredState += "~"+fact+"^"
        return factoredState[:-1]

    def getFactoredStates(self,model):
        '''returns the states as conjunction of state variables'''
        stateDict = {}
        self.states = []
        self.stateFacts = self.getStateFacts(model)
        for line in model:
            if "states" in line:
                self.states = line.split("=")[1].strip()[1:-1].split(",")
                break
        for state in self.states:
            stateDict[state] = self.getFactoredState(state,self.stateFacts,model)
        return stateDict

    def getObservations(self,model):
        '''returns the observations of the pomdp model'''
        return [line.split("=")[1].strip()[1:-1].split(",") for line in model if "observations" in line][0]

    def getObservationFromLine(self,line):
        '''returns the observation part of the line'''
        return line.split("=>")[1].split(" ")[0].split("(")[0]

    def getObservationProbabilityFromLine(self,line):
        '''returns the observation probability of the line'''
        return float(line.split("=>")[1].split(" ")[1])

    def getObservationStateFromLine(self,line,model):
        '''returns the state for the observation'''
        state = line.split("=>")[1].split(" ")[0].split("(")[1][:-1]
        return self.getFactoredState(state,self.stateFacts,model)

    def getObservationModel(self,model):
        #method to constructs the observation model
        self.observationModel = {}
        self.observations = self.getObservations(model)
        for state in self.factoredStates:
            self.observationModel[self.factoredStates[state]] = {}
            for observation in self.observations:
                self.observationModel[self.factoredStates[state]][observation] = False
        for line in model:
            if "observation:" in line:
                obs = self.getObservationFromLine(line)
                obsProb = self.getObservationProbabilityFromLine(line)
                factoredState = self.getObservationStateFromLine(line,model)
                self.observationModel[factoredState][obs] = obsProb
        for factoredState in self.observationModel:
            missingObservations = []
            for observation in self.observationModel[factoredState]:
                if self.observationModel[factoredState][observation] == False:
                    missingObservations.append(observation)
            numberOfMissingObservations = len(missingObservations)
            if numberOfMissingObservations == 0:
                continue
            total = sum([item for item in  self.observationModel[factoredState].values() if item])
            for observation in missingObservations:
                self.observationModel[factoredState][observation] = (1 - total)/float(numberOfMissingObservations)

    def getStates(self,model):
        '''method that returns the states of the model'''
        self.stateVariables = self.getStateVariables(model)
        self.factoredStates = self.getFactoredStates(model)


import os
import shutil
import subprocess
import sys
import re

import toml

from . import validators as val
from .util import prompt

default_config_name = "makelove.toml"

all_targets = ["win32", "win64", "appimage", "macos", "lovejs"]

all_love_versions = [
    "11.5",
    "11.4",
    "11.3",
    "11.2",
    "11.1",
    "11.0",
    "0.10.2",
    "0.10.1",
    "0.10.0",
    "0.9.2",
    "0.9.1",
    "0.9.0",
    "0.8.0",
    "0.7.2",
    "0.7.1",
    "0.7.0",
    "0.6.2",
    "0.6.1",
    "0.6.0",
    "0.5.0",
    "0.4.0",
    "0.3.2",
    "0.3.1",
    "0.3.0",
    "0.2.1",
    "0.2.0",
    "0.1.1",
]

config_params = {
    "name": val.String(),
    "love_version": val.Choice(*all_love_versions),
    "default_targets": val.List(val.Choice(*all_targets)),
    "build_directory": val.Path(),
    "icon_file": val.Path(),
    "love_files": val.List(val.Path()),
    "keep_game_directory": val.Bool(),
    "archive_files": val.Dict(val.Path(), val.Path()),
    "hooks": val.Section(
        {
            "prebuild": val.List(val.Command()),
            "postbuild": val.List(val.Command()),
            "parameters": val.Dict(val.Any(), val.Any()),
        }
    ),
    "windows": val.Section(
        {
            "exe_metadata": val.Dict(val.String(), val.String()),
            "archive_files": val.Dict(val.Path(), val.Path()),
        }
    ),
    "win32": val.Section(
        {
            "love_binaries": val.Path(),
            "shared_libraries": val.List(val.Path()),
            "artifacts": val.ValueOrList(val.Choice("directory", "archive")),
        }
    ),
    "win64": val.Section(
        {
            "love_binaries": val.Path(),
            "shared_libraries": val.List(val.Path()),
            "artifacts": val.ValueOrList(val.Choice("directory", "archive")),
        }
    ),
    "linux": val.Section(
        {"desktop_file_metadata": val.Dict(val.String(), val.String())}
    ),
    "appimage": val.Section(
        {
            "source_appimage": val.Path(),
            "shared_libraries": val.List(val.Path()),
            "artifacts": val.ValueOrList(val.Choice("appdir", "appimage")),
        }
    ),
    "macos": val.Section(
        {
            "love_binaries": val.Path(),
            "icon_file": val.Path(),
            "app_metadata": val.Dict(val.String(), val.String()),
            "archive_files": val.Dict(val.Path(), val.Path()),
        }
    ),
    "lovejs": val.Section(
        {
            "title": val.String(),
            "memory": val.String(),
        }
    ),
}

def should_build_artifact(config, target, artifact, default):
    if not target in config or not "artifacts" in config[target]:
        return default
    if artifact in config[target]["artifacts"]:
        return True

def load_config_file(path):
    with open(path) as f:
        config_data = toml.load(f)
    validate_config(config_data)
    return config_data

def is_inside_git_repo():
    try:
        return (
            subprocess.run(
                ["git", "rev-parse", "--is-inside-work-tree"], capture_output=True
            ).returncode
            == 0
        )
    except FileNotFoundError:  # git is not installed
        return False

def guess_name():
    res = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True)
    if res.returncode == 0:
        git_root_path = res.stdout.decode("utf-8").strip()
        return os.path.basename(git_root_path)
    else:
        return os.path.basename(os.getcwd())

def get_default_targets():
    targets = ["win32", "win64"]
    if sys.platform == "linux":
        targets.append("appimage")
    return targets

def get_conf_filename():
    candidates = ["conf.lua", "conf.moon", "conf.ts"]
    for name in candidates:
        if os.path.isfile(name):
            print("Found {}".format(name))
            return name
    print("Could not find löve config file")
    return None

def guess_love_version():
    filename = get_conf_filename()
    if filename == None:
        return None

    with open(filename) as f:
        conf_lua = f.read()

    regex = re.compile(r"(?<!--)\.version\s*=\s*\"(.*)\"")
    matches = regex.findall(conf_lua)
    if len(matches) == 0:
        return None
    elif len(matches) > 1:
        print(
            "Could not determine löve version unambiguously. Candidates: {}".format(
                matches
            )
        )
        return None
    return matches[0]

def get_default_love_files(build_directory):
    if is_inside_git_repo():
        return [
            "::git-ls-tree::",
            "-*/.*",
        ]
    else:
        return [
            "+*",
            "-*/.*",
            "-./{}/*".format(build_directory),
        ]

def validate_config(config):
    try:
        val.Section(config_params).validate(config)
    except ValueError as exc:
        sys.exit("Could not parse config:\n{}".format(exc))

def get_raw_config(config_path):
    if config_path != None:
        if not os.path.isfile(config_path):
            sys.exit("Config file '{}' does not exist".format(config_path))
        print("Loading config file '{}'".format(config_path))
        return load_config_file(config_path)
    else:
        if os.path.isfile(default_config_name):
            print("Loading config from default path '{}'".format(default_config_name))
            return load_config_file(default_config_name)
        else:
            print("No config file found. Using default config.")
            return {}

def get_config(config_path):
    config = get_raw_config(config_path)
    if not "name" in config:
        config["name"] = guess_name()
        print("Guessing project name as '{}'".format(config["name"]))
    if not "love_version" in config:
        conf_love_version = guess_love_version()
        if conf_love_version:
            config["love_version"] = conf_love_version
            print(
                "Guessed löve version from löve config file: {}".format(
                    conf_love_version
                )
            )
        else:
            config["love_version"] = "11.3"  # update this manually here
            print("Assuming default löve version '{}'".format(config["love_version"]))
    if not "default_targets" in config:
        config["default_targets"] = get_default_targets()
    if not "build_directory" in config:
        config["build_directory"] = "makelove-build"
        print("Using default build directory '{}'".format(config["build_directory"]))
    if not "love_files" in config:
        config["love_files"] = get_default_love_files(config["build_directory"])
        print("Using default love_files patterns: {}".format(config["love_files"]))
    validate_config(config)
    return config

init_config_template = """name = {name}
default_targets = [{default_targets}]
build_directory = {build_directory}

love_files = [
{love_files}
]
"""

def init_config_assistant():
    if os.path.isfile(default_config_name):
        sys.exit("{} already exists in this directory".format(default_config_name))

    if not is_inside_git_repo():
        print("If you plan on using git, please initialize the repository first!")

    name = prompt("Project name")
    default_targets = get_default_targets()
    build_directory = prompt("Build directory", "makelove-build")
    love_files = get_default_love_files(build_directory)

    quote = lambda x: '"' + x.replace('"', '\\"') + '"'
    config = init_config_template.format(
        name=quote(name),
        default_targets=", ".join(map(quote, default_targets)),
        build_directory=quote(build_directory),
        love_files="\n".join("    " + quote(pat) + "," for pat in love_files),
    )

    with open(default_config_name, "w") as f:
        f.write(config)
    print("Configuration written to {}".format(default_config_name))
    print("You should probably adjust love_files before you build.")


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

from functools import reduce
import numpy as np
import pandas as pd
import itertools as it
import os
import re
import textwrap
import logging
import matplotlib

class decomposition:
    """a class to store & query npz file"""
    # https://matplotlib.org/api/collections_api.html#matplotlib.collections.Collection.set_hatch
    def __init__(
        self,
        npz_file,
        colors = matplotlib.pyplot.cm.tab20c((np.arange(13)).astype(int)),
        hatches = ['', '/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*', '++', 'xx', 'oo', 'OO', '..', '**'],
    ):
        """read npz file and store it into a python dict and store"""
        self.logger = logging.getLogger('data_load_from_npz')
        data = dict([])
        self.logger.info('reading data from {}'.format(npz_file))
        with np.load(npz_file) as f:
            for k in f.keys():
                data[k] = f[k]
        if('eigen_v' in data):
            data['n_PCs'] = len(data['eigen_v'])
        else: # for ssvd results
            data['n_PCs'] = data['factor_phe'].shape[1]
        data['n_phes']  = data['contribution_phe'].shape[0]
        data['n_vars']  = data['contribution_var'].shape[0]
        data['n_genes']  = data['contribution_gene'].shape[0]
        if('eigen_v' in data):
            data['variance_explained'] = (data['eigen_v'] ** 2) / data['total_inertia']
        self.d = data

        # dict to look up index given a label
        self.dict_inv_label = {
            target: dict(zip(self.d['label_{}'.format(target)],
                             np.arange(len(self.d['label_{}'.format(target)]))))
            for target in ['phe', 'var', 'gene']}

        self.colors = colors
        self.hatches = hatches
        self.color_len = len(self.colors)
        self.hatch_len = len(self.hatches)

    def get_index_generic(self, target, label):
        return self.dict_inv_label[target][label]
    def get_phe_index(self, label):
        return self.get_index_generic('phe', label)
    def get_var_index(self, label):
        return self.get_index_generic('var', label)
    def get_gene_index(self, label):
        return self.get_index_generic('gene', label)
    def get_phe_str(self, index):
        return self.d['label_phe'][index]
    def get_cos_phe_by_index(self, index):
        return self.d['cos_phe'][index]
    def get_cos_phe_by_label(self, label):
        return self.d['cos_phe'][self.get_phe_index(label)]
    def get_topk_pcs_for_phe_by_index(self, index, topk=None):
        if topk is None:
            topk = self.d['n_PCs']
        return np.argsort(-self.d['cos_phe'][index, :])[:topk]
    def get_topk_pcs_for_phe_by_label(self, label, topk=None):
        return self.get_topk_pcs_for_phe_by_index(self.get_phe_index(label), topk=topk)
    def get_topk_pcs_for_phe_with_scores_by_index(self, index, topk=None):
        sort_order = self.get_topk_pcs_for_phe_by_index(index, topk)
        labels = self.d['cos_phe'][index, sort_order]
        return sort_order, labels
    def get_topk_pcs_for_phe_with_scores_by_label(self, label, topk=None):
        return self.get_topk_pcs_for_phe_with_scores_by_index(
            self.get_phe_index(label), topk=topk)
    def get_kth_pc_for_phe_by_index(self, index, k):
        return self.get_topk_pcs_for_phe_by_index(index, topk=k)[-1]
    def get_kth_pc_for_phe_by_label(self, label, k):
        return self.get_kth_pc_for_phe_by_index(self.get_phe_index(label), k)
    def get_contribution_score_by_label_generic(self, target, pc_0index, label):
        return self.d['contribution_{}'.format(target)][self.get_index_generic(target, label), pc_0index]

    def plot_data_cos_phe_by_index(self, index):
        return {
            'x': np.arange(self.d['n_PCs']) + 1,
            'y': self.get_cos_phe_by_index(index),
            'title': 'Squared cosine score for {}'.format(self.get_phe_str(index)),
            'xlabel': 'component',
            'ylabel': 'Squared cosine score'
        }
    def plot_data_cos_phe_by_label(self, label):
        return self.plot_data_cos_phe_by_index(self.get_phe_index(label))

    def get_stacked_bar_color(self, target, labels):
        return np.array([
            self.colors[self.get_index_generic(target, label) % self.color_len]
            if label != 'others'
            else '0.8'
            for label in labels
        ])

    def get_stacked_bar_hatch(self, target, labels):
        return np.array([
            self.hatches[self.get_index_generic(target, label) % self.hatch_len]
            if label != 'others'
            else ''
            for label in labels
        ])

    def plot_data_contribution_generic(
        self, target, pc_index, topk=None, sort=True, append_others = False,
        contribution_thr = None, contribution_cumsum_thr = None,
    ):
        assert(topk is None or sort)
        if target is 'phe':
            topk_default = self.d['n_phes']
            contribution_key = 'contribution_phe'
            xlabel = 'Phenotype'
            label_key = 'label_phe'
            label_key_sub = 'label_phe_code'
        elif target is 'gene':
            topk_default = self.d['n_genes']
            contribution_key = 'contribution_gene'
            xlabel = 'Gene'
            label_key = 'label_gene'
            label_key_sub = 'label_gene'
        elif target is 'var':
            topk_default = self.d['n_vars']
            contribution_key = 'contribution_var'
            xlabel = 'Variant'
            label_key = 'label_var'
            label_key_sub = 'label_var'
        else:
            raise(ValueError("target ({}) is not in ['phe', 'var', 'gene']".format(target)))
        if topk is None:
            topk = topk_default
        if (contribution_thr is not None) or (contribution_cumsum_thr is not None):
            sort = True
        if sort:
            sort_order = np.argsort(-self.d[contribution_key][:, pc_index])
        else:
            sort_order = np.arange(topk)
        if contribution_thr is not None:
            topk = np.sum(
                self.d[contribution_key][:, pc_index] >= contribution_thr)
        if contribution_cumsum_thr is not None:
            topk = 1 + np.sum(
                np.cumsum(self.d[contribution_key][sort_order, pc_index]) < contribution_cumsum_thr)
        pd_x = np.arange(topk) + 1
        pd_y = self.d[contribution_key][sort_order[:topk], pc_index]
        pd_title = '{} contribution score for PC{}'.format(xlabel, pc_index + 1)
        pd_xlabel = xlabel
        pd_ylabel = '{} contribution score'.format(xlabel)
        pd_xticklabels = self.d[label_key][sort_order[:topk]]
        pd_xticklabels_sub = self.d[label_key_sub][sort_order[:topk]]

        if(append_others):
            pd_y = np.append(pd_y, 1 - np.sum(pd_y))
            pd_xticklabels = np.append(pd_xticklabels, 'others')
            pd_xticklabels_sub = np.append(pd_xticklabels_sub, 'others')
            pd_x = np.arange(topk + 1) + 1

        stacked_bar_color = self.get_stacked_bar_color(target, pd_xticklabels)
        stacked_bar_hatch = self.get_stacked_bar_hatch(target, pd_xticklabels)

        return {
            'x': pd_x,
            'y': pd_y,
            'title': pd_title,
            'xlabel': pd_xlabel,
            'ylabel': pd_ylabel,
            'xticklabels': pd_xticklabels,
            'xticklabels_sub': pd_xticklabels_sub,
            'stacked_bar_color': stacked_bar_color,
            'stacked_bar_hatch': stacked_bar_hatch,
        }
    def plot_data_contribution_phe(
        self, pc_index, topk=None, sort=True, append_others = False,
        contribution_thr = None, contribution_cumsum_thr = None,):
        return self.plot_data_contribution_generic(
            'phe', pc_index, topk, sort, append_others,
            contribution_thr, contribution_cumsum_thr)
    def plot_data_contribution_var(
        self, pc_index, topk=None, sort=True, append_others = False,
        contribution_thr = None, contribution_cumsum_thr = None,):
        return self.plot_data_contribution_generic(
            'var', pc_index, topk, sort, append_others,
            contribution_thr, contribution_cumsum_thr)
    def plot_data_contribution_gene(
        self, pc_index, topk=None, sort=True, append_others = False,
        contribution_thr = None, contribution_cumsum_thr = None,):
        return self.plot_data_contribution_generic(
            'gene', pc_index, topk, sort, append_others,
            contribution_thr, contribution_cumsum_thr)
    def plot_data_contribution_phe_list(self, phe_list, pc_index=0):
        pd_title = 'Phenotype contribution score'
        phe_set = set(phe_list)
        phe_slice = np.array([x in phe_set for x in self.d['label_phe']])
        labels = self.d['label_phe'][phe_slice]
        return {
            'x': np.arange(len(phe_set)),
            'y': self.d['contribution_phe'][phe_slice, pc_index],
            'title': pd_title,
            'xlabel': '',
            'ylabel': pd_title,
            'xticklabels': labels,
            'xticklabels_sub': self.d['label_phe_code'][phe_slice],
            'stacked_bar_color': self.get_stacked_bar_color('phe', labels),
            'stacked_bar_hatch': self.get_stacked_bar_hatch('phe', labels),
        }
    def plot_data_pca_generic(self, target, pc_index1, pc_index2):
        assert ((target == 'phe') or (target == 'var'))
        if target == 'phe':
            fig_title = 'Phenotype PCA'
        elif target == 'var':
            fig_title = 'Variant PCA'
        else:
            raise(ValueError("target ({}) is not in ['phe', 'var']".format(target)))
        return {
            'x': self.d['factor_{}'.format(target)][:, pc_index1],
            'y': self.d['factor_{}'.format(target)][:, pc_index2],
            'title': fig_title,
            'xlabel': 'Component {}'.format(pc_index1 + 1),
            'ylabel': 'Component {}'.format(pc_index2 + 1)
        }
    def plot_data_pca_phe(self, pc_index1, pc_index2):
        return self.plot_data_pca_generic('phe', pc_index1, pc_index2)
    def plot_data_pca_var(self, pc_index1, pc_index2):
        return self.plot_data_pca_generic('var', pc_index1, pc_index2)
    def plot_data_scree(self):
        return {
            'x': np.arange(self.d['n_PCs']) + 1,
            'y': self.d['variance_explained'],
            'title': 'Scree plot',
            'xlabel': 'Components',
            'ylabel': 'Variance explained score',
        }
    def bed_data_contribution_var(
        self, pc_index, topk=None, sort=True, append_others = False,
        contribution_thr = None, contribution_cumsum_thr = None,
    ):
        plotd = self.plot_data_contribution_generic(
            'var', pc_index, topk, sort, append_others,
            contribution_thr, contribution_cumsum_thr)
        topk_var_chrs, topk_var_poss = zip(*[x.split('-') for x in plotd['xticklabels']])
        return pd.DataFrame({
            'chrom': ['chr{}'.format(x) for x in topk_var_chrs],
            'chromStart': topk_var_poss,
            'chromEnd': [str(int(x) + 1) for x in topk_var_poss],
            'name': ['{:.4e}'.format(x) for x in plotd['y']]
        })[['chrom', 'chromStart', 'chromEnd', 'name']]
    def text_data_contribution_gene(
        self, pc_index, topk=None, sort=True, append_others = False,
        contribution_thr = None, contribution_cumsum_thr = None,
    ):
        plotd = self.plot_data_contribution_generic(
            'gene', pc_index, topk, sort, append_others,
            contribution_thr, contribution_cumsum_thr)

        mask_by_gene_name = np.array([len(x.split(',')) == 1 for x in plotd['xticklabels']])
        labels = plotd['xticklabels'][mask_by_gene_name]
        scores = plotd['y'][mask_by_gene_name]
        query_str = '\n'.join(['{},{:.4f}'.format(x[0], x[1])
                               for x in zip(labels, scores)])
        return query_str, len(labels), np.sum(scores)
    def text_contribution_generic(
        self, target, pc_index, topk=None, sort=True, append_others = False,
        contribution_thr = None, contribution_cumsum_thr = None,
        labels='xticklabels', values='y', value_multiplier = 100,
        string_format='{} ({:.2f}%)', delim=', '
    ):
        plot_d = self.plot_data_contribution_generic(
            target, pc_index, topk, sort, append_others,
            contribution_thr, contribution_cumsum_thr
        )
        return delim.join([string_format.format(l, y*value_multiplier) for l, y in zip(plot_d[labels], plot_d[values])])
    def text_description_phe_by_index(
        self, index, num_of_top_pcs, target,
        pcs_delim = '; ', pcs_string_format='[PC{}, {:.2f}]: {}',
        topk=None, sort=True, append_others = False,
        contribution_thr = None, contribution_cumsum_thr = None,
        labels='xticklabels', values='y', value_multiplier = 100,
        string_format='{} ({:.2f}%)', delim=', ',
    ):
        pcs, squared_cos_scores = self.get_topk_pcs_for_phe_with_scores_by_index(index, topk=num_of_top_pcs)
        return 'Top {} components for {} is: '.format(
            num_of_top_pcs, self.get_phe_str(index)
        ) + pcs_delim.join([
            pcs_string_format.format(
                pc_index + 1, squared_cos_score,
                self.text_contribution_generic(
                    target = target, pc_index = pc_index,
                    topk = topk, sort = sort, append_others = append_others,
                    contribution_thr = contribution_thr,
                    contribution_cumsum_thr = contribution_cumsum_thr,
                    labels = labels, values = values,
                    value_multiplier = value_multiplier,
                    string_format=string_format, delim=delim))
            for pc_index, squared_cos_score
            in zip(pcs, squared_cos_scores)
        ])
    def text_description_phe_by_label(
        self, label, num_of_top_pcs, target,
        pcs_delim = '; ', pcs_string_format='[PC{}, {:.2f}]: {}',
        topk=None, sort=True, append_others = False,
        contribution_thr = None, contribution_cumsum_thr = None,
        labels='xticklabels', values='y', value_multiplier = 100,
        string_format='{} ({:.2f}%)', delim=', ',
    ):
        return self.text_description_phe_by_index(
            self.get_phe_index(label), num_of_top_pcs, target,
            pcs_delim, pcs_string_format,
            topk, sort, append_others,
            contribution_thr, contribution_cumsum_thr,
            labels, values, value_multiplier,
            string_format, delim)
    def get_biplot_arrow_by_phenotypes(self, pc_list, phenotypes):
        matrix_key = 'eigen_phe'
        return np.array([
            [self.d['eigen_phe'][phe_idx][pc_idx] for pc_idx in pc_list]
            for phe_idx in [self.get_phe_index(x) for x in phenotypes]
        ])


def solve():
    n, k = map(int, input().split())
    i = 1
    indices = []
    while i < 30 and k >= 0:
        if k == 0:
            print("YES")
            print(len(indices))
            for j in indices:
                print(j)
            return
        if k < _range[i - 1]:
            print("NO")
            return
        k -= _range[i - 1]
        indices.append(k + 1)
        i += 1
    else:
        print("NO")

_range = [2 ** (i - 1) for i in range(1, 30)]

def presum(arr):
    ret = [0] * len(arr)
    ret[0] = arr[0]
    for i in range(1, len(arr)):
        ret[i] = ret[i - 1] + arr[i]
    return ret

T = int(input())
for _ in range(T):
    solve()


import json
import os

import logging
log = logging.getLogger('zeek')

def dump_config_to_json(config, outputdir):
    """
    Dump the configuration file to json.

    Args
        config: a dictionary with model configuration
        outputdir: path of the output directory
    """
    with open(os.path.join(outputdir, "config.json"), "w") as f_out:
        json.dump(config, f_out)

def update_config_datasetone(config_dict, outputdir):
    """Config for Dataset-1."""
    config_dict['training']['df_train_path'] = \
        "/input/Dataset-1/training_Dataset-1.csv"
    config_dict['training']['features_train_path'] = \
        "/input/Dataset-1/features/training/zeek_Dataset-1_training.json"
    config_dict['validation'] = dict(
        positive_path="/input/Dataset-1/pairs/validation/pos_validation_Dataset-1.csv",
        negative_path="/input/Dataset-1/pairs/validation/neg_validation_Dataset-1.csv",
        features_validation_path="/input/Dataset-1/features/validation/zeek_Dataset-1_validation.json"
    )
    config_dict['testing'] = dict(
        positive_path=None,
        negative_path=None,
        full_tests_inputs=[
            "/input/Dataset-1/pairs/testing/neg_rank_testing_Dataset-1.csv",
            "/input/Dataset-1/pairs/testing/neg_testing_Dataset-1.csv",
            "/input/Dataset-1/pairs/testing/pos_rank_testing_Dataset-1.csv",
            "/input/Dataset-1/pairs/testing/pos_testing_Dataset-1.csv"
        ],
        full_tests_outputs=[
            os.path.join(outputdir, "neg_rank_testing_Dataset-1_sim.csv"),
            os.path.join(outputdir, "neg_testing_Dataset-1_sim.csv"),
            os.path.join(outputdir, "pos_rank_testing_Dataset-1_sim.csv"),
            os.path.join(outputdir, "pos_testing_Dataset-_sim2.csv")
        ],
        features_testing_path="/input/Dataset-1/features/testing/zeek_Dataset-1_testing.json"
    )

def update_config_datasettwo(config_dict, outputdir):
    """Config for Dataset-2."""
    config_dict['testing'] = dict(
        positive_path=None,
        negative_path=None,
        full_tests_inputs=[
            "/input/Dataset-2/pairs/neg_rank_testing_Dataset-2.csv",
            "/input/Dataset-2/pairs/neg_testing_Dataset-2.csv",
            "/input/Dataset-2/pairs/pos_rank_testing_Dataset-2.csv",
            "/input/Dataset-2/pairs/pos_testing_Dataset-2.csv"
        ],
        full_tests_outputs=[
            os.path.join(outputdir, "neg_rank_testing_Dataset-2_sim.csv"),
            os.path.join(outputdir, "neg_testing_Dataset-2_sim.csv"),
            os.path.join(outputdir, "pos_rank_testing_Dataset-2_sim.csv"),
            os.path.join(outputdir, "pos_testing_Dataset-_sim2.csv")
        ],
        features_testing_path="/input/Dataset-2/features/zeek_Dataset-2.json"
    )

def update_config_datasetvuln(config_dict, outputdir):
    """Config for Dataset-Vulnerability."""
    config_dict['testing'] = dict(
        positive_path=None,
        negative_path=None,
        full_tests_inputs=[
            "/input/Dataset-Vulnerability/pairs/pairs_testing_Dataset-Vulnerability.csv",
        ],
        full_tests_outputs=[
            os.path.join(outputdir, "pairs_testing_Dataset-Vulnerability.csv")
        ],
        features_testing_path="/input/Dataset-Vulnerability/features/zeek_Dataset-Vulnerability.json"
    )

def get_config(args):
    """The default configs."""

    config_dict = dict(
        nn_input_size=2048,
        vector_size=1024,
        l1_size=512,
        l2_size=128,
        dropout_reg=0.1,

        training=dict(
            learning_rate=0.001,
            num_epochs=args.num_epochs,
            print_after=20
        ),
        validation=dict(),
        testing=dict(),

        # -1: whole dataset
        batch_size=32,
        checkpoint_dir=args.checkpointdir,
        seed=11
    )

    if args.dataset == 'one':
        update_config_datasetone(config_dict, args.outputdir)
    elif args.dataset == 'two':
        update_config_datasettwo(config_dict, args.outputdir)
    elif args.dataset == 'vuln':
        update_config_datasetvuln(config_dict, args.outputdir)

    return config_dict


import scipy.stats as st
import numpy as np
import matplotlib.pyplot as plt

distributions = {
    'normal': st.norm(loc=0, scale=1),
    'laplace': st.laplace(loc=0, scale=1/np.sqrt(2)),
    'cauchy': st.cauchy(),
    'uniform': st.uniform(loc=-np.sqrt(3), scale=2*np.sqrt(3)),
    'poisson': st.poisson(5)
}

def Zr(x):
    return (np.amin(x) + np.amax(x))/2

def Zq(x):
    return (np.quantile(x, 1/4) + np.quantile(x, 3/4))/2

def Ztr(x):
    n = x.size
    r = (int)(n / 4)
    sum1 = 0
    for i in range(r, n - r):
        sum1 += x[i]
    return sum1 / (n - 2 * r)

pos_characteristics = {
    'average': np.mean,
    'med': np.median,
    'Zr': Zr,
    'Zq': Zq,
    'Ztr': Ztr
}

sizes = [20, 60, 100]
k_h = [0.5, 1, 2]

def prob_dist_table(x_e):
    a = np.sort(x_e)
    result = []
    elms, counts = np.unique(a, return_counts=True)
    result.append(elms)
    dist_table = [counts[i] / x_e.size for i in range(0, elms.size)]
    sum_p = 0
    dist = []
    for p in dist_table:
        sum_p += p
        dist.append(sum_p)
    result.append(dist)
    return result

def prob_dist_func(x_e, table):
    for t in range(0, table[0].size):
        if t == 0 and x_e < table[0][t]:
            return 0
        if x_e < table[0][t]:
            return table[1][t - 1]
    return 1

def h(n, var):
    return 1.06*np.std(var)*np.power(n,-0.2)

def K(u):
    return np.exp(-(u**2)/2)/np.sqrt(2*np.pi)

def density_function(x_e, var, h_n_e):
    sum_d = 0
    for x_i in var:
        sum_d += K((x_e - x_i) / h_n_e)
    return sum_d / (var.size * h_n_e)

for size in sizes:
    for dist in distributions.keys():
        fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(12, 8))
        r = distributions[dist].rvs(size=size)
        for i in range(0, 3):
            h_n = k_h[i]*h(r.size, r)
            if (dist == 'poisson'):
                x = [k for k in range(6, 15)]
                ax[i].plot(x, distributions[dist].pmf(x), 'bo', ms=4)
                ax[i].vlines(x, 0, distributions[dist].pmf(x), colors='b', lw=2, label='PDF', alpha=0.2)
                ax[i].plot(x, density_function(x, r, h_n), 'r-', label='Kernel density', lw=4)
            else:
                x = np.linspace(-4, 4, 100)
                ax[i].plot(x, distributions[dist].pdf(x), 'b-', label='PDF', lw=2)
                ax[i].plot(x, density_function(x, r, h_n), 'r-', label='Kernel density', lw=4)
            if k_h[i] != 1:
                ax[i].set_title(str(k_h[i]) + '*h_n')
            else:
                ax[i].set_title('h_n')
            ax[i].legend(loc='upper left')
            ax[i].grid()
        fig.suptitle('n=' + str(size) + 'with window width h =[0.5, 1, 2]', fontsize=12)
        fig.savefig(dist + '_pdf_' + str(size))

for dist in distributions.keys():
    fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(12, 8))
    for i in range(0, 3):
        r = distributions[dist].rvs(size=sizes[i])
        table = prob_dist_table(r)
        if dist == 'poisson':
            x = [k for k in range(6, 15)]
            ax[i].plot(x, distributions[dist].cdf(x), 'b-', ms=4)
            ax[i].vlines(x, 0, distributions[dist].cdf(x), colors='b', lw=2, label='CDF', alpha=0.2)
            ax[i].plot(x, [prob_dist_func(x_i, table) for x_i in x], 'r-', label='Experimental distribution', lw=4)
        else:
            x = np.linspace(-4, 4, 100)
            ax[i].plot(x, distributions[dist].cdf(x), 'b-', label='CDF', lw=2)
            ax[i].plot(x, [prob_dist_func(x_i, table) for x_i in x], 'r-', label='Experimental distribution', lw=4)
        ax[i].set_title('n = ' + str(sizes[i]))
        ax[i].legend(loc='upper left')
        ax[i].grid()
    fig.savefig(dist + '_cdf')


# Problem 25
# 1000-digit Fibonacci number
#
# By Eunsol

cache = {1:1, 2:1}
def f(n):
    if not n in cache:
        cache[n] = f(n-1) + f(n-2)
    return cache[n]

for i in range(1, 10000):
    if f(i) > 10 ** 999:
        print (i)
        break


#
#   Library file for unifying interface for both SQL results, storing results
#       and loading stored queries.
#   Also contains code for combining different log files.
#
#   Wouter Kayser 2020
#

from collections import defaultdict
from datetime import datetime
import csv
import matplotlib.pyplot as plt
import pyodbc

def sum_dicts(dicts):
    # Similar to how counters can be summed. But now for the general
    # type of dicts
    ret = defaultdict(int)
    for d in dicts:
        for k, v in d.items():
            ret[k] += v
    return dict(ret)

def sql_query(file, key='../default.key', header=True):
    # Executes a query on the server defined by the key
    # Can also skip the header if needed.
    # Operates nicely as a generator to save resources.
    with open(key, 'r') as keyfile:
        conn = pyodbc.connect(keyfile.read())

    with open(file, 'r') as query_file:
        query = query_file.read()

    cursor = conn.cursor()
    cursor.execute(query)

    if header:
        yield [i[0] for i in cursor.description]

    for row in cursor:
        yield(row)

def store_sql(file, key='../default.key', header=True):
    # Used to store the outcome of an SQL query so it can be used later
    # Includes a time stamp
    stamp = datetime.now().strftime('%Y%m%d %H %M %S')
    name = file + stamp + '.bckup'

    with open(name, 'w', newline='') as bckup:
        reader = sql_query(file, key, header)
        writer = csv.writer(bckup)
        for row in reader:
            writer.writerow(row)
            yield row

def csvreader(file, sep='\t', header=True):
    # Simple CSV reader wrapper to handle headers
    # Exposes a nice generator again.
    with open(file, newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=sep)
        if not header:
            next(reader)
        while(True):
            try:
                yield next(reader)
            except StopIteration:
                return

def load_dict(reader, max_index=1):
    # Mainly used to load counter values from eNodeBs into dictionaries
    # However is not recommended to use, as more processing often needs to
    # happen on the database.

    # Dictionaries are nested to attempt to gain some structure.

    def convtime(str_date):
        # Function to convert time into the python representation.
        return datetime.strptime(str_date, '%Y-%m-%d %H:%M:%S.0000000')

    headers = next(reader)
    if max_index == 1:
        timeseries = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
        for row in reader:
            time, enb = convtime(row[0]), row[1]
            for value, counter in enumerate(headers[2:]):
                if row[value+2] != 'NULL':
                    timeseries[time][enb][counter] = int(row[value+2])
    else:
        timeseries = defaultdict(lambda: defaultdict(
                                 lambda: defaultdict(
                                    lambda: [0 for x in range(max_index)])))
        for row in reader:
            time, enb, index = convtime(row[0]), row[1], int(row[2])
            for value, counter in enumerate(headers[3:]):
                if row[value+3] != 'NULL':
                    timeseries[time][enb][counter][index] = int(row[value+3])

    return timeseries

def print_dict(target):
    # Function that could be used to print a nested dict such
    # such as created by the previous function
    for time in target:
        for enb in target[time]:
            print(time, '||', enb)
            for counter in target[time][enb]:
                print('\t', counter, ': ', target[time][enb][counter])

def read_log(rows, eNodeB, rat=8):
    # Used to load in the AT-AT log of sent messages
    # eNodeB is used to match the dict structure to earlier used methods
    # rat can be used to select only the NB-IoT activity.
    headers = next(rows)
    timeseries = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
    for row in rows:
        if int(row[-1]) == rat:
            # Again most code is used for time manipulation
            time = datetime(2020,
                            int(row[0]),
                            int(row[1]),
                            hour=int(row[2]),
                            minute=int(row[3])*15)

            timeseries[time][eNodeB]['Payload size'] += int(row[-2])
            timeseries[time][eNodeB]['Occurrence'] += 1
    return timeseries

def combine_ts(sets):
    # Can be used to combine the timeseries dicts created earlier
    # can be used to combine logs and counters
    result = defaultdict(lambda: defaultdict(dict))
    for ts in sets:
        for date in ts.keys():
            for enb in ts[date].keys():
                result[date][enb].update(ts[date][enb])
    return result

def try_store(file):
    # Simple helper function for windows based systems, as some pdf or image
    # readers lock the file while viewing.
    try:
        plt.savefig(file)
        print(f'Saved file as {file}')
    except Exception:
        print("Remember that you are on windows")
        try_store('new_' + file)


#!/usr/bin/env python3

# Lesson_6 Activity 1 Test Mailroom Part 4

from Mailroom_Pt4 import *
import os.path

def test_add_donation():
    add_donation('James Franconstein', 3009375072340)
    assert 'James Franconstein' in donor_chart.keys()
    assert 3009375072340 in donor_chart['James Franconstein']

def test_create_report():
    report_test = create_report()
    for item in donor_chart.items():
        assert item[0] in report_test
        assert f"{sum(item[1]):.2f}" in report_test

def test_send_letters_1():
    send_letters("somewhere_over_the_rainbow")
    for item in donor_chart.items():
        assert os.path.isfile((item[0] + ".txt"))

def test_send_letters_2():
    test_dump = "C:\\Users\\chris.kenyon\\Documents\\"
    "Kenyon\\UWPython\\Testing_File_dump"
    send_letters(test_dump)
    for item in donor_chart.items():
        assert os.path.isfile((os.path.join(test_dump, item[0] + ".txt")))

def test_get_key():
    for donor in donor_chart.items():
        sumlist = get_key(donor)
        assert sumlist == sum(donor[1])


from mxnet import gluon
from mxnet.gluon import nn

import mxnet as mx

class Discriminator(gluon.HybridBlock):

    def __init__(self, opts, *args, **kwargs):
        super(Discriminator, self).__init__(*args, **kwargs)
        self.opts = opts
        self.init = {
            'weight_initializer': mx.init.Normal(0.02)
        }

        mult = 1
        feature_size = self.opts.image_size

        with self.name_scope():
            self.stages = nn.HybridSequential()
            # We have to produce (? x 4 x 4) features maps at layer n-1, whatever the original image size was
            while feature_size > 4:
                layer = nn.HybridSequential()
                layer.add(nn.Conv2D(self.opts.d_h_size * mult, 4, 2, 1, use_bias=False, **self.init))
                if self.opts.relu:
                    layer.add(nn.LeakyReLU(0.2))
                else:
                    layer.add(nn.BatchNorm())
                    layer.add(nn.SELU())

                feature_size = feature_size // 2
                mult *= 2
                self.stages.add(layer)

            self.stages.add(nn.Conv2D(1, 4, 1, 0, use_bias=False, **self.init))
            # Decreases performances
            #self.stages.add(nn.Activation('sigmoid'))

    def hybrid_forward(self, F, x, *args, **kwargs):
        x = self.stages(x)
        return F.reshape(x, shape=-1)  # .view(-1) in PyTorch => we need to rearrange 1x1x1 to 1


import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.misc import onehot_from_logits, categorical_sample

import numpy as np
cloest = np.load("cloest.npy")

class SelfAttention(nn.Module):
    def __init__(self, s_dim, hid_dim, n_heads):
        super().__init__()

        self.hid_dim = hid_dim
        self.n_heads = n_heads

        # d_model // h 仍然是要能整除，换个名字仍然意义不变
        assert hid_dim % n_heads == 0

        self.w_q = nn.Linear(s_dim, hid_dim)
        self.w_k = nn.Linear(s_dim, hid_dim)
        self.w_v = nn.Linear(s_dim, hid_dim)

        self.fc = nn.Linear(hid_dim, hid_dim)

        self.scale = torch.sqrt(torch.FloatTensor([hid_dim // n_heads]))

    def forward(self, query, key, value):

        bsz = query.shape[0]

        Q = self.w_q(query)
        K = self.w_k(key)
        V = self.w_v(value)

        Q = Q.view(bsz, -1, self.n_heads, self.hid_dim //
                   self.n_heads).permute(0, 2, 1, 3)
        K = K.view(bsz, -1, self.n_heads, self.hid_dim //
                   self.n_heads).permute(0, 2, 1, 3)
        V = V.view(bsz, -1, self.n_heads, self.hid_dim //
                   self.n_heads).permute(0, 2, 1, 3)

        energy = torch.matmul(Q, K.permute(0, 1, 3, 2)) / self.scale

        attention = torch.softmax(energy, dim=-1)

        x = torch.matmul(attention, V)

        x = x.permute(0, 2, 1, 3).contiguous()

        x = x.view(bsz, -1, self.n_heads * (self.hid_dim // self.n_heads))[:,0,:]

        x = self.fc(x)

        return x

class AttentionPolicy(nn.Module):
    """
    Attention policy network
    """
    def __init__(self, input_dim, out_dim, hidden_dim=256, nonlin=F.leaky_relu,
                 norm_in=True, onehot_dim=0, attend_heads=4):
        """
        Inputs:
            sa_sizes (list of (int, int)): Size of state and action spaces per
                                          agent
            hidden_dim (int): Number of hidden dimensions
            norm_in (bool): Whether to apply BatchNorm to input
            attend_heads (int): Number of attention heads to use (use a number
                                that hidden_dim is divisible by)
        """
        super(AttentionPolicy, self).__init__()
        assert (hidden_dim % attend_heads) == 0
        self.sa_sizes = [input_dim, out_dim]
        self.nagents = 859
        self.attend_heads = attend_heads

        self.obs_dim = input_dim
        self.hidden_dim = hidden_dim

        self.attention = SelfAttention(input_dim, hidden_dim ,attend_heads)

        # self.l1 = nn.Linear(hidden_dim, hidden_dim)
        # self.n1 = nn.LeakyReLU()
        self.l1 = nn.Linear(hidden_dim, out_dim)

        self.norm_in = norm_in

        if norm_in:

            self.query_bn = nn.BatchNorm1d(input_dim,affine=False)
            self.key_bn = nn.BatchNorm1d(input_dim, affine=False)
            self.value_bn = nn.BatchNorm1d(input_dim, affine=False)

        '''
        self.query_encoder = nn.Sequential()

        if norm_in:
            self.state_encoder.add_module('s_enc_bn', nn.BatchNorm1d(

        self.query_encoder.add_module('q_enc_fc1', nn.Linear(sdim,
                                                        hidden_dim))
        self.query_encoder.add_module('q_enc_nl', nn.LeakyReLU())
        self.query_encoder.add_module('q_enc_fc2', nn.Linear(hidden_dim, hidden_dim))

        self.key_encoder = nn.Sequential()
        self.key_encoder.add_module('k_fc1', nn.Linear(s_dim,
                                                    hidden_dim))
        self.key_encoder.add_module('k_nl', nn.LeakyReLU())
        self.key_encoder.add_module('k_fc2', nn.Linear(hidden_dim, hidden_dim))

        self.value_encoder = nn.Sequential()

        if norm_in:
            self.critic_encoder.add_module('enc_bn', nn.BatchNorm1d(idim,
                                                        affine=False))

        self.value_encoder.add_module('v_fc1', nn.Linear(sdim, hidden_dim))
        self.value_encoder.add_module('v_nl', nn.LeakyReLU())

        attend_dim = hidden_dim // attend_heads
        self.key_extractors = nn.ModuleList()
        self.selector_extractors = nn.ModuleList()
        self.value_extractors = nn.ModuleList()
        for i in range(attend_heads):
            self.key_extractors.append(nn.Linear(hidden_dim, attend_dim, bias=False))
            self.selector_extractors.append(nn.Linear(hidden_dim, attend_dim, bias=False))
            self.value_extractors.append(nn.Sequential(nn.Linear(hidden_dim,
                                                                attend_dim),
                                                       nn.LeakyReLU()))
        '''

    def forward(self, obs):

        if self.norm_in:
            query_in = []
            key_in = []
            value_in = []
            query_5obs, key_5obs, value_5obs = [], [], []
            for a_i in range(self.nagents):

                obs[a_i] = torch.tensor(obs[a_i]).float()

                try:
                    query_in.append(self.query_bn(obs[a_i]))
                    key_in.append(self.key_bn(obs[a_i]))
                    value_in.append(self.value_bn(obs[a_i]))
                except:
                    import pdb
                    pdb.set_trace()

            for a_i in range(self.nagents):
                query_5obs.append(torch.stack([query_in[i] for i in cloest[a_i]]))
                key_5obs.append(torch.stack([key_in[i] for i in cloest[a_i]]))
                value_5obs.append(torch.stack([value_in[i] for i in cloest[a_i]]))
            query = torch.stack(query_5obs).permute(0,2,1,3).reshape((-1, 5, self.obs_dim))
            key = torch.stack(key_5obs).permute(0,2,1,3).reshape((-1, 5, self.obs_dim))
            value = torch.stack(value_5obs).permute(0,2,1,3).reshape((-1, 5, self.obs_dim))
        else:
            curr_5obs = []
            for a_i in range(self.nagents):
                curr_5obs.append([obs[i] for i in cloest[a_i]])

            obs = np.array(curr_5obs).transpose(0,2,1,3).reshape((-1, 5, self.obs_dim))
            obs = torch.tensor(obs).float()
            query, key, value = obs, obs, obs

        h1 = self.attention(query,key,value)
        out = self.l1(F.leaky_relu(h1))

        return out

class BasePolicy(nn.Module):
    """
    Base policy network
    """
    def __init__(self, input_dim, out_dim, hidden_dim=64, nonlin=F.leaky_relu,
                 norm_in=True, onehot_dim=0):
        """
        Inputs:
            input_dim (int): Number of dimensions in input
            out_dim (int): Number of dimensions in output
            hidden_dim (int): Number of hidden dimensions
            nonlin (PyTorch function): Nonlinearity to apply to hidden layers
        """
        super(BasePolicy, self).__init__()

        if norm_in:  # normalize inputs
            self.in_fn = nn.BatchNorm1d(input_dim, affine=False)
        else:
            self.in_fn = lambda x: x

        self.fc1 = nn.Linear(input_dim + onehot_dim, hidden_dim)
        self.fc2 = nn.Linear(hidden_dim, hidden_dim)
        self.fc3 = nn.Linear(hidden_dim, out_dim)
        self.nonlin = nonlin

    def forward(self, X):
        """
        Inputs:
            X (PyTorch Matrix): Batch of observations (optionally a tuple that
                                additionally includes a onehot label)
        Outputs:
            out (PyTorch Matrix): Actions
        """

        onehot = None
        if type(X) is tuple:
            X, onehot = X
        inp = self.in_fn(X)  # don't batchnorm onehot
        if onehot is not None:
            inp = torch.cat((onehot, inp), dim=1)
        h1 = self.nonlin(self.fc1(inp))
        h2 = self.nonlin(self.fc2(h1))
        out = self.nonlin(self.fc3(h2))
        return out

class DiscretePolicy(AttentionPolicy):
    """
    Policy Network for discrete action spaces
    """
    def __init__(self, *args, **kwargs):
        super(DiscretePolicy, self).__init__(*args, **kwargs)

    def forward(self, obs, sample=True, return_all_probs=False,
                return_log_pi=False, regularize=False,
                return_entropy=False):
        out = super(DiscretePolicy, self).forward(obs)
        probs = F.softmax(out, dim=1)
        on_gpu = next(self.parameters()).is_cuda
        if sample:
            int_act, act = categorical_sample(probs, use_cuda=on_gpu)
        else:
            act = onehot_from_logits(probs)
        rets = [act]
        if return_log_pi or return_entropy:
            log_probs = F.log_softmax(out, dim=1)
        if return_all_probs:
            rets.append(probs)
        if return_log_pi:
            # return log probability of selected action
            rets.append(log_probs.gather(1, int_act))
        if regularize:
            rets.append([(out**2).mean()])
        if return_entropy:
            rets.append(-(log_probs * probs).sum(1).mean())
        if len(rets) == 1:
            return rets[0]
        return rets


import random

def countingSort(array):
    countArray = []
    finalArray = []
    tempTala = 0

    # Find Maximum Number
    for tala in array:
        if tala > tempTala:
            tempTala = tala

    # Create Empty Array Large As Biggest Number
    for x in range(0,tempTala+1):
        countArray.append(0)

    # Count into array
    for x in array:
        countArray[x] = countArray[x] + 1

    print(countArray)

    # Move From Count Array Into Return Array
    for x in range(0, len(countArray)):
        for z in range(0, countArray[x]):
            finalArray.append(x)

    return finalArray

tala = []
for x in range(0,5):
    tala.append(random.randint(1,15))
print(tala)
print(countingSort(tala))


import pygame
from agent import Agent
from spritesheet import SpriteSheet
from enum import Enum
from fsm import State,Transition,FSM
from common import Directions, ALPHA

# ENEMY STATES
class Event(Enum):
    IDLE = 1,
    WALK = 2,
    DIE = 3

# | ENEMY IDLE STATE
class Idle(State):
    def __init__(self) -> None:
        super().__init__(self.__class__.__name__)

    # stop enemy
    def update(self, object, dir):
        object.stop()

    # getting idle sprite
    def get_xy(self, dir, walking_pointer):
        walking_pointer = 0
        if dir == Directions.LEFT:
            frameX, frameY = (1, 0)
        elif dir == Directions.RIGHT:
            frameX, frameY = (1, 1)
        return frameX, frameY, walking_pointer

# | ENEMY WALK STATE
class Walk(State):
    # walking sprite coords
    WALKING =   [(0, 1), #walk-0
                (1, 1),  #walk-1
                (2, 1),  #walk-2
                (1, 1)]  #walk-3
    WALKING_R = [(0, 0), #walk-0
                (1, 0),  #walk-1
                (2, 0),  #walk-2
                (1, 0)]  #walk-3

    def __init__(self) -> None:
        super().__init__(self.__class__.__name__)

    # move enemy
    def update(self, object, dir):
        if dir==Directions.LEFT:
            object.move(Directions.LEFT, change_x = 1)
        else:
            object.move(Directions.RIGHT, change_x = 1)

    # getting walking sprite
    def get_xy(self, dir, walking_pointer):
        if dir == Directions.LEFT:
            frameX, frameY = self.WALKING_R[int(walking_pointer)]
        elif dir == Directions.RIGHT:
            frameX, frameY = self.WALKING[int(walking_pointer)]
        walking_pointer = (walking_pointer + 0.2) % len(self.WALKING)
        return frameX, frameY, walking_pointer

# | ENEMY DIE STATE
class Die(State):
    # dead sprite coords
    DEAD = (3,0)
    DEAD_R = (3,1)

    def __init__(self) -> None:
        super().__init__(self.__class__.__name__)

    # kill enemy
    def update(self, object, dir):
        if object.dead:
            return
        object.kill()
        return object.stop()

    # getting dead sprite
    def get_xy(self,dir):
        if dir == Directions.LEFT:
            frameX, frameY = self.DEAD
        if dir == Directions.RIGHT:
            frameX, frameY = self.DEAD_R
        return frameX, frameY

STATES = [Idle, Walk, Die]

TRANSITIONS = {
    Event.IDLE: [
        Transition(Walk, Idle)],
    Event.WALK: [Transition(Idle, Walk)],
    Event.DIE: [
        Transition(Idle, Die),
        Transition(Walk, Die)
    ]
}

class Enemy(Agent):
    def __init__(self, name, width, height, scale, direction) -> None:
        super().__init__(name, width, height, scale, direction)
        self.width = width
        self.height = height
        self.scale = scale
        self.name = name
        self.direction_auto = self.direction

        # state machine responsible for tux in big fsm or mini fsm
        self.fsm = FSM(STATES, TRANSITIONS)

    def clone(self):
        return NotImplemented

    def is_smashable(self):
        return 1

    # move enemy automatically
    def commands(self, is_dead):
        if is_dead:
            self.fsm.update(Event.DIE, self)
        else:
            self.fsm.update(Event.WALK, self, dir=self.direction)
        return None

    # verify collisions and update sprite and state if needed
    def collisions(self):
        # See if we hit anything
        idle, _, _ = super().collisions()

        #making sure that monster changes to idle when he lands on the ground and does not move
        if idle:
            self.fsm.update(Event.IDLE, self)

    # update sprite based on state
    def update(self):
        # Get body
        x, y = self.rect.x, self.rect.y

        current_state = self.fsm.get_cstate()()

        # update direction
        if self.direction != self.direction_auto:
            self.direction = self.direction_auto

        if isinstance(current_state, Walk):
            #enemy is walking
            frameX, frameY, self.walking_pointer = current_state.get_xy(self.direction, self.walking_pointer)
        elif isinstance(current_state, Idle):
            #enemy is idle
            frameX, frameY, self.walking_pointer = current_state.get_xy(self.direction, self.walking_pointer)
        elif isinstance(current_state, Die):
            #enemy is dead
            frameX, frameY= current_state.get_xy(dir=self.direction)

        super().update(x,y,frameX,frameY,cell_size=(self.cellsize,self.cellsize))

class Snowball(Enemy):
    def __init__(self, initial_x, initial_y, width, height, scale, direction=Directions.LEFT) -> None:
        super().__init__("Snowball", width, height, scale, direction)
        # load snowball spritesheet
        self.sheet = SpriteSheet("assets/creatures/spritesheet_snowball.png")
        self.cellsize = 50
        frameX, frameY = (1, 0)
        self.image = self.sheet.image_at((frameX * self.cellsize, frameY * self.cellsize, self.cellsize, self.cellsize), colorkey=ALPHA)
        self.rect = self.image.get_rect()

        self.set_start_position(initial_x, initial_y) #set player initial  position

    def clone(self, initial_x, initial_y, direction) -> Enemy:
        return Snowball(initial_x, initial_y, self.width, self.height, self.scale, direction)

    def is_smashable(self):
        return 1

class Spiky(Enemy):
    def __init__(self, initial_x, initial_y, width, height, scale, direction=Directions.LEFT) -> None:
        super().__init__("Spiky", width, height, scale, direction)
        # load snowball spritesheet
        self.sheet = SpriteSheet("assets/creatures/spritesheet_spiky.png")
        self.cellsize = 50
        frameX, frameY = (1, 0)
        self.image = self.sheet.image_at((frameX * self.cellsize, frameY * self.cellsize, self.cellsize, self.cellsize), colorkey=ALPHA)
        self.rect = self.image.get_rect()

        self.set_start_position(initial_x, initial_y) #set player initial  position

    def clone(self, initial_x, initial_y, direction) -> Enemy:
        return Spiky(initial_x, initial_y, self.width, self.height, self.scale, direction)

    def is_smashable(self):
        return 0

class Spawner:
    def spawn_enemy(self, prototype, initial_x, initial_y, is_right=0) -> Enemy:
        if is_right:
            return prototype.clone(initial_x, initial_y, Directions.RIGHT)
        return prototype.clone(initial_x, initial_y, Directions.LEFT)


from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
from urllib.parse import quote_plus
import requests
import pandas as pd

def search(query, num_results=50, lang='en', timerange=None):
    '''Return a dataframe containing Google search results

    Keyword arguments:
    query -- search parameters (string)
    num_results -- the number of results to search (int)
    lang -- language code (string)
    timerange -- tuple containing two years to search between.
                    if none, then no query for year is made

    '''
    root = 'https://www.google.com/search?q='
    search = quote_plus(query)
    if timerange:
        begin = min(timerange)
        end = max(timerange)
        timestring = f'&tbs=cdr%3A1%2Ccd_min%3A{begin}%2Ccd_max%3A{end}'
    else:
        timestring = ''
    link = f'{root}{search}&num={str(num_results)}&hl={lang}{timestring}'
    usr_agent = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
        'Chrome/61.0.3163.100 Safari/537.36'
    }
    req = Request(link, headers=usr_agent)
    webpage = urlopen(req).read()
    return get_data(BeautifulSoup(webpage, 'html.parser'))

def get_data(soup):
    ''' Return a dataframe containing parsed search results

    Keyword arguments:
    soup -- a bs4 soup object representing the Google page

    '''
    result_block = soup.find_all('div', attrs={'class': 'g'})
    df_dict = {
        "title": [],
        "description": [],
        "link": []
    }
    for result in result_block:
        if(len(result['class']) != 1):
            continue
        link = result.find('a', href=True)
        title = result.find('h3')
        desc = result.find('span', attrs={'class': None})
        if link and title and desc:
            df_dict["title"].append(title.text)
            df_dict["description"].append(desc.text)
            df_dict["link"].append(link['href'])
    return pd.DataFrame(df_dict)

df = search('africa', lang='en')
df.to_csv('test.csv', index=False)


import numpy as np
from skimage import measure
import os
from PIL import Image
import numpy as np
import cv2
import matplotlib.pyplot as plt
# rle masks.
b_mask_path = "D:\\work\\nuclear segment\\dateset_train\\nucleus\\train\\tnbc\\Labels_png_01"
masks = os.listdir(b_mask_path)

#基于cv2
#基于连通区域获取bbox&&area
def mask2bbox(binary_mask,filename):
    mask = Image.open(os.path.join(b_mask_path,filename))
    binary_mask = np.array(mask, np.uint8)
    contours,hierarchy = cv2.findContours(
        binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    areas = []
    bounding_boxs = []
    for cnt in contours:
        area = cv2.contourArea(cnt)
        areas.append(area)
    # 取最大面积的连通区域
    #idx = areas.index(np.max(areas))
        #计算cnt的bbox
        x, y, w, h = cv2.boundingRect(cnt)
        bounding_box = [x, y, x+w, y+h]
        bounding_boxs.append(bounding_box)
    return bounding_boxs

#获取的bbox显示在原图上
def img_show(bounding_boxs,filename):
    image = cv2.imread(os.path.join(b_mask_path,filename))
    for i in bounding_boxs:
        cv2.rectangle(image, (i[0], i[1]), (i[2], i[3]), (0, 0, 255),2)
    cv2.imshow(str(_), image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    print("#################################")

def close_contour(contour):
    if not np.array_equal(contour[0], contour[-1]):
        contour = np.vstack((contour, contour[0]))
    return contour

#从二值图用Douglas-Peucker algorithm获取坐标
def binary_mask_to_polygon(binary_mask, tolerance=0):
    """Converts a binary mask to COCO polygon representation

    Args:
        binary_mask: a 2D binary numpy array where '1's represent the object
        tolerance: Maximum distance from original points of polygon to approximated
            polygonal chain. If tolerance is 0, the original coordinate array is returned.

    """
    polygons = []
    # pad mask to close contours of shapes which start and end at an edge
    padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
    contours = measure.find_contours(padded_binary_mask, 0.5)
    contours = np.subtract(contours, 1)
    #fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(9, 4))
    #plt.gray()
    #ax2.imshow(binary_mask)
    for contour in contours:
        contour = close_contour(contour)
        contour = measure.approximate_polygon(contour, tolerance)
        #ax2.plot(contour[:, 1], contour[:, 0], '-r', linewidth=2)
        #plt.show()
        if len(contour) < 3:
            continue
        contour = np.flip(contour, axis=1)
        segmentation = contour.ravel().tolist()
        # after padding and subtracting 1 we may get -0.5 points in our segmentation
        segmentation = [0 if i < 0 else i for i in segmentation]
        polygons.append(segmentation)

    return polygons

#将坐标整理为x，y
def binary_mask_to_xy(binary_mask):
    polygons = binary_mask_to_polygon(binary_mask, tolerance=2)

    #each cell
    x=[]
    y=[]
    for polygon in polygons:
        xs = []
        ys = []
        for tdx in range(0, len(polygon), 2):
            xs.append(polygon[tdx])
            ys.append(polygon[tdx + 1])
        x.append(xs)
        y.append(ys)

    return x, y

bounding_boxs = []
k=0
for _ in masks:
    box=[]
    print(str(_))
    mask = Image.open(os.path.join(b_mask_path,_))

    binary_mask = np.array(mask, np.uint8)
    boxes=mask2bbox(binary_mask,_)
    #img_show(boxes,_)
    #binary_mask_to_polygon(binary_mask,0)
    x, y = binary_mask_to_xy(binary_mask)
    if len(x) < 1 or len(y) < 1:
        continue
    # left, top, right, bottom

    for i,j in zip(x,y):
        box.append([int(min(i)), int(min(j)), int(max(i)), int(max(j))])
    bounding_boxs.append(box)
    img_show(bounding_boxs[k],_)
    k+=1

for _,j in zip(range(len(bounding_boxs)),masks):
    #cv2.destroyAllWindows()
    img_show(bounding_boxs[_],j)


lista1=[]
lista2=[]
num=0

print("Ingrese números para crear una lista. Termina ingresando un número negativo")
num=int(input("Número: "))
while num>= 0:
    lista1.append(num)
    num=int(input("Ingrese un número: "))
print("Lista ingresada: ",lista1)
for num in lista1:
    if num not in lista2:
        lista2.append(num)

print("Nueva lista: ",lista2)


import sys
import math
import utils
import sounddevice as sd
import matplotlib.pyplot as plt

def main():

    input("Pressione enter para gravar a música")

    # gerador do tom
    frequencies = (CONFIG.TONS[digit][0], CONFIG.TONS[digit][1])
    time_array, tone_array = utils.build_tone(
        frequencies,
        CONFIG.AMPLITUDE,
        CONFIG.TRANSMIT_TIME,
        CONFIG.SAMPLE_RATE
    )

    sd.play(tone_array, CONFIG.SAMPLE_RATE)
    sd.wait()

    # Exibe gráficos
    frequencies, intensities = utils.calculate_fft(tone_array, CONFIG.SAMPLE_RATE)
    plt.show()
    plt.figure(figsize=(12,4))
    plt.subplot(1,2,1)
    plt.plot(time_array[:200], tone_array[:200])
    plt.title('Sinal')
    plt.ylabel('Amplitude')
    plt.xlabel('Tempo (s)')
    plt.grid(True)
    plt.subplot(1,2,2)
    plt.plot(frequencies, intensities)
    plt.title('Transformada de Fourier')
    plt.xlabel('Frequência (Hz)')
    plt.ylabel('Intensidade')
    plt.xlim(0, max(CONFIG.FREQUENCIAS) * 2)
    plt.grid(True)
    plt.show()

if __name__ == "__main__":
    main()


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection

def hyperbolic_paraboloid():
    ax = plt.axes(projection='3d')
    x = np.linspace(-1, 1, 30)
    y = np.linspace(-1, 1, 30)
    X, Y = np.meshgrid(x, y)           # make a mesh, a 2D array, and assign 2D arrays to X and Yprn
    a, b = 1, 1
    Z = X*X/a - Y*Y/b                  # make a 2D array and assign it to Z

    # plot and show
    ax.contour3D(X, Y, Z, 50)
    ax.set_title('Hyperbolic Paraboloid')
    plt.show()

def elliptic_paraboloid():
    ax = plt.axes(projection='3d')

    # create 2d meshgrid (plane)
    x = np.linspace(-1, 1, 30)
    y = np.linspace(-1, 1, 30)
    X, Y = np.meshgrid(x, y)

    # equation of z-height
    a, b = 1, 1
    Z = (a * X**2) + (b * Y**2)

    # plot and show
    ax.contour3D(X, Y, Z, 50)
    ax.set_title('Elliptic Paraboloid')
    plt.show()

def hyperbolic_hyperboloid():
    ax = plt.axes(projection='3d')

    # create parametric meshgrid
    t = np.linspace(0, 2*np.pi, 30)
    v = np.linspace(-1, 1, 30)
    T, V = np.meshgrid(t, v)

    # parametric equations for hyperboloid
    a, b, c = 1, 1, 1
    X = a*np.cosh(V)*np.cos(T)
    Y = b*np.cosh(V)*np.sin(T)
    Z = c*np.sinh(V)

    # plot and show
    ax.contour3D(X, Y, Z, 50)
    ax.set_title('Hyperbolic Hyperboloid')
    plt.show()

def elliptic_hyperboloid():
    ax = plt.axes(projection='3d')

    # create parametric meshgrid
    t = np.linspace(0, 2*np.pi, 30)
    v = np.linspace(-2, 2, 30)
    T, V = np.meshgrid(t, v)
    a, b = 1, 1

    # Top sheet coordinates
    X = a*np.sinh(V)*np.cos(T)
    Y = a*np.sinh(V)*np.sin(T)
    Z = b*np.cosh(V)

    # Bottom sheet coordinates
    X2 = -a*np.sinh(V)*np.cos(T)
    Y2 = -a*np.sinh(V)*np.sin(T)
    Z2 = -b*np.cosh(V)

    # plot and show
    ax.contour3D(X, Y, Z, 50)
    ax.contour3D(X2, Y2, Z2, 50)
    ax.set_title('Elliptic Hyperboloid')
    plt.show()

def sphere():
    ax = plt.axes(projection='3d')

    # create parametric meshgrid
    t = np.linspace(0, 2*np.pi, 30)
    v = np.linspace(0, np.pi, 30)
    T, V = np.meshgrid(t, v)
    a, b, c = 1, 1, 1

    # parametric equations for sphere
    X = a*np.cos(T)*np.sin(V)
    Y = b*np.sin(T)*np.sin(V)
    Z = c*np.cos(V)

    # plot and show
    ax.contour3D(X, Y, Z, 50)
    ax.set_title('Sphere')
    plt.show()

def cone():
    ax = plt.axes(projection='3d')

    # create meshgrid
    h = 1
    r = 1
    v = np.linspace(0, h, 30)
    t = np.linspace(0, 2*np.pi, 30)
    V, T = np.meshgrid(v, t)

    # parametric equations for cone
    X = (h - V)/h * r*np.cos(T)
    Y = (h - V)/h * r*np.sin(T)
    Z = V

    # plot and show
    ax.contour3D(X, Y, Z, 50)
    ax.set_title('Cone')
    plt.show()

def square_pyramid():
    ax = plt.axes(projection='3d')

    h = 1
    b = 1

    x = [b, b, -b, -b, 0]
    y = [b, -b, b, -b, 0]
    z = [0, 0, 0, 0, h]

    ax.plot_trisurf(x, y, z)
    ax.set_title('Square Pyramid')
    plt.show()

def parallelepiped():
    points = np.array([[-1, -1, -1], [1, -1, -1 ], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1 ], [1, 1, 1], [-1, 1, 1]])

    P = [[2.06498904e-01 , -6.30755443e-07 ,  1.07477548e-03],
    [1.61535574e-06 ,  1.18897198e-01 ,  7.85307721e-06],
    [7.08353661e-02 ,  4.48415767e-06 ,  2.05395893e-01]]

    Z = np.zeros((8,3))
    for i in range(8): Z[i,:] = np.dot(points[i,:],P)
    Z = 10.0*Z

    ax = plt.axes(projection='3d')

    # plot vertices
    ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2])

    # list of sides' polygons of figure
    verts = [[Z[0],Z[1],Z[2],Z[3]],
    [Z[4],Z[5],Z[6],Z[7]],
    [Z[0],Z[1],Z[5],Z[4]],
    [Z[2],Z[3],Z[7],Z[6]],
    [Z[1],Z[2],Z[6],Z[5]],
    [Z[4],Z[7],Z[3],Z[0]]]

    # plot sides
    ax.add_collection3d(Poly3DCollection(verts, linewidths=1, edgecolors='black'))

    plt.show()

if __name__ == '__main__':
    hyperbolic_paraboloid()
    elliptic_paraboloid()
    hyperbolic_hyperboloid()
    elliptic_hyperboloid()
    sphere()
    cone()
    square_pyramid()
    parallelepiped()


from bs4 import BeautifulSoup
import os
import pandas as pd
import glob
import datetime

if not os.path.exists("parsed_files"):
	os.mkdir("parsed_files")

df = pd.DataFrame()

for one_file_name in glob.glob("deep_link_html/*.html"):
	print("parsing: ",one_file_name)
	scraping_time = os.path.basename(one_file_name)
	f = open(one_file_name, "r")
	soup = BeautifulSoup(f.read(), 'html.parser')
	f.close()
	daily_table = soup.find(id='table')
	daily_rows = daily_table.find_all("tr")
	page_date = soup.find("div", {"class":"a-section a-spacing-none"}).find("h1").text.replace("Domestic Box Office For ","").replace(",","")
	formatted_date = datetime.datetime.strptime(page_date, '%b %d %Y').strftime('%m/%d/%Y')
	for r in daily_rows[1:]:
		boxoffice_date = formatted_date
		movie_links = r.find("a", {"class":"a-link-normal"})["href"]
		movie_name = r.find("td", {"class":"a-text-left mojo-field-type-release mojo-cell-wide"}).find("a").text
		movie_dailygross = r.find("td", {"class":"a-text-right mojo-field-type-money mojo-estimatable"}).text.replace(",","").replace("$","")
		movie_theaters = r.find("td", {"class":"a-text-right mojo-field-type-positive_integer mojo-estimatable"}).text.replace(",","")
		movie_grosstodate = r.find_all("td", {"class":"a-text-right mojo-field-type-money mojo-estimatable"})[2].text.replace(",","").replace("$","")
		# movie_daynumber = r.find("td", {"class":"a-text-right mojo-field-type-positive_integer"}).text
		days_number = r.find_all("td", {"class":"a-text-right mojo-field-type-positive_integer"})
		movie_daynumber = days_number[1].text
		movie_distributor = r.find("td", {"class": "a-text-left mojo-field-type-release_studios"}).text

		df = df.append({  # df=data frame ( = put argumet, { = list of stuff
				'Date':boxoffice_date,
				'movie name':movie_name,
				'daily box office':movie_dailygross,
				'theaters': movie_theaters,
				'gross box office to date':movie_grosstodate,
				'number of days in release':movie_daynumber,
				'distributor': movie_distributor,
				'movie_links ': movie_links

			}, ignore_index=True)
# 	# except:
# 	# 	pass

df.to_csv("parsed_files/movie_deeplinks.csv")


import abc, sys
import pygame, cv2, os
import numpy as np

from game.models import GameState, Grid
import frontend.palette as palette
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from frontend.button import Button

def round_number(number: int):
    if number % 2:
        return number/2
    return (number + 1)/2

class Renderer():

    def get_font(self, name, size):
        font_file = os.path.join('font', name + '.ttf')

        return pygame.font.Font("font/font.ttf", size)

    def draw_board(self, screen, board_size=15, cell_size=45):
        for i in range(1, board_size + 1):
            pygame.draw.line(screen, palette.BLACK, [cell_size * i, cell_size], [cell_size * i, cell_size*15], 2)
            pygame.draw.line(screen, palette.BLACK, [cell_size, cell_size * i], [cell_size*15, cell_size * i], 2)

        pygame.draw.circle(screen, palette.BLACK, [cell_size * 8, cell_size * 8], 5)
        pygame.draw.circle(screen, palette.BLACK, [cell_size * 4, cell_size * 4], 5)
        pygame.draw.circle(screen, palette.BLACK, [cell_size * 12, cell_size * 4], 5)
        pygame.draw.circle(screen, palette.BLACK, [cell_size * 4, cell_size * 12], 5)
        pygame.draw.circle(screen, palette.BLACK, [cell_size * 12, cell_size * 12], 5)
        pygame.display.update()

    def board_to_grid(screen, x_pos, y_pos, cell_size):
        if x_pos % cell_size > round_number(x_pos):
            x_pos = (x_pos - x_pos % cell_size) + cell_size
        else:
            x_pos = x_pos - x_pos % cell_size

        if y_pos % cell_size > round_number(y_pos):
            y_pos = (y_pos - y_pos % cell_size) + cell_size
        else:
            y_pos = y_pos - y_pos % cell_size

        return x_pos, y_pos

    def draw_grid(self, screen, grid: Grid, cell_size: int) -> None:
        for row in range(grid.BOARD_SIZE):
            for col in range(grid.BOARD_SIZE):
                if grid.cells[row, col] == 1:
                    pygame.draw.circle(screen, palette.BLACK, [cell_size * (col + 1), cell_size * (row + 1)], cell_size//2)
                elif grid.cells[row, col] == 2:
                    pygame.draw.circle(screen, palette.WHITE, [cell_size * (col + 1), cell_size * (row + 1)], cell_size//2)
        update_rect = pygame.Rect(0, 0, cell_size * (grid.BOARD_SIZE + 1), cell_size * (grid.BOARD_SIZE + 1))
        pygame.display.update(update_rect)

    def drawArcCv2(self, surf, color, center, radius, width, start_angle, end_angle):
        circle_image = np.zeros((radius * 2 + 4, radius * 2 + 4, 4), dtype=np.uint8)
        circle_image = cv2.ellipse(circle_image, (radius + 2, radius + 2),
                                  (radius - width // 2, radius - width // 2), 0, start_angle, end_angle,
                                  (*color, 255), width, lineType=cv2.LINE_AA)
        circle_surface = pygame.image.frombuffer(circle_image.flatten(), (radius * 2 + 4, radius * 2 + 4), 'RGBA')
        surf.blit(circle_surface, circle_surface.get_rect(center=center),
                  special_flags=pygame.BLEND_PREMULTIPLIED)

    def draw_score(self, player1_score, player2_score, screen,current_player=1, board_size=15, cell_size=45):

        y_center = screen.get_height() // 2

        p1_center = cell_size * board_size + cell_size
        p1_score_center = cell_size * board_size + (screen.get_width() - cell_size * board_size) // 2
        if current_player == 1:
            p1_color = palette.RED
        else:
            p1_color = palette.BLACK
        p1_text = self.get_font("Roboto-Medium", 20).render("Player 1", True, p1_color)
        screen.blit(p1_text, (p1_center, y_center - cell_size * 2))

        # Draw Player 1 score
        score_font = pygame.font.Font(None, 45)
        p1_score_text = score_font.render(str(player1_score), True, palette.BLACK)
        p1_rect = pygame.Rect(45*17 + 5, 45*7 - 13, 50, 50)
        screen.fill(palette.BOARD_COLOR, p1_rect)
        screen.blit(p1_score_text, (p1_score_center, y_center - cell_size - 1))

        # Draw "Player 2" text
        if current_player == 2:
            p2_color = palette.RED
        else:
            p2_color = palette.WHITE
        p2_text = self.get_font("Roboto-Medium", 20).render("Player 2", True, p2_color)
        screen.blit(p2_text, (p1_center, y_center + cell_size * 2 - 20))

        # Draw Player 2 score
        p2_score_text = score_font.render(str(player2_score), True, palette.WHITE)
        screen.blit(p2_score_text, (p1_score_center, y_center + cell_size - 20))

        pygame.display.flip()

    def display_total_time(self, screen, total_time, curr_stone):
        if total_time < 0:
            total_time = 0
        minutes = total_time // 60
        seconds = total_time % 60
        if minutes > 99:
            minutes = 99
            seconds = 59
        time_string = f"{minutes:02d}:{seconds:02d}"
        time_surf = pygame.font.Font(None, 30).render(time_string, True, palette.BLACK)
        if curr_stone == 1:
            time_rect = time_surf.get_rect(center=(45*15 + 113, 45*5))
        else:
            time_rect = time_surf.get_rect(center=(45*15 + 113, 45*11 + 10))

        screen.blit(time_surf, time_rect)


import socket
IP = '172.23.176.14'
PORT = 40000
max_msg_size = 1024

max_msg_size = max_msg_size

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((IP, PORT))

print('client online')

while True:
    received_msg = sock.recv(max_msg_size)
    decoded_msg = received_msg.decode('utf-8')
    print(f'\t\t @server: {decoded_msg}')
    if decoded_msg == 'Quit':
        break
    else:
        sending_msg = input()
        encoded_msg = sending_msg.encode('utf-8')
        sock.send(encoded_msg)
        if encoded_msg == 'Quit':
            break
sock.close()


# -*- coding: windows-1250 -*-

alfabet = 'a¹bcædeêfghijkl³mnñoóprsœtuwyzŸ¿'

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

def slownik_szyfrujacy():
    litery = [x for x in alfabet]
    wykodowane = [alfabet[indeks:] + alfabet[:indeks] for indeks in range(len(alfabet))]
    slownik = {litera: kodowanie for litera, kodowanie in zip(litery, wykodowane)}
    return slownik

def ceasar(slowo, klucz):
    szyfrowanie = slownik_szyfrujacy()
    szyfrogram = ''
    slowo = slowo.lower()

    for litera in slowo:
        szyfrogram += szyfrowanie[litera][klucz]

    return szyfrogram

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

slowo = 'Labladolek'
klucz = 9

print(ceasar(slowo, klucz))


from rest_framework.exceptions import ValidationError
from rest_framework.fields import HiddenField, CurrentUserDefault
from rest_framework.serializers import ModelSerializer

from api.models import Favorite
from api.models import Purchase
from api.models import Subscription
from recipes.models import Ingredient

def validate_author(data):
    if data.get('author') == data.get('user'):
        raise ValidationError('Нельзя подписаться на самого себя')
    return data

class IngredientSerializer(ModelSerializer):
    class Meta:
        fields = ('title', 'dimension')
        model = Ingredient

class SubscriptionSerializer(ModelSerializer):
    user = HiddenField(default=CurrentUserDefault())

    class Meta:
        fields = ('author', 'user')
        model = Subscription
        validators = (validate_author, )

class FavoriteSerializer(ModelSerializer):
    class Meta:
        fields = ('recipe',)
        model = Favorite

class PurchaseSerializer(ModelSerializer):
    class Meta:
        fields = ('recipe',)
        model = Purchase


from typing import Any, Tuple, Dict, Type, Callable

Bases = Tuple[Type]
Attrs = Dict[str, Callable]

def abstract(func):
    func.__isabstract__ = True
    return func

def absmths(cls, mths):
    cls.__abstractmethods__ = frozenset(mths)

class Abstract(type):
    def __new__(mcls, clsname: str, bases: Bases, attrs: Attrs) -> Any:
        cls = super(mcls, mcls).__new__(mcls, clsname, bases, attrs)

        # 類別上定義的抽象方法
        abstracts = {name for name, value in attrs.items()
                       if getattr(value, "__isabstract__", False)}

        # 從父類別中繼承下來的抽象方法
        for parent in bases:
            for name in getattr(parent, "__abstractmethods__", set()):
                value = getattr(cls, name, None)
                if getattr(value, "__isabstract__", False):
                    abstracts.add(name)

        # 指定給 __abstractmethods__
        absmths(cls, abstracts)

        return cls

class AbstractX(metaclass=Abstract):
    @abstract
    def doSome(self):
        pass

# TypeError: Can't instantiate abstract class AbstractX with abstract methods doSome
x = AbstractX()


import sys
sys.stdin = open('sample_input3.txt', 'r')

T = int(input())
for testCase in range(1, T+1) :
    str = list(input())

    toRemove = -1
    while True :
        if toRemove >= 0 :
            str.pop(toRemove)
            str.pop(toRemove)

        toRemove = -1
        for i in range(len(str)-1) :
            if str[i] == str[i+1] :
                toRemove = i

        if toRemove == -1 :
            answer = len(str)
            break

    print('#{0} {1}'.format(testCase, answer))


class Solution:
    def maxSubarraySumCircular(self, nums: List[int]) -> int:
        n = len(nums)

        total = 0
        MAX = currMax = -inf
        MIN = currMin = inf
        for num in nums:
            currMax = max(currMax+num, num)
            MAX = max(MAX, currMax)
            currMin = min(currMin+num, num)
            MIN = min(MIN, currMin)

            total += num
        return max(MAX, total-MIN) if MAX > 0 else MAX

Greedy/918. Maximum Sum Circular Subarray/solution.py