import json
import os

from aws_lambda_powertools.utilities.batch import sqs_batch_processor
from aws_lambda_powertools.utilities.idempotency import (
    DynamoDBPersistenceLayer,
    IdempotencyConfig,
    idempotent_function,
)

persistence_layer = DynamoDBPersistenceLayer(table_name=os.getenv("IDEMPOTENCY_STORE_TABLE_NAME"))

config = IdempotencyConfig(event_key_jmespath="body")

@idempotent_function(data_keyword_argument="record", config=config, persistence_store=persistence_layer)
def record_handler(record):
    print(f"メッセージ毎の処理するよ！{json.dumps(record['body'])}")
    return record

@sqs_batch_processor(record_handler=record_handler)
def handler(event, context):
    print(f"ハンドラーだよ!{json.dumps([x['body'] for x in event['Records']])}")
    return {"statusCode": 200}


import sys
import asyncio
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))).replace("ext/",""))
from utils import *
from .lib import gameclasses

HELP="""\
`ext.game`
```bash
Hey, look away.
This shit is still in development, yo.
```
"""

async def getResponse(self,bot,message,responsecheck):
    uid=message.author.id
    answer = await bot.wait_for_message(
            timeout=15.0,
            author=message.author,
            check=responsecheck
            )
    if answer is None:
        await bot.send_message(
                message.channel,
                "Sorry, I got bored waiting. You'll have to be faster next time."
                )
    return answer

async def digest(message,bot):
    if not (message.channel.name=="botdev" or message.channel.is_private):
        return
    if message.content[0] in bot.commandPrefix:
        user=message.author.id
        tokens=tokenize(message)
        tokens[0]=tokens[0][1:]
		# do stuff here
    return


"""Mailer functions for API"""
import os
from string import Template

import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from app.conf.config import APP_PATH, MAILRELAY, MAIL_PORT, EMAIL_SENDER, APP_URL, COMPANY_INFO

def send_email_api(receiver_email, filename, api_user):
    """ Function that handles mail for API calls """
    subject = "API call Ansible runlog"
    template = os.path.join(APP_PATH, "restapi", "templates", "restapi", "api_email_template.html")
    body_file = open(template)
    body_template = body_file.read()
    # Pass variables into the HTML template
    body = Template(body_template).safe_substitute(curr_user=str(api_user), app_url=str(APP_URL), company_info=str(COMPANY_INFO))
    sender_email = EMAIL_SENDER

    # Create a multipart message and set headers
    message = MIMEMultipart("alternative")
    message["From"] = sender_email
    message["To"] = receiver_email
    message["Subject"] = subject

    # Add body to email
    message.attach(MIMEText(body, "html"))
    body_file.close()

    # Open attachment file in binary mode
    file_path = os.path.join(APP_PATH, "logs", filename)
    with open(file_path, "rb") as attachment:
        # Add file as application/octet-stream
        # Email client can usually download this automatically as attachment
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())

    # Encode file in ASCII characters to send by email
    encoders.encode_base64(part)

    # Add header as key/value pair to attachment part
    part.add_header(
        "Content-Disposition",
        f"attachment; filename= {filename}",
    )

    # Add attachment to message and convert message to string
    message.attach(part)
    text = message.as_string()

    # Send email via mailrelay using SMTP
    with smtplib.SMTP(MAILRELAY, MAIL_PORT) as server:
        server.sendmail(sender_email, receiver_email, text)


'''
    linear programming
    Transportation problem
    Used package: pulp, numpy
'''
import pulp
import numpy as np
from pprint import pprint

def transportation_problem(costs, x_max, y_max):
    '''
    :param costs: an array contains every items cost
    :param x_max: constraint value of x
    :param y_max: constraint value of y
    :return:
    '''

    row = len(costs)
    col = len(costs[0])

    '''
        First, init a problem named "prob", sense means what we want to get, "LpMaximize" means we want a max value
    '''
    prob = pulp.LpProblem('Transportation Problem', sense=pulp.LpMaximize)

    '''
        Second, set constraint value, lowBound means the lowest permitted value, cat means type of value
    '''
    var = [[pulp.LpVariable(f'x{i}{j}', lowBound=0, cat=pulp.LpInteger) for j in range(col)] for i in range(row)]

    '''
        Third, set constraint function
    '''
    flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]

    prob += pulp.lpDot(flatten(var), costs.flatten())

    for i in range(row):
        prob += (pulp.lpSum(var[i]) <= x_max[i])

    for j in range(col):
        prob += (pulp.lpSum([var[i][j] for i in range(row)]) <= y_max[j])

    prob.solve()

    return {'objective':pulp.value(prob.objective), 'var': [[pulp.value(var[i][j]) for j in range(col)] for i in range(row)]}

if __name__ == '__main__':
    costs = np.array([[500, 550, 630, 1000, 800, 700],
                       [800, 700, 600, 950, 900, 930],
                       [1000, 960, 840, 650, 600, 700],
                       [1200, 1040, 980, 860, 880, 780]])

    max_plant = [76, 88, 96, 40] # x
    max_cultivation = [42, 56, 44, 39, 60, 59] # y
    res = transportation_problem(costs, max_plant, max_cultivation)
    pprint(res)
'''
    The output of last line is::
        {'objective': 284230.0,
         'var': [[0.0, 0.0, 6.0, 39.0, 31.0, 0.0],
                 [0.0, 0.0, 0.0, 0.0, 29.0, 59.0],
                 [2.0, 56.0, 38.0, 0.0, 0.0, 0.0],
                 [40.0, 0.0, 0.0, 0.0, 0.0, 0.0]]}

    In this lines, objective means needed value, var means corresponding arguments
'''


from docutils.parsers.rst import Directive, directives
from docutils import nodes
from docutils.core import publish_doctree
from sphinx.errors import SphinxError
import os
import netCDF4
import re

# We store this using a global variable because this much data seems
# to break Sphinx if we store it in an env attribute. (For small
# numbers of parameters config_role an access env via
# inliner.document.settings.env, for larger numbers it cannot.)
pism_data = {}

def make_id(parameter):
    return "config-" + parameter

class config(nodes.literal):
    parameter = None

    def __init__(self, parameter, **kwargs):
        self.parameter = parameter

        nodes.literal.__init__(self, parameter, **kwargs)

# this node makes it possible to add soft hyphens to wrap long parameter names
class softhyphen(nodes.Element):
    pass

def visit_softhyphen_html(self, node):
    self.body.append('')

def depart_softhyphen_html(self, node):
    pass

def visit_softhyphen_latex(self, node):
    self.body.append(r"\-")

def depart_softhyphen_latex(self, node):
    pass

def config_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    """Parse :config:`parameter` roles and create `config` nodes resolved
    in resolve_config_links()."""

    # Warn about misspelled parameters names.
    if text not in pism_data:
        msg = inliner.reporter.error('{}: invalid parameter name'.format(rawtext),
                                     line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]

    name = text

    return [config(name, text=text)], []

class ParameterList(Directive):
    has_content = False
    required_arguments = 0

    option_spec = {"prefix": directives.unchanged,
                   "exclude": directives.unchanged}

    def format_value(self, value, T):
        if T == "string" and len(value) == 0:
            return nodes.emphasis("", "empty")

        if T in ["string", "keyword" ]:
            return nodes.literal(value, value.replace(",", ", "))

        if T in ["number", "integer"]:
            return nodes.Text("{:g}".format(value))

        if T == "flag":
            return nodes.Text(str(value))

    def list_entry(self, name, data):
        "Build an entry for the list of parameters."

        p1 = nodes.paragraph()
        p1 += nodes.target('', '', ids=[make_id(name)])
        p1 += nodes.literal("", name)

        fl = nodes.field_list()

        if True:
            f = nodes.field()
            f += [nodes.field_name("", "Type"),
                  nodes.field_body("", nodes.Text(" " + data["type"]))]
            fl += f

            f = nodes.field()
            value = nodes.paragraph()
            value += self.format_value(data["value"], data["type"])
            if "units" in data:
                value += nodes.emphasis("", " ({})".format(data["units"]))
            f += [nodes.field_name("", "Default value"),
                  nodes.field_body("", value)]
            fl += f

        if "choices" in data:
            choices = self.format_value(data["choices"], "keyword")
            f = nodes.field()
            f += [nodes.field_name("", "Choices"),
                  nodes.field_body("", nodes.paragraph("", "", choices))]
            fl += f

        if "option" in data:
            option = self.format_value("-" + data["option"], "keyword")
            f = nodes.field()
            f += [nodes.field_name("", "Option"),
                  nodes.field_body("", nodes.paragraph("", "", option))]
            fl += f

        p2 = nodes.paragraph()
        doc, _ = self.state.inline_text(data["doc"], self.lineno)
        p2 += doc
        p2 += fl

        return [p1, p2]

    def compact_list_entry(self, name, text, data):
        "Build an entry for the compact list of parameters."

        p1 = nodes.paragraph()
        p1 += config(name, text=text)

        if not (data["type"] == "string" and len(data["value"]) == 0):
            p1 += nodes.Text(" (")
            p1 += self.format_value(data["value"], data["type"])
            if "units" in data:
                if data["units"] not in ["1", "pure number", "count"]:
                    p1 += nodes.emphasis("", " {units}".format(**data))
            p1 += nodes.Text(")")

        doc, _ = self.state.inline_text(data["doc"], self.lineno)

        p1 += nodes.Text(" ")
        p1 += doc

        return p1

    def run(self):
        env = self.state.document.settings.env

        # make sure the current document gets re-built if the config file changes
        env.note_dependency(env.pism_parameters["filename"])

        if "prefix" in self.options:
            prefix = self.options["prefix"]
        else:
            prefix = ""

            # Store the docname corresponding to this parameter list.
            # It is used in resolve_config_links() to build URIs.
            env.pism_parameters["docname"] = env.docname

        if "exclude" in self.options:
            exclude = self.options["exclude"]
        else:
            exclude = None

        full_list = prefix == "" and exclude == None

        parameter_list = nodes.enumerated_list()

        parameters_found = False
        for name in sorted(pism_data.keys()):

            pattern = "^" + prefix
            # skip parameters that don't have the desired prefix
            if not re.match(pattern, name):
                continue

            if exclude and re.match(exclude, name):
                continue

            parameters_found = True

            item = nodes.list_item()

            if full_list:
                # only the full parameter list items become targets
                item += self.list_entry(name, pism_data[name])
            else:
                item += self.compact_list_entry(name,
                                                re.sub(pattern, "", name),
                                                pism_data[name])
            parameter_list += item

        if not parameters_found:
            msg = 'Error in a "{}" directive: no parameters with prefix "{}".'.format(self.name, prefix)
            text_error = nodes.error()
            text_error += nodes.Text(msg)

            reporter = self.state_machine.reporter
            system_error = reporter.error(msg, nodes.literal('', ''), line=self.lineno)
            return [text_error, system_error]

        return [parameter_list]

def resolve_config_links(app, doctree, fromdocname):
    """Replace config nodes with references to items in the list of
    parameters.
    """
    docname = app.builder.env.pism_parameters["docname"]

    for node in doctree.traverse(config):
        reference = nodes.reference('', '')
        reference['internal'] = True
        reference['refdocname'] = docname
        reference['refuri'] = "{}#{}".format(app.builder.get_relative_uri(fromdocname, docname),
                                             make_id(node.parameter))

        # Allow wrapping long parameter names
        words = node.astext().split(".")
        reference += nodes.literal("", words[0])
        for w in words[1:]:
            reference += [softhyphen(), nodes.literal("", "." + w)]

        node.replace_self(reference)

def init_pism_parameters(app):
    """Read and pre-process the list of PISM's configuration parameters."""
    global pism_data
    env = app.builder.env

    filename = os.path.normpath(app.config.pism_config_file)

    if not hasattr(env, "pism_parameters"):
        # the path to the configuration file (used to tell Sphinx to
        # re-build if it changes)
        env.pism_parameters = {"filename" : filename}

    f = netCDF4.Dataset(filename)
    variable = f.variables["pism_config"]
    data = {k : getattr(variable, k) for k in variable.ncattrs()}

    suffixes = ["choices", "doc", "option", "type", "units"]

    def special(name):
        "Return true if 'name' is a 'special' parameter, false otherwise."
        for suffix in suffixes:
            if name.endswith("_" + suffix) or name == "long_name":
                return True
        return False

    for key, value in data.items():
        if special(key):
            continue

        pism_data[key] = {"value" : value}

        for s in suffixes:
            try:
                pism_data[key][s] = data[key + "_" + s]
            except:
                pass

def check_consistency(app, env):
    """Check if we have a full parameter list with link targets"""
    if not "docname" in env.pism_parameters:
        raise SphinxError("make sure that this document contains a pism-parameters directive")

def env_purge_doc(app, env, docname):
    """Update the environment if the file containing the full list changed"""
    if "docname" in env.pism_parameters and docname == env.pism_parameters["docname"]:
        del env.pism_parameters["docname"]

def setup(app):
    app.add_config_value('pism_config_file', "pism_config.json", 'env')

    app.add_node(config)
    app.add_node(softhyphen,
                 html=(visit_softhyphen_html, depart_softhyphen_html),
                 latex=(visit_softhyphen_latex, depart_softhyphen_latex))
    app.add_role('config', config_role)
    app.add_directive('pism-parameters', ParameterList)

    app.connect("builder-inited", init_pism_parameters)
    app.connect("env-purge-doc", env_purge_doc)
    app.connect("env-check-consistency", check_consistency)
    app.connect('doctree-resolved', resolve_config_links)

    return {
        'version': '0.1',
        'parallel_read_safe': False,
        'parallel_write_safe': True,
    }


import json
original_file = '/raid/nanopore/shubham/Nanopore-DNA-storeage/oligos_2_7_19/code/conv_m11_nosync_init_64payload_init10010110001_oligos_raptor_coded'
recon_file = 'tmpfile.m11_nosync.l_64.280743'
with open(recon_file) as f:
    m1 = json.loads(f.read())
with open(original_file) as f:
    m2 = json.loads(f.read())
print('Number of symbols in original:',len(m2['symbols']))
print('Number of symbols in reconstruction:',len(m1['symbols']))
d1 = {l[0]:l[1] for l in m1['symbols']}
d2 = {l[0]:l[1] for l in m2['symbols']}

to_be_removed = []
for k in d1:
    if k not in d2:
        # out of range
        to_be_removed.append(k)

for k in to_be_removed:
    del d1[k]
print('Number of symbols out of range:',len(to_be_removed))
print('Number of erroneous symbols in reconstruction:',sum([d1[k]!=d2[k] for k in d1]))


# -*- coding: utf-8 -*-
import csv
import glob
import logging
import multiprocessing
import os
import re
import shutil
import subprocess
import tempfile

from delia_commons import deliafile
from delia_preprocessor.deliaobject import DeliaObject
from delia_tokenizer import token
from delia_tokenizer.tokenize import get_type, get_token, get_path, get_offset

from factory import consts
from factory.backends.base import delia_context, get_project_path
from factory.deliaobject import Procedure

log = logging.getLogger(__name__)

def ignore_comment_ws(scanner):
    for lexeme in scanner:
        if get_type(*lexeme) not in (token.comment, token.WS):
            yield lexeme

def load_frame_map(path):
    frame_map = {}
    if not os.path.exists(path):
        return frame_map
    with open(path, newline='') as fd:
        reader = csv.DictReader(fd, delimiter=';')
        for row in reader:
            if len(row) == 6:
                frame_map[row['frame_name']] = [
                    (int(row['X']), int(row['Y']), int(row['Z'])),
                    (int(row['new_X']), int(row['new_Y'])),
                ]
    return frame_map

FRAME_MAP_BASENAME = 'frame_map.csv'

class BaseFrameBackend(object):
    def export_frame_map(self, schema_version, procedure_name, revision):
        url = self.url + '/gp{schema_version}/adl/src/gra/java/{procedure_basename}/{basename}'.format(
            schema_version=schema_version,
            procedure_basename=procedure_name.replace('.', '_'),
            basename=FRAME_MAP_BASENAME,
        )
        with tempfile.TemporaryDirectory() as temp:
            path = os.path.join(temp, FRAME_MAP_BASENAME)
            if not self.subversion_backend.safe_export(url, path, revision=max(revision, consts.FRAME_MAP_MIN_REVISION)):
                return {}
            return load_frame_map(path)

class FrameAreaBackend(BaseFrameBackend):
    def __init__(self, subversion_backend, url, sandbox_timeout=5 * 60):
        super(FrameAreaBackend, self).__init__()
        self.subversion_backend = subversion_backend
        self.url = url
        self.sandbox_timeout = sandbox_timeout

    def expanse(self, checkout, schema_version, procedure_name):
        ctx = delia_context()
        ctx.initialize(get_project_path(checkout, schema_version))
        procedure = Procedure(procedure_name)
        procedure_path = deliafile.DeliaFile(ctx, True, procedure_name).path
        with tempfile.TemporaryDirectory() as temp:
            procedure_new_path = os.path.join(temp, os.path.basename(procedure_path))
            with open(procedure_new_path, 'w', encoding='latin1') as fd:
                for line in procedure.listing_gen():
                    fd.write(line)
                    fd.write('\n')
            shutil.move(procedure_new_path, procedure_path)

    def tokenize(self, checkout, schema_version, procedure_name):
        frames = {}
        frame_name = None
        ctx = delia_context()
        ctx.initialize(get_project_path(checkout, schema_version))
        procedure = DeliaObject(procedure_name)
        scanner = ignore_comment_ws(procedure.scan_all())
        for lexeme in scanner:
            lexeme_type = get_type(*lexeme)
            if lexeme_type == token.FRAME:
                lexeme = next(scanner)
                if get_type(*lexeme) == token.mag_name:
                    frame_name = get_token(*lexeme).lower()
            elif frame_name and lexeme_type == token.FRAME_AREA:
                from_lexeme = next(scanner)
                if get_type(*from_lexeme) == token.integer:
                    next(scanner)
                    to_lexeme = next(scanner)
                    if get_type(*to_lexeme) == token.integer:
                        if frame_name in frames:
                            raise ValueError(frame_name)
                        frames[frame_name] = (from_lexeme, to_lexeme)
        return procedure.files, frames

    def fix(self, schema_version, procedure_name, revision, checkout, sandbox=False):
        frame_map = self.export_frame_map(schema_version, procedure_name, revision)
        if not frame_map:
            log.info('frame fix ignored as %d:%s@%d has no frame map', schema_version, procedure_name, revision)
            return
        args = (schema_version, procedure_name, checkout, frame_map)
        if sandbox:
            failure = None
            ctx = multiprocessing.get_context('spawn')
            process = ctx.Process(target=self._fix, args=args)
            process.start()
            process.join(self.sandbox_timeout)
            if process.exitcode is None:
                process.terminate()
                failure = 'timeout'
            elif process.exitcode != 0:
                failure = 'exit: %d' % process.exitcode
            if failure:
                raise ValueError('failed to fix frames of %d:%s@%d (%s)' % (schema_version, procedure_name, revision, failure))
        else:
            self._fix(*args)

    def fix_local(self, schema_version, procedure_name, checkout):
        frame_map_path = os.path.join(checkout, 'gp%d' % schema_version, 'adl', 'src', 'gra', 'java', procedure_name.replace('.', '_').lower(), FRAME_MAP_BASENAME)
        frame_map = load_frame_map(frame_map_path)
        if not frame_map:
            log.info('frame fix ignored as %d:%s has no frame map', schema_version, procedure_name)
            return
        self._fix(schema_version, procedure_name, checkout, frame_map)

    def _fix(self, schema_version, procedure_name, checkout, frame_map):
        # Need to work on expanse as some FRAME.AREA are defined in MACROs T_T
        self.expanse(checkout, schema_version, procedure_name)
        files, frames = self.tokenize(checkout, schema_version, procedure_name)
        patch = {}
        for frame_name, [(X, Y, Z), (new_X, new_Y)] in frame_map.items():
            if frame_name in frames:
                from_lexeme, to_lexeme = frames[frame_name]
                if X != new_X:
                    from_path = files[get_path(*from_lexeme)]
                    from_offset = get_offset(*from_lexeme)
                    from_token = get_token(*from_lexeme)
                    if from_path not in patch:
                        patch[from_path] = []
                    patch[from_path].append((from_offset, from_token, str(new_X)))
                if Y != new_Y:
                    to_path = files[get_path(*to_lexeme)]
                    to_offset = get_offset(*to_lexeme)
                    to_token = get_token(*to_lexeme)
                    if to_path not in patch:
                        patch[to_path] = []
                    patch[to_path].append((to_offset, to_token, str(new_Y)))
        if len(patch) == 0:
            log.info('nothing to fix in %d:%s', schema_version, procedure_name)
        for path, data in patch.items():
            log.info('fix frame in %s for %d:%s', os.path.basename(path), schema_version, procedure_name)
            with open(path, 'rb') as fd:  # offset comes as binaries
                content = fd.read()
            data.sort(key=lambda x: x[0], reverse=True)
            for offset, token, new_token in data:
                log.info('replace %s by %s @%d in %s for %d:%s', token, new_token, offset, os.path.basename(path), schema_version, procedure_name)
                content = content[:offset - len(token)] + new_token.encode('latin1') + content[offset:]
            with open(path, 'wb') as fd:
                fd.write(content)

class FrameBackend(BaseFrameBackend):
    WEBINTAKE_CLIENT_JAR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'webintake-client.jar')
    POM_XML = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pom.xml')
    LEGACY_NAME_RE = re.compile('^frm_(?P<X>\d+)_(?P<Y>\d+)_(?P<Z>\d+).java$')
    NAME_RE = re.compile('^frm_(?P<X>\d+)_(?P<Y>\d+).java$')
    MLG_TEMPLATE = '''package %(package)s;

import java.util.*;

public class %(name)s_%(lang)s extends ListResourceBundle
{
\tpublic Object[][] getContents() {
\t\treturn contents;
\t}

\tstatic final Object[][] contents =
\t{
%(contents)s
\t};
}
'''

    def __init__(self, subversion_backend, url, java_home, m2_home, compile_timeout=120):
        super(FrameBackend, self).__init__()
        self.subversion_backend = subversion_backend
        self.url = url
        if not java_home or not os.path.isdir(java_home):
            raise ValueError('JAVA_HOME does not exist: %s' % java_home)
        if not m2_home or not os.path.isdir(m2_home):
            raise ValueError('M2_HOME does not exist: %s' % m2_home)
        self.java_home = java_home
        self.m2_home = m2_home
        self.compile_timeout = compile_timeout

    def is_comment(self, line):
        return line.strip().startswith('//')

    def get_url(self, schema_version, procedure_name):
        return self.url + '/gp{schema_version}/adl/src/gra/java/{procedure_basename}'.format(
            schema_version=schema_version,
            procedure_basename=procedure_name.replace('.', '_'),
        )

    def get_legacy_paths(self, frame_dir):
        return self._get_paths(frame_dir, self.LEGACY_NAME_RE)

    def get_paths(self, frame_dir):
        return self._get_paths(frame_dir, self.NAME_RE)

    def _get_paths(self, frame_dir, pattern):
        frame_paths = []
        if os.path.isdir(frame_dir):
            for bn in os.listdir(frame_dir):
                if pattern.match(bn):
                    frame_paths.append(os.path.join(frame_dir, bn))
        return frame_paths

    def get_new_names(self, frame_dir, frame_map, frame_revisions):
        frames = list(frame_revisions.items())
        frames.sort(key=lambda x: x[1])
        new_names = {}
        areas = []
        for frame_name, (area, new_area) in frame_map.items():
            areas.append(area)
        for frame_path, revision in frames:
            m = self.LEGACY_NAME_RE.match(os.path.basename(frame_path))
            X = int(m.group('X'))
            Y = int(m.group('Y'))
            Z = int(m.group('Z'))
            if (X, Y, Z) not in areas:
                new_names['frm_%d_%d' % (X, Y)] = frame_path
        for frame_name, (area, new_area) in frame_map.items():
            frame_path = os.path.join(frame_dir, 'frm_%d_%d_%d.java' % area)
            if os.path.isfile(frame_path):
                new_names['frm_%d_%d' % new_area] = frame_path
        return new_names

    def get_name(self, frame_path):
        return os.path.basename(frame_path)[:-len('.java')]

    def generate(self, frame_path, frame_new_dir, frame_encoding, frame_new_name=None):
        keys = {}
        frame_name = self.get_name(frame_path)
        if not frame_new_name:
            frame_new_name = frame_name
        frame_new_path = os.path.join(frame_new_dir, frame_new_name + '.java')
        if not os.path.exists(frame_new_dir):
            os.makedirs(frame_new_dir)
        with open(frame_path, encoding=frame_encoding) as frame_fd:
            with open(frame_new_path, 'w', encoding='utf-8') as frame_new_fd:
                content = frame_fd.read()
                if frame_name != frame_new_name:
                    content = content.replace(frame_name, frame_new_name)
                for line in content.splitlines(False):
                    if 'SgfTranslator' in line and self.is_comment(line):
                        frame_new_fd.write(line.replace('//', '', 1) + '\n')
                    elif self.is_comment(line):
                        pass
                    elif 'setText' in line or 'setToolTipText' in line or 'setBeanText' in line or 'setTitle' in line:
                        start = line.find('("')
                        stop = line.rfind('")')
                        key = line[0: line.find('.')].strip().upper()
                        msgid = line[start + 2: stop].replace('\\n', '\n').replace('\\"', '"')
                        if msgid.strip() == '':
                            frame_new_fd.write(line + '\n')
                        else:
                            if 'setToolTipText' in line or 'setBeanText' in line:
                                key += '_T'
                            frame_new_fd.write(line[0: start] + '(trans.getString("' + key + '"))' + line[stop + 2:] + '\n')
                            keys[key] = msgid
                    elif 'Placement' in line:
                        pass
                    else:
                        frame_new_fd.write(line + '\n')
        return keys

    def generate_lang(self, frame_dir, frame_name, lang, mo, keys):
        frame_new_path = os.path.join(frame_dir, frame_name + '_' + lang + '.java')
        with open(frame_new_path, 'w', encoding='utf-8') as frame_new_fd:
            contents = []
            for key, msgid in keys.items():
                # TODO: find stripped
                msgstr = None
                if mo:
                    entry = mo.find(msgid)
                    if entry and entry.msgstr:
                        msgstr = entry.msgstr
                if msgstr is None:
                    msgstr = msgid
                # Strip the message. Why?
                msgstr = msgstr.strip().replace('\r', '').replace('"', '\\"').replace('\n', '\\n')
                contents.append('\t\t{"%s", "%s"}' % (key, msgstr))
            context = {
                'package': os.path.basename(frame_dir),
                'name': frame_name,
                'lang': lang,
                'contents': ',\n'.join(contents)
            }
            frame_new_fd.write(self.MLG_TEMPLATE % context)

    def compile(self, schema_version, procedure_name, frame_dir, class_dir):
        if not os.path.exists(class_dir):
            os.makedirs(class_dir)
        env = os.environ.copy()
        env.pop('CLASSPATH', None)
        env['LANG'] = 'en_US.UTF-8'
        env['JAVA_HOME'] = self.java_home
        env['M2_HOME'] = self.m2_home
        env['PATH'] = os.pathsep.join([
            os.path.join(self.java_home, 'bin'),
            os.path.join(self.m2_home, 'bin'),
            env.get('PATH', ''),
        ])
        src_paths = glob.glob(os.path.join(frame_dir, '*.java'))
        with tempfile.TemporaryDirectory() as temp:
            if schema_version <= 2009:
                command = [
                    os.path.join(self.java_home, 'bin', 'javac'),
                    '-cp', self.WEBINTAKE_CLIENT_JAR,
                    '-nowarn',
                    '-d', class_dir,
                ]
                command.extend(src_paths)
            else:
                command = [
                    os.path.join(self.m2_home, 'bin', 'mvn'),
                    '--file', self.POM_XML,
                    '-Dsrc.directory=' + os.path.dirname(frame_dir),
                    '-Doutput.directory=' + class_dir,
                    '-Dtarget.directory=' + temp,
                ]
            try:
                output = subprocess.check_output(command, env=env, stderr=subprocess.STDOUT, timeout=self.compile_timeout).decode('utf-8', 'replace')
            except subprocess.CalledProcessError as e:
                print(e.output.decode('utf-8', 'replace'))

        for src_path in src_paths:
            bin_path = os.path.join(
                class_dir,
                procedure_name.replace('.', '_'),
                os.path.splitext(os.path.basename(src_path))[0] + '.class',
            )
            if not os.path.isfile(bin_path):
                raise ValueError('class %s for %s does not exist' % (os.path.basename(bin_path), procedure_name))
        return output

    def generate_all(self, schema_version, procedure_name, all_mo, frame_dir, frame_names, encoding):
        # Go threw the frames to process
        for frame_name, frame_path in frame_names.items():
            # Log
            log.info('generate frame %s for %d:%s from %s', frame_name, schema_version, procedure_name, frame_path)
            # Generate the new frame
            keys = self.generate(frame_path, frame_dir, encoding, frame_name)
            # Go threw that supported languages
            for lang, mo in all_mo.items():
                # Log
                log.info('generate %s frame %s for %d:%s', lang, frame_name, schema_version, procedure_name)
                # Generate the new internationalized frame
                self.generate_lang(frame_dir, frame_name, lang, mo, keys)

    def generate_and_compile(self, schema_version, procedure_name, revision, all_mo, output_dir):
        # Log
        log.info('generate frames for %d:%s@%d', schema_version, procedure_name, revision)
        # Get work folder
        with tempfile.TemporaryDirectory() as temp:
            # Inputs
            procedure_basename = procedure_name.replace('.', '_')
            frame_dir = os.path.join(temp, 'frame', procedure_basename)
            frame_new_dir = os.path.join(temp, 'frame_new', procedure_basename)
            # Keep in mind if frames were created
            has_frame = False
            # Get frames URL
            url = self.get_url(schema_version, procedure_name)
            # Checkout frames
            if self.subversion_backend.safe_checkout(url, frame_dir, revision=revision):
                # Get the list of legacy frames
                frame_legacy_paths = self.get_legacy_paths(frame_dir)
                # Check if at least one legacy frame
                if frame_legacy_paths:
                    # Get the frame revisions (to be able to sort them)
                    frame_revisions = self.subversion_backend.get_revisions(frame_legacy_paths)
                    # Get frame mapping
                    frame_map = self.export_frame_map(schema_version, procedure_name, revision)
                    # Map old names with new ones
                    frame_new_names = self.get_new_names(frame_dir, frame_map, frame_revisions)
                    # Generate all frames
                    self.generate_all(schema_version, procedure_name, all_mo, frame_new_dir, frame_new_names, 'latin1')
                    # At least one frame
                    has_frame = True
                # Get the list of new frames
                frame_paths = self.get_paths(frame_dir)
                # Check if at least one new frame
                if frame_paths:
                    # Get frame names
                    frame_names = dict([(self.get_name(frame_path), frame_path) for frame_path in frame_paths])
                    # Generate all frames
                    self.generate_all(schema_version, procedure_name, all_mo, frame_new_dir, frame_names, 'utf-8')
                    # At least one frame
                    has_frame = True
                # Check if at least one frame
                if has_frame:
                    # Log
                    log.info('compile %d:%s frames', schema_version, procedure_name)
                    # Compile all the frames
                    self.compile(schema_version, procedure_name, frame_new_dir, output_dir)
            # No frame, log it
            if not has_frame:
                log.info('%d:%s has no frame', schema_version, procedure_name)

    def generate_and_compile_local(self, schema_version, procedure_name, all_mo, checkout, output_dir, compile_legacy=True):
        # Log
        log.info('generate frames for %d:%s', schema_version, procedure_name)
        # Input
        procedure_basename = procedure_name.replace('.', '_').lower()
        # Frame directory
        frame_dir = os.path.join(checkout, 'gp%d' % schema_version, 'adl', 'src', 'gra', 'java', procedure_basename)
        # Keep in mind if frames were created
        has_frame = False
        # Checkout frames
        if os.path.isdir(frame_dir):
            # Get work folder
            with tempfile.TemporaryDirectory() as temp:
                # Get the new frame directory
                frame_new_dir = os.path.join(temp, procedure_basename)
                # Get the list of legacy frames
                frame_legacy_paths = self.get_legacy_paths(frame_dir)
                # Check if at least one legacy frame
                if frame_legacy_paths:
                    # We have not the revisions
                    frame_revisions = dict([(path, 0) for path in frame_legacy_paths])
                    # Load frame map
                    frame_map = load_frame_map(os.path.join(frame_dir, FRAME_MAP_BASENAME))
                    # Map old names with new ones
                    frame_new_names = self.get_new_names(frame_dir, frame_map, frame_revisions)
                    # Also compile the legacy ones if required
                    if compile_legacy:
                        frame_new_names.update(dict([(self.get_name(frame_legacy_path), frame_legacy_path) for frame_legacy_path in frame_legacy_paths]))
                    # Generate all frames
                    self.generate_all(schema_version, procedure_name, all_mo, frame_new_dir, frame_new_names, 'latin1')
                    # At least one frame
                    has_frame = True
                # Get the list of new frames
                frame_paths = self.get_paths(frame_dir)
                # Check if at least one new frame
                if frame_paths:
                    # Get frame names
                    frame_names = dict([(self.get_name(frame_path), frame_path) for frame_path in frame_paths])
                    # Generate all frames
                    self.generate_all(schema_version, procedure_name, all_mo, frame_new_dir, frame_names, 'utf-8')
                    # At least one frame
                    has_frame = True
                # Check if at least one frame
                if has_frame:
                    # Log
                    log.info('compile %d:%s frames', schema_version, procedure_name)
                    # Compile all the frames
                    self.compile(schema_version, procedure_name, frame_new_dir, output_dir)
        # No frame, log it
        if not has_frame:
            log.info('%d:%s has no frame', schema_version, procedure_name)


import cv2
from cvzone.PoseModule import PoseDetector

cap = cv2.VideoCapture('1.flv')

_ISOPENED = cap.isOpened()
detertor = PoseDetector()

posList = []
while True:
    success, img = cap.read()
    img = detertor.findPose(img)
    lmList, bboxInfo = detertor.findPosition(img)

    if bboxInfo:
        lmString = ''
        for lm in lmList:
            #opencv和unity的定位点不同所以要做y轴反转
            lmString += f'{lm[1]},{img.shape[0]-lm[2]},{lm[3]},'
        posList.append(lmString)

    img = cv2.resize(img, (0, 0), fx=0.4, fy=0.4, interpolation=cv2.INTER_NEAREST)
    cv2.imshow("Image",img)
    key = cv2.waitKey(1)

    if key == ord('s'):
        with open("AnimationFile.txt",'w') as f:
            f.writelines(["%s\n" % item for item in posList])


import os
import collections
from contextlib import contextmanager

import tensorflow as tf

from mayo.log import log
from mayo.net.tf import TFNet
from mayo.session.test import Test

class TFTaskBase(object):
    """Specifies common training and evaluation tasks.  """
    debug = False

    def __init__(self, session):
        super().__init__()
        self.is_test = isinstance(session, Test)
        self.session = session
        self.config = session.config
        self.num_gpus = self.config.system.num_gpus
        self.mode = session.mode
        self.estimator = session.estimator
        self._instantiate_nets()

    @contextmanager
    def _gpu_context(self, gid):
        with tf.device('/gpu:{}'.format(gid)):
            with tf.name_scope('tower_{}'.format(gid)) as scope:
                yield scope

    def map(self, func):
        iterer = enumerate(zip(self.nets, self.predictions, self.truths))
        for i, (net, prediction, truth) in iterer:
            with self._gpu_context(i):
                yield func(net, prediction, truth)

    @staticmethod
    def _test_files(folder):
        suffixes = ['.jpg', '.jpeg', '.png']
        files = [
            name for name in sorted(os.listdir(folder))
            if any(name.endswith(s) for s in suffixes)]
        log.debug(
            'Running in folder {!r} on images: {}'
            .format(folder, ', '.join(files)))
        return [os.path.join(folder, name) for name in files]

    def _instantiate_nets(self):
        nets = []
        inputs = []
        predictions = []
        truths = []
        names = []
        model = self.config.model
        iterer = self.generate()
        for i, (data, additional) in enumerate(iterer):
            if self.is_test:
                name, truth = additional[0], None
            else:
                name, truth = None, additional
            log.debug('Instantiating graph for GPU #{}...'.format(i))
            with self._gpu_context(i):
                net = TFNet(self.session, model, data, bool(nets))
            nets.append(net)
            prediction = net.outputs()
            data, prediction, truth = self.transform(
                net, data, prediction, truth)
            if i == 0 and self.debug:
                self._register_estimates(prediction, truth)
            inputs.append(data)
            predictions.append(prediction)
            truths.append(truth)
            names.append(name)
        self.nets = nets
        self.inputs = inputs
        self.predictions = predictions
        self.truths = truths
        self.names = names

    def _register_estimates(self, prediction, truth):
        def register(root, mapping):
            history = 'infinite' if self.mode == 'validate' else None
            if not isinstance(mapping, collections.Mapping):
                if mapping is not None:
                    self.estimator.register(mapping, root, history=history)
                return
            for key, value in mapping.items():
                register('{}.{}'.format(root, key), value)
        register('prediction', prediction)
        register('truth', truth)

    def transform(self, net, data, prediction, truth):
        return data, prediction, truth

    def generate(self):
        raise NotImplementedError(
            'Please implement .generate() which produces training/validation '
            'samples and the expected truth results.')

    def augment(self, serialized):
        raise NotImplementedError(
            'Please implement .augment() which augments input tensors.')

    def train(self, net, prediction, truth):
        raise NotImplementedError(
            'Please implement .train() which returns the loss tensor.')

    def eval(self):
        raise NotImplementedError(
            'Please implement .eval() which registers the evaluation metrics.')

    def post_eval(self):
        raise NotImplementedError(
            'Please impelement .post_eval() which computes an info dict '
            'for the evaluation metrics.')

    def test(self, name, prediction):
        raise NotImplementedError(
            'Please implement .test() which produces human-readable output '
            'for a given input.')


# File: examples/sklearn_refactored_script.py
from sklearn.datasets import load_boston
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import LinearRegression
import pandas as pd

class ExtractTrainingSet:

    def run(self):
        df = load_boston()
        return dict(
            x=pd.DataFrame(df.data, columns=df.feature_names),
            y=pd.DataFrame(df.target, columns=['target'])
        )

class TrainModel:

    MODELS = {
        'ols': LinearRegression,
        'gbm': GradientBoostingRegressor,
    }

    def __init__(self, model, x, y):
        if model not in self.MODELS:
            raise ValueError(f'invalid model: {model}')
        self.model = model
        self.x = x
        self.y = y

    def run(self):
        model = self.MODELS[self.model]()
        model.fit(self.x, self.y)
        score = model.score(self.x, self.y)
        return {'score': score}


# 617 JungEun : 230608 THU mission 22 (1)
# 2th type1-3
# basic1.csv -> 'age' 컬럼의 이상치(IQR로 구하는 방법)를 더하라.

# 1. Data and libraries
import pandas as pd
df = pd.read_csv('/kaggle/input/bigdatacertificationkr/basic1.csv')

# 2. Get the std and limit line values of normal data
avg, std = df['age'].mean(), df['age'].std()

# 3. Define abnormal data and Print it
print(df[(df['age'] < avg-std*1.5)|(df['age'] > avg + std*1.5)]['age'].sum())

# 473.5

# 풀이
# 라이브러리 및 데이터 불러오기
import pandas as pd
import numpy as np

df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv')

std = df['age'].std() * 1.5
mean = df['age'].mean()

min_out = mean - std
max_out = mean + std
print(min_out, max_out)
# 5.298862216116952 96.62713778388306

# 이상치 age합
df[(df['age']>max_out)|(df['age']<min_out)]['age'].sum()

# 다르게 작성방법
# df.loc[(df['age'] > max)]['age'].sum() + df.loc[(df['age']< min)]['age'].sum()


import os, time, re, glob
import h5py
import nibabel as nib
import numpy as np
from gpiozero import LED

def usb_inserted():

    devices = os.popen('sudo blkid').readlines()

    usbs = []
    for u in devices:
        loc = [u.split(':')[0]]
        if '/dev/sd' not in loc[0]:
              continue # skip
        loc+=re.findall(r'"[^"]+"',u)
        columns = ['loc']+re.findall(r'\b(\w+)=',u)

        usbs.append(dict(zip(columns,loc)))

        if len(usbs) > 0:
            flag = True
        if len(usbs) == 0:
            flag = False
        return flag

def standardize(image):

  standardized_image=np.zeros(image.shape)
  for c in range(image.shape[0]):
    for z in range(image.shape[3]):
      image_slice = image[c,:,:,z]
      centered = image_slice - np.mean(image_slice)
      if np.std(centered) != 0:
                centered_scaled = centered / np.std(centered)
      else:
        centered_scaled=centered
      standardized_image[c, :, :, z] = centered_scaled
  return standardized_image

def saveh5(filename,cbf_data,cbv_data,mtt_data,tmax_data):
    cbf_data=cbf_data.reshape(1,256,256,8)
    cbv_data=cbv_data.reshape(1,256,256,8)
    mtt_data=mtt_data.reshape(1,256,256,8)
    tmax_data=tmax_data.reshape(1,256,256,8)
    image_data=np.concatenate((cbf_data,cbv_data,mtt_data,tmax_data),axis=0)
    image_data = standardize(image_data)

    with h5py.File('/home/pi/brain_stroke/preprocess/'+str(filename),'w') as f:
        f.create_dataset("X_train",data=image_data)
    f.close()

####MAIN#############
print("Waiting for USB...")
led_r = LED(23)
led_g = LED(24)
while True:
    if usb_inserted():
        break
    else:
        led_r.on()
        time.sleep(0.5)
        led_r.off()
        time.sleep(0.5)

print("USB Inserted")
led_r.off()
time.sleep(2)

usb_path = glob.glob('/media/pi/*/')
print(f"USB Path:{usb_path[0]}")
files_in_usb = glob.glob(str(usb_path[0]) + '/*/')
print(f"Files in usb: {files_in_usb}")
files_in_usb = [i for i in files_in_usb if 'System' not in i]

#print(files_in_usb)

for file in files_in_usb:
    cbf_path = glob.glob(file+'/*CBF.*/*.nii')[0]
    cbv_path = glob.glob(file+'/*CBV.*/*.nii')[0]
    mtt_path = glob.glob(file+'/*MTT.*/*.nii')[0]
    tmax_path= glob.glob(file+'/*Tmax*/*.nii')[0]

    file = file.split('/')[-2]

    cbf_obj=nib.load(cbf_path)
    cbv_obj=nib.load(cbv_path)
    mtt_obj=nib.load(mtt_path)
    tmax_obj=nib.load(tmax_path)

    cbf = cbf_obj.get_fdata()
    cbv = cbv_obj.get_fdata()
    mtt = mtt_obj.get_fdata()
    tmax=tmax_obj.get_fdata()

    if cbf.shape[2] != 8:
        print(cbf.shape)
        if cbf.shape[2] > 8:
            n = cbf.shape[2]
            n = n - (n%8)
            for i in range(0,n):
                name = file + str(i)
                saveh5(name,cbf[:,:,(i*8):(i+1)*8],cbv[:,:,(i*8):(i+1)*8],mtt[:,:,(i*8):(i+1)*8],tmax[:,:,(i*8):(i+1)*8])

        if cbf.shape[2] < 8:
            while cbf.shape[2] <= 8:
                cbf = np.concatenate([cbf,cbf],axis=2)
                cbv = np.concatenate([cbv,cbv],axis=2)
                mtt = np.concatenate([mtt,mtt],axis=2)
                tmax= np.concatenate([tmax,tmax],axis=2)
            print(cbf.shape)
            saveh5(file,cbf[:,:,:8],cbv[:,:,:8],mtt[:,:,:8],tmax[:,:,:8])

    if cbf.shape[2] == 8:
        saveh5(file,cbf,cbv,mtt,tmax)


##the import "neuralNet" is referred from
##https://towardsdatascience.com/an-introduction-to-neural-networks-with-implementation-from-scratch-using-python-da4b6a45c05b
import neuralNet

import os
import gym
import numpy as np
import random
import ipdb
import math
import matplotlib.pyplot as plt
env = gym.make('MountainCar-v0')

#increase length of episode. Referred from
#https://www.reddit.com/r/reinforcementlearning/comments/agd6j4/how_to_change_episode_length_and_reward/
env._max_episode_steps = 2000

#entire function referred from
#https://www.youtube.com/watch?v=KzsBaqYzNLc&ab_channel=Jakester897
def get_reward(state):
    if(state>=0.5):
        return 2
    else:
        reward = (state+1.2)/1.8 -1
    return reward

replay_mem = []

## initialise the replay memory with 20,000 random samples
def generate_replay():
    for i in range(100):
        observation = env.reset()
        for t in range(200):
            #ipdb.set_trace()
            state1 = observation[0]
            state2 = observation[1]
            action = env.action_space.sample()
            new_observation, reward, done, info = env.step(action)
            new_state = [new_observation[0],new_observation[1]]
            reward = get_reward(new_observation[0])
            attach = ([state1,state2],reward,new_state,action)
            #print(attach)
            replay_mem.append(attach)
            if(done):
                break
            observation = new_observation
    return replay_mem

##create a directory to save results
##https://www.tutorialspoint.com/How-can-I-create-a-directory-if-it-does-not-exist-using-Python
if not os.path.exists('results'):
    os.makedirs('results')

start_lr=0
start_batch=0
reward_batch = []
total_goal = []
#read_text('./progress.txt')
replay_mem = generate_replay()
reward_tot = []
print(len(replay_mem))

eps = 1.0

#declare neural network architecture
layers = [2,150,100,3]

##initialise 2 neural networks
param = neuralNet.initialize_params(layers)
base_param = neuralNet.initialize_params(layers)

flag=0
goal = 0
flag_goal = 0
goal_list = []

for i in range(len(total_goal)):
    if(total_goal[i]==0):
        goal_list.append(list([]))
    else:
        goal_list.append(total_goal[i])

##iterate over different batch and learning rate values
batch = [30,100,500]
lr = [0.01,0.001,0.0001]

for lr_i in range(len(lr)):
    for batch_i in range(len(batch)):
        reward_mean = []
        reward_batch = []
        loss= 0
        eps = 1.0
        goal_lis = []
        flag=0
        goal = 0
        param = neuralNet.initialize_params(layers)
        base_param = neuralNet.initialize_params(layers)
        for i in range(1000):
            observation = env.reset()
            tot_reward = 0
            for t in range(1000):
                #ipdb.set_trace()
                state1 = observation[0]
                state2 = observation[1]
                curr_state = np.reshape(np.array([state1,state2]),(1,2))

                #get q value for current state
                q_val_curr = neuralNet.forward_propagation(np.transpose(curr_state),param)
                q_val_curr = q_val_curr["A3"]

                ##epsilon greedy strategy
                ##following 4 lines referred from
                ##https://github.com/ikvibhav/reinforcement_learning/blob/master/code/mountain_car/mountain_car_sarsa.py
                if np.random.random() > eps:
                    action = np.argmax(q_val_curr)
                else:
                    action = np.random.randint(0, env.action_space.n)

                new_observation, reward, done, info = env.step(action)

                ##get custom reward
                reward = get_reward(new_observation[0])
                tot_reward = tot_reward + reward

                ##termination condition to consider that MountainCar is solved
                if(new_observation[0]>=0.5):
                    if(eps<0.5):
                        goal = goal+1
                        goal_lis.append(i)
                    print("Goal is:",goal)
                    print("Episode is:",i)
                    done = True
                    #terminate if car reached goal 3 times
                    if(goal >= 3):
                        flag = 1
                    break
                new_state1 = new_observation[0]
                new_state2 = new_observation[1]

                ##append to replay memory and pop the first sample
                if(len(replay_mem)>2000):
                    replay_mem.pop(0)
                replay_mem.append(([state1,state2],reward,[new_state1,new_state2],action))

                if(done):
                    break

                ##randomly sample from replay memory.
                ##following line referred from
                ##https://stackoverflow.com/questions/22842289/generate-n-unique-random-numbers-within-a-range
                sample = random.sample(range(0, len(replay_mem)), batch[batch_i])

                input_curr_state = []
                input_next_state = []
                action = []
                reward = []

                ##processing after getting the samples
                for i_curr in range(len(sample)):
                    input_curr_state.append(replay_mem[sample[i_curr]][0])
                    input_next_state.append(replay_mem[sample[i_curr]][2])
                    action.append(int(replay_mem[sample[i_curr]][3]))
                    reward.append(replay_mem[sample[i_curr]][1])

                #ipdb.set_trace()
                input_curr_state = np.array(input_curr_state)
                input_next_state = np.array(input_next_state)

                #get q value for current state and next state
                y_pred_dict = neuralNet.forward_propagation(np.transpose(input_curr_state),param)
                y_pred = (np.transpose(y_pred_dict["A3"]))
                next_state_y = neuralNet.forward_propagation(np.transpose(input_next_state),base_param)
                next_state_y = (np.transpose(next_state_y["A3"]))
                #get the maximum q value for next state
                max_next_state = np.max(next_state_y,axis=1)

                ##determine if next state is terminal state.
                # This is done by looking at reward function.
                # If it is negative then state was terminal.
                for i_curr in range(len(max_next_state)):
                    ##if next state is terminal state then do not consider it.
                    if(reward[i_curr]==-1):
                        max_next_state[i_curr] = 0

                #calculating the expected q value
                y = reward + 0.99*max_next_state

                ##processing to compute loss. I have used L1 loss in this code
                y_final = y_pred.copy()
                y_pred_final = []
                for i_curr in range(len(y_final)):
                    y_pred_final.append(y_final[i_curr][action[i_curr]])
                    y_final[i_curr][action[i_curr]] = y[i_curr]
                try:
                    loss = np.mean(np.abs(y-y_pred_final))
                except Exception as e:
                    print("Exception ocurred")

                ##perform gradient descent
                ##https://towardsdatascience.com/an-introduction-to-neural-networks-with-implementation-from-scratch-using-python-da4b6a45c05b
                grads = neuralNet.backward_propagation(param,y_pred_dict,np.transpose(input_curr_state),np.transpose(y_final))
                ##update parameters
                param = neuralNet.update_params(param, grads, lr[lr_i])
                observation = new_observation

            ##epsilon decay
            ##https://github.com/philtabor/Youtube-Code-Repository/blob/master/ReinforcementLearning/Fundamentals/mountaincar.py
            eps = eps - 2/100 if eps > 0.01 else 0.01

            if(i%100==0):
                print(i,eps,loss,tot_reward)
            if(math.isnan(loss)):
                print(eps)
                print("Gradient Exploded")
                break
            reward_tot.append(tot_reward)

            ##update target network every 1000 episodes. This is done to keep the DQN stable
            if(i%100==0 and i>100):
                base_param = param

            if(flag==1):
                break

            if(i==0):
                reward_mean.append(np.float(tot_reward))
            else:
                reward_mean.append(np.float(reward_mean[-1]+tot_reward))
        mean_print = []
        for i in range(len(reward_mean)):
            if(math.isnan(reward_mean[i])):
                break
            mean_print.append((reward_mean[i])/(i+1))
        reward_mean_copy = mean_print.copy()
        reward_batch.append(reward_mean_copy)
        if(len(goal_lis)==0):
            total_goal.append([0])
        else:
            total_goal.append(goal_lis)

        goal_list.append(goal_lis)
        ##following 2 lines referred from
        ##https://stackoverflow.com/questions/28439701/how-to-save-and-load-numpy-array-data-properly
        np.save(('./results/result_np'+str(lr_i)),np.array(total_goal))
        np.save(('./results/pregress_np'+str(lr_i)+str(batch_i)),np.array(reward_batch))

        print("Batch finished",batch_i)
    start_batch =0
    print("Alpha finished",lr_i)
print("Finished!!!")
print(len(total_goal))
print(total_goal[0])


# Se importan las librerías a utilizar
import time
# La librería board es una forma de llamar a los pines de la Rpi
import board
# Se importa la librería del bme280 de adafruit
from adafruit_bme280 import basic as adafruit_bme280

# Se crea el sensro, usando los pines por defecto de la Rpi para I2C
i2c = board.I2C()  # Usa los pines board.SCL (3) y board.SDA (2)
# Debido a que el sensor que tenemos cuenta con la dirección 0x76 y no 0x77 que es con la que viene por defecto
# Se debe agregar el parámetro de address como se observa abajo
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c, address=0x76)

# Se debe colocar la presión (hPa) sobre el nivel del mar del lugar en que se encuentre
# Sería bueno consumir un api que entregue esta información a partir de las coordenadas
bme280.sea_level_pressure = 1010

while True:
    print("\nTemperatura: %0.1f C" % bme280.temperature)
    print("Humedad: %0.1f %%" % bme280.relative_humidity)
    print("Presión: %0.1f hPa" % bme280.pressure)
    print("Altura = %0.2f metros" % bme280.altitude)
    time.sleep(2)


import os
import collections
import json
import pickle
import time
from datetime import datetime, timedelta, date
from concurrent.futures import ThreadPoolExecutor
import click
from appdirs import user_cache_dir

import calendar

import math

try:
    import numpy as np
except:
    np = None

def np_exception(function):
    def wrapper(*args, **kwargs):
        if not np:
            raise ModuleNotFoundError("Please install pandas and numpy using \n pip install pandas")
        return function(*args, **kwargs)

    return wrapper

@np_exception
def np_float(num):
    try:
        return np.float64(num)
    except:
        return np.nan

@np_exception
def np_date(dt):
    try:
        return np.datetime64(dt)
    except:
        pass

    try:
        dt = datetime.strptime(dt, "%d-%b-%Y").date()
        return np.datetime64(dt)
    except:
        pass

    try:
        dt = datetime.strptime(dt, "%d %b %Y").date()
        return np.datetime64(dt)
    except:
        pass

    return np.datetime64('nat')

@np_exception
def np_int(num):
    try:
        return np.int64(num)
    except:
        return 0

def break_dates(from_date, to_date):
    if from_date.replace(day=1) == to_date.replace(day=1):
        return [(from_date, to_date)]
    date_ranges = []
    month_start = from_date
    month_end = month_start.replace(day=calendar.monthrange(month_start.year, from_date.month)[1])
    while(month_end < to_date):
        date_ranges.append((month_start, month_end))
        month_start = month_end + timedelta(days=1)
        month_end = month_start.replace(day=calendar.monthrange(month_start.year, month_start.month)[1])
        if month_end >= to_date:
            date_ranges.append((month_start, to_date))
    return date_ranges

def kw_to_fname(**kw):
    name = "-".join([str(kw[k]) for k in sorted(kw) if k != "self"])
    return name

def cached(app_name):
    """
        Note to self:
            This is a russian doll
            wrapper - actual caching mechanism
            _cached - actual decorator
            cached - wrapper around decorator to make 'app_name' dynamic
    """
    def _cached(function):
        def wrapper(*args, **kw):
            kw.update(zip(function.__code__.co_varnames, args))
            env_dir = os.environ.get("J_CACHE_DIR")
            if not env_dir:
                cache_dir = user_cache_dir(app_name, app_name)
            else:
                cache_dir = os.path.join(env_dir, app_name)

            file_name = kw_to_fname(**kw)
            path = os.path.join(cache_dir, file_name)
            if not os.path.isfile(path):
                if not os.path.exists(cache_dir):
                    os.makedirs(cache_dir)
                j = function(**kw)
                with open(path, 'wb') as fp:
                    pickle.dump(j, fp)
            else:
                with open(path, 'rb') as fp:
                    j = pickle.load(fp)
            return j
        return wrapper
    return _cached

def pool(function, params, use_threads=True, max_workers=2):
    if use_threads:
        with ThreadPoolExecutor(max_workers=max_workers) as ex:
            dfs = ex.map(function, *zip(*params))
    else:
        dfs = []
        for param in params:
            try:
                r = function(*param)
            except:
                raise
            dfs.append(r)
    return dfs

def live_cache(app_name):
    """Caches the output for time_out specified. This is done in order to
    prevent hitting live quote requests to NSE too frequently. This wrapper
    will fetch the quote/live result first time and return the same result for
    any calls within 'time_out' seconds.

    Logic:
        key = concat of args
        try:
            cached_value = self._cache[key]
            if now - self._cache['tstamp'] < time_out
                return cached_value['value']
        except AttributeError: # _cache attribute has not been created yet
            self._cache = {}
        finally:
            val = fetch-new-value
            new_value = {'tstamp': now, 'value': val}
            self._cache[key] = new_value
            return val

    """
    def wrapper(self, *args, **kwargs):
        """Wrapper function which calls the function only after the timeout,
        otherwise returns value from the cache.

        """
        # Get key by just concating the list of args and kwargs values and hope
        # that it does not break the code :P
        inputs =  [str(a) for a in args] + [str(kwargs[k]) for k in kwargs]
        key = app_name.__name__ + '-'.join(inputs)
        now = datetime.now()
        time_out = self.time_out
        try:
            cache_obj = self._cache[key]
            if now - cache_obj['timestamp'] < timedelta(seconds=time_out):
                return cache_obj['value']
        except:
            self._cache = {}
        value = app_name(self, *args, **kwargs)
        self._cache[key] = {'value': value, 'timestamp': now}
        return value

    return wrapper


try:
    from cv2 import cv2
except Exception:
    import cv2
import numpy as np

max_x = 1000
max_y = 500

def resize(img, x = 800, y = 800):
    return cv2.resize(img, (x,y), interpolation = cv2.INTER_AREA)

def auto_resize(img):
    if (img.shape[0] / img.shape[1]) > (max_y / max_x):
        return resize(img, int(max_y * img.shape[1] / img.shape[0]), max_y)
    else:
        return resize(img, max_x, int(max_x * img.shape[0] / img.shape[1]))
    return("forbidden poop")

def get_blank_image(rows,cols,color = False):
    if color:
        return np.zeros((rows, cols, 3), np.uint8)
    else:
        return np.zeros((rows, cols, 1), np.uint8)

def copy_blank(image):
    im = image.copy()
    im.fill(0)
    return im


n, t = map(int, input().split())
study = [(0, 0)]

for _ in range(n):
    k, s = map(int, input().split())
    study.append((k, s))

arr = [[0 for _ in range(t + 1)] for _ in range(n + 1)]

for i in range(1, n + 1):
    for j in range(1, t + 1):
        time = study[i][0]
        score = study[i][1]

        if j < time:
            arr[i][j] = arr[i - 1][j]
        else:
            arr[i][j] = max(arr[i - 1][j - time] + score, arr[i - 1][j])

print(arr[i][j])


from flask import (
    Blueprint,
    render_template,
    request,
    Response,
)
from .configloader import config
import os
from .utils import *
import random
import traceback

router = Blueprint("router", __name__, url_prefix="/")
root_folder = os.path.dirname(os.path.abspath(__file__))

# 404 Page
@router.app_errorhandler(404)
@router.app_errorhandler(405)
def not_found(e):
    return render_template("error.html", title="404 - Page not found", message="Ala ala, are you lost ?"), 404

@router.app_errorhandler(403)
def unauthorized(e):
    return render_template("error.html", title="403 - Unauthorized", message="Ala ala, are you allowed to see this page ?"), 403

if config["env"] == "production":
    @router.errorhandler(Exception)
    def server_error(e):
        print(traceback.format_exc())
        return render_template("error.html", title="500 - Internal server error", message="Ala ala, an error occured, try in few minutes"), 500

@router.app_errorhandler(500)
def server_error(e):
    return render_template("error.html", title="500 - Internal server error", message="Ala ala, an error occured, try in few minutes"), 500

# Home route
@router.route("/", methods=["GET"])
def home():
    return render_template("home.html", title="File uploader", max_size=config["upload"]["max_size"], git_hash=git_hash())

# FAQ route
@router.route("/faq", methods=["GET"])
def faq():
    return render_template("faq.html", title="FAQ", ext_unauthorized=config["upload"]["unauthorized_ext"], git_hash=git_hash())

# ShareX route
@router.route("/sharex", methods=["GET"])
def sharex():
    return render_template("sharex.html", title="ShareX", git_hash=git_hash())

# Upload files
@router.route("/upload", methods=["POST"])
def upload_files():
    # Get upload domain
    if "UPLOAD_DOMAIN" in request.form:
        if request.form["UPLOAD_DOMAIN"] not in config["upload"]["domain"]:
            return json_with_statuscode({
                "success": False,
                "error": "Invalid upload domain."
            }, 400)
        else:
            upload_domain = request.form["UPLOAD_DOMAIN"]
    else:
        upload_domain = random.choice(config["upload"]["domain"])

    # Get (and create if not exist) upload dir
    upload_dir = os.path.normpath(os.path.join(
        root_folder, config["upload"]["folder"]))
    if not os.path.exists(upload_dir):
        os.mkdir(upload_dir)

    # check if user has uploaded a file
    if len(request.files.getlist("upload[]")) < 1:
        return json_with_statuscode({
            "success": False,
            "error": "You must upload least than one file."
        }, 400)

    files = request.files.getlist("upload[]")
    process_files = []

    # process files
    for file in files:
        # Check file size
        size = uploaded_file_size(file)
        if convert_to_megabites(size) > int(config["upload"]["max_size"]):
            process_files.append({
                "success": False,
                "error": "File too big"
            })
            continue

        # Check file extention
        if "." in file.filename:
            ext = os.path.splitext(file.filename)[1]
        else:
            ext = None

        if ext in config["upload"]["unauthorized_ext"]:
            process_files.append({
                "success": False,
                "error": "Invalid extention"
            })
            continue

        retry_filename = 0
        find_uniq = False

        while retry_filename < int(config["upload"]["retry_filename"]) and not find_uniq:
            upload_filename = generate_filename(ext)

            if not os.path.exists(os.path.join(upload_dir, upload_filename)):
                find_uniq = True

            retry_filename += 1

        if not find_uniq:
            process_files.append({
                "success": False,
                "error": "Unable to find unique name."
            })
            continue

        file.save(os.path.join(upload_dir, upload_filename))

        process_files.append({
            "success": True,
            "original_filename": file.filename,
            "filename": upload_filename,
            "url": "{}/{}".format(upload_domain, upload_filename),
            "size": size
        })

    return {
        "success": True,
        "files": process_files
    }


#!/usr/bin/env python3
import pyautogui
import rospy

def points_callback(data):
    touch_point = data.data.split()
    x_pos = int(touch_point[0])
    y_pos = int(touch_point[1])
    if 0 <= x_pos <= 1920 and 0 <= y_pos <= 1056:
        print(x_pos, y_pos)
        pyautogui.moveTo(x_pos, y_pos)

rospy.init_node('point_grapher', anonymous=True)
point_sub = rospy.Subscriber("/on_screen_touch_point", String, points_callback)
rospy.spin()


import json
import os
import os.path
import re
import unittest

import six

from gherkin_parser import ParseError, parse_lines

class ParserTestCaseMixin(object):
    def parse(self, feature_string):
        return parse_lines(feature_string.split('\n'))

    def assertErrorMessage(self, feature_string, message):
        with self.assertRaises(ParseError) as cm:
            self.parse(feature_string)
        self.assertEqual(str(cm.exception), message)

class FeatureTagsTestCase(ParserTestCaseMixin, unittest.TestCase):
    def test_broken_tags(self):
        self.assertErrorMessage(u"""
            @tag broken tags
        """, "Tags must start with a '@' character, and not contain spaces (line 2)")

class FeatureTitleTestCase(ParserTestCaseMixin, unittest.TestCase):
    def test_empty_title(self):
        parsed = self.parse(u"""
            Feature:
        """)
        self.assertEqual(parsed['title']['content'], '')

    def test_missing_feature_title(self):
        self.assertErrorMessage(u"""
            Not a feature
        """, 'Expected feature title (line 2)')

    def test_multiple_feature_titles(self):
        self.assertErrorMessage(u"""
            Feature: Feature 1
                Scenario:
                    Given a given

            Feature: Feature 2
        """, "Unexpected {!r}. File must not contain multiple features (line 6)".format(six.text_type('Feature: Feature 2')))

class FeatureBackgroundTestCase(ParserTestCaseMixin, unittest.TestCase):
    def test_background_after_scenario(self):
        self.assertErrorMessage(u"""
            Feature:
                Scenario:

                Background:
                    Description 1
        """, "Unexpected {!r}. Background must not occur after scenarios (line 5)".format(six.text_type('Background:')))

class ScenarioTestCase(ParserTestCaseMixin, unittest.TestCase):
    def test_with_examples(self):
        self.assertErrorMessage(u"""
            Feature: Title
                Scenario: Title
                    Given I have a given

                    Examples:
        """, "Scenario block has examples section - should be 'scenario outline' (line 3)")

class ScenarioOutlineTestCase(ParserTestCaseMixin, unittest.TestCase):
    def test_without_examples(self):
        self.assertErrorMessage(u"""
            Feature: Title
                Scenario Outline: Title
                    Given I have a given
        """, "Scenario Outline block is missing an examples section (line 3)")


from weboob.capabilities.video import BaseVideo
from weboob.capabilities.image import Thumbnail
from weboob.capabilities.collection import Collection

from weboob.exceptions import ParseError
from weboob.browser.elements import ItemElement, ListElement, method
from weboob.browser.pages import HTMLPage, pagination, JsonPage
from weboob.browser.filters.standard import Regexp, Env, CleanText, DateTime, Duration, Field
from weboob.browser.filters.html import Attr, Link, CleanHTML, XPath
from weboob.browser.filters.json import Dict

import re

class VimeoDuration(Duration):
    _regexp = re.compile(r'PT(?P<hh>\d+)H(?P<mm>\d+)M(?P<ss>\d+)S')

class ListPage(HTMLPage):
    @pagination
    @method
    class iter_videos(ListElement):
        item_xpath = '//div[@id="browse_content"]/ol/li'
        next_page = Link(u'//a[text()="Next"]')

        class item(ItemElement):
            klass = BaseVideo

            obj_id = Regexp(Attr('.', 'id'), 'clip_(.*)')
            obj_title = Attr('./a', 'title')

            def obj_thumbnail(self):
                thumbnail = Thumbnail(self.xpath('./a/img')[0].attrib['src'])
                thumbnail.url = thumbnail.id
                return thumbnail

class SearchPage(HTMLPage):
    @pagination
    @method
    class iter_videos(ListElement):
        item_xpath = '//ul[@class="small-block-grid-3"]/li/div[has-class("clip_thumbnail")]'

        next_page = Link(u'//a[text()="Next"]')

        class item(ItemElement):
            klass = BaseVideo

            obj_id = Attr('.', 'data-clip-id')
            obj_title = Attr('./a/span', 'title')

            def obj_thumbnail(self):
                thumbnail = Thumbnail(self.xpath('./a/div/img')[0].attrib['src'])
                thumbnail.url = thumbnail.id
                return thumbnail

class VideoPage(HTMLPage):
    def __init__(self, *args, **kwargs):
        super(VideoPage, self).__init__(*args, **kwargs)
        from weboob.tools.json import json
        jsoncontent = XPath('//script[@type="application/ld+json"]/text()')(self.doc)[0]
        self.doc = json.loads(jsoncontent)[0]

    @method
    class get_video(ItemElement):
        klass = BaseVideo

        obj_id = Env('_id')
        obj_title = CleanText(CleanHTML(Dict('name')))
        obj_description = CleanHTML(Dict('description'))
        obj_date = DateTime(Dict('uploadDate'))
        obj_duration = VimeoDuration(Dict('duration'))
        obj_author = CleanText(Dict('author/name'))

        def obj_nsfw(self):
            _sfw = Dict('isFamilyFriendly', default="True")(self)
            return _sfw != "True"

        def obj_thumbnail(self):
            thumbnail = Thumbnail(Dict('thumbnailUrl')(self.el))
            thumbnail.url = thumbnail.id
            return thumbnail

class VideoJsonPage(JsonPage):
    @method
    class fill_url(ItemElement):
        klass = BaseVideo

        def obj_url(self):
            data = self.el

            if not data['request']['files']:
                raise ParseError('Unable to detect any stream method for id: %r (available: %s)'
                                 % (int(Field('id')(self)),
                                    data['request']['files'].keys()))

            # Choosen method is not available, we choose an other one
            method = self.obj._method
            if method not in data['request']['files']:
                method = data['request']['files'].keys()[0]

            streams = data['request']['files'][method]
            if not streams:
                raise ValueError('There is no url available for id: %r' % (int(Field('id')(self))))

            # stream is single for hls, just return the url
            stream = streams['url'] if method == 'hls' else None

            # ...but a list for progressive
            # we assume the list is sorted by quality with best first
            if not stream:
                quality = self.obj._quality
                stream = streams[quality]['url'] if quality < len(streams) else streams[0]['url']

            return stream.split('?')[0]

        obj_ext = Regexp(Field('url'), '.*\.(.*)$', '\\1')

class CategoriesPage(HTMLPage):
    @method
    class iter_categories(ListElement):
        item_xpath = '//div[@class="category_grid"]/div/a'

        class item(ItemElement):
            klass = Collection

            obj_id = CleanText('./@href')
            obj_title = CleanText('./div/div/p')

            def obj_split_path(self):
                split_path = ['vimeo-categories']
                category = CleanText('./@href', replace=[('/categories/', '')])(self)
                split_path.append(category)
                return split_path

class ChannelsPage(HTMLPage):
    @pagination
    @method
    class iter_channels(ListElement):
        item_xpath = '//div[@id="browse_content"]/ol/li'
        next_page = Link('//li[@class="pagination_next"]/a')

        class item(ItemElement):
            klass = Collection

            obj_title = CleanText('div/a/div/p[@class="title"]')
            obj_id = CleanText('./@id')

            def obj_split_path(self):
                split_path = ['vimeo-channels']
                channel = CleanText('div/a/@href', replace=[('/channels/', '')])(self)
                split_path.append(channel)
                return split_path


from .models import CustomerInfo, CustomerDocument
from django.forms import ModelForm
from django import forms

CUSTOMER_CHOICES = [
    ('commercial', 'Commercial'),
    ('private', 'Private'),
]

class CustomerTypeForm(forms.Form):
    customer_chioces = forms.CharField(label="Customertype", widget=forms.RadioSelect(choices=CUSTOMER_CHOICES))

class CustomerInfoForm(forms.ModelForm):
    class Meta:
        model = CustomerInfo
        fields = "__all__"

class CustomerDocumentForm(forms.ModelForm):
    class Meta:
        model = CustomerDocument
        fields = ['document']


import math
'''
    optimal scheduling problem: greedy

    given a list of intervals where an interval is semi open / closed --> [s, f)
        s < f

    find the optimum schedule, meaning the schedule with the most intervals possible that are compatible with each other

    interval a is compatible with b if they don't overlap
        b[0] >= a[1] or a[0] >= b[1]

'''
def optimalSchedule(intervals : list[list[int]]):
    # sort intervals by end time
    sortedIntervals = intervals[:]
    sortedIntervals.sort(key=lambda interval : interval[1])

    result = [[-math.inf, -math.inf]]

    for interval in sortedIntervals:
        if interval[0] >= result[-1][1]: # compatibility
            result.append(interval)

    return result[1:]

'''
example run through on hw 4 problem 8
'''
tasks = [[14,15],[10,13],[1,5],[4,6],[8,11],[11,16],[3,6],[2,4],[7,10],[12,14]]

# sort tasks by their end time (second item in the interval)
# if 2 end times are the same,sort by their start time
tasks = [[2,4],[1,5],[3,6],[4,6],[7,10],[8,11],[10,13],[12,14],[14,15],[11,16]]

# loop through sorted tasks and add element i to our result list if element i is
# compatible with the last element saved
lastInterval = [-math.inf, -math.inf]

i = 1
result = [[2,4]]
lastInterval = [2,4]

i = 2
result = [[2,4]] # elem at i = 2 isn't compatible --> don't add to result list
lastInterval = [2,4]

i = 3 # elem isn't compatible

i = 4
result = [[2,4],[4,6]]
lastInterval = [4,6]

i = 5
result = [[2,4],[4,6],[7,10]]
lastInterval = [7,10]

i = 6 # elem isn't compatible

i = 7
result = [[2,4],[4,6],[7,10],[10,13]]
lastInterval = [10,13]

i = 8 # elem isn't compatible

i = 9
result = [[2,4],[4,6],[7,10],[10,13],[14,15]]
lastInterval = [14,15]

i = 10 # elem isn't compatible


import random

class Hangman:
    def __init__(self, word_list, num_lives=5):
        self.word = random.choice(word_list).lower()
        self.word_guessed = ['_' for _ in self.word]
        self.num_letters = len(set(self.word))
        self.num_lives = num_lives
        self.word_list = word_list
        self.list_of_guesses = []

    def check_guess(self, guess):
        guess = guess.lower()
        if guess in self.word:
            print(f"Good guess! {guess} is in the word.")
            # Update the word_guessed to reveal the letter
            for index, letter in enumerate(self.word):
                if letter == guess:
                    self.word_guessed[index] = guess
            # Reduce the number of unique letters if this was the first occurrence of the letter
            if guess not in self.list_of_guesses:
                self.num_letters -= 1
        else:
            self.num_lives -= 1
            print(f"Sorry, {guess} is not in the word. You have {self.num_lives} lives left.")

    def ask_for_input(self):
        while True:
            guess = input("Guess a letter: ")
            if not guess.isalpha() or len(guess) != 1:
                print("Invalid letter. Please, enter a single alphabetical character.")
            elif guess in self.list_of_guesses:
                print("You already tried that letter!")
            else:
                self.list_of_guesses.append(guess)
                self.check_guess(guess)
                break  # Exit the loop if a valid guess was made

if __name__ == "__main__":
    word_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
    game = Hangman(word_list)

    # Keep asking for user input until the word is guessed or lives run out
    while game.num_lives > 0 and '_' in game.word_guessed:
        print(f"Word guessed so far: {' '.join(game.word_guessed)}")
        game.ask_for_input()

        if game.num_letters == 0:
            print(f"Congratulations! You've guessed the word '{game.word}' correctly!")
            break
        elif game.num_lives == 0:
            print(f"Game over! The word was '{game.word}'. Better luck next time.")


# https://www.kaggle.com/c/boston-housing
# https://towardsdatascience.com/linear-regression-on-boston-housing-dataset-f409b7e4a155

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

#l load dataset from scikit-learn
from sklearn.datasets import load_boston
boston_dataset = load_boston()

print(boston_dataset.keys())
# dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename'])
# 'data' - contains the info for various houses
# 'target' - prices of the house
# 'feature_names' - names of the features
# 'DESCR' - describes the dataset

# print more about the dataset
print(boston_dataset.DESCR)

# load data into pandas dataframe
boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
print(boston.head())

# Prepare the data for training the mode
boston["PRICE"] = boston_dataset.target
boston.isnull().sum() # count the number of missing values

X = boston.drop('PRICE', axis=1)
Y = boston['PRICE']

# split the data into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
print("X_train: ", X_train.shape, "\n",
      "Y_train: ", Y_train.shape, "\n",
      "X_test: ", X_test.shape, "\n",
      "Y_test: ", Y_test.shape)

# X_train:  (404, 2)
# Y_train:  (404,)
# X_test:  (102, 2)
# Y_test:  (102,)

# plot regression
from sklearn.linear_model import LinearRegression
linearRegression = LinearRegression()
linearRegression.fit(X_train, Y_train)

Y_pred = linearRegression.predict(X_test)

plt.scatter(Y_test, Y_pred)
plt.xlabel("Prices")
plt.ylabel("Predicted prices")
plt.title("Boston houses prices")
plt.savefig('DL_hw1.png')

# compute mean squared error
# https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html
from sklearn.metrics import mean_squared_error

# number of samples : [102, 404] - it not works
meanSquaredError = mean_squared_error(Y_test, Y_train)
print("mean squared error: ", meanSquaredError)


import train_cnn as cnn
from source import params
import eval

def main():
    args = params.opt

    if args.evaluate:
        eval.evaluate(args.path, args.dataset)
    else:
        cnn.train()

if __name__ == '__main__':
    main()


import logging
import shutil
import tempfile
import zipfile
from pathlib import Path

from ..helpers.system import download_file
from .git_url import GitUrl

LOGGER = logging.getLogger(__name__)

def git_download_zip(repo_url: str, target_folder: Path, branch: str, commit: str = ""):
    """Download Repo Zip from Github.

    Parameters
    ----------
    repo_url : str
        Github Repo Url
    target_folder : Path
        Download Target
    branch : str
        BRanch to download
    commit : str, optional
        Specific Commit to download, by default ""

    Raises
    ------
    FileNotFoundError
        If Download failed
    """
    git_url = GitUrl(repo_url)
    download_url = git_url.get_archive_url(ref=commit or branch)
    with tempfile.TemporaryDirectory() as tdir:
        zip_path = Path(tdir) / f"{git_url.name}.zip"
        LOGGER.info("Downloading GitRepo Zip: '%s'", download_url)
        LOGGER.debug("Target Path: '%s' ", zip_path)
        download_file(download_url, zip_path)
        if not zip_path.exists():
            raise FileNotFoundError(f"Could not download Repo Zip from: {download_url}")
        LOGGER.info("Extracting GitRepo Zip: %s", git_url.name)
        ex_location = Path(tdir) / "extract"
        with zipfile.ZipFile(zip_path, "r") as zip_ref:
            zip_ref.extractall(ex_location)
        for path in ex_location.glob("*"):
            LOGGER.info("Moving %s to %s", path.stem, target_folder)
            shutil.rmtree(target_folder, ignore_errors=True)
            path.rename(target_folder)
            break


res = 0

class Node:
    def __init__(self, level):
        self.children = {}
        self.value = None
        self.level = level

    def insert(self, value):
        node = self
        for c in value:
            if c not in node.children:
                node.children[c] = Node(self.level + 1)
            node = node.children[c]
        node.value = value

    def print(self):
        if self.value is not None:
            print(self.value)
        for k in self.children:
            print(">", end="")
            self.children[k].print()
            print("<", end="")

    def compact(self):
        node = self
        global res
        to_be_deleted_keys = set()
        for k, child in node.children.items():
            child.compact()
            if len(child.children) == 0 and child.value is None:
                # delete
                to_be_deleted_keys.add(k)
        for k in to_be_deleted_keys:
            del node.children[k]

        if len(node.children) == 1 and len(list(node.children.values())[0].children) == 0:
            if node.value:
                # print("+", node.value, list(node.children.values())[0].value)
                res += 2
                node.value = None
            else:
                node.value = list(node.children.values())[0].value
            node.children = {}

        if len(node.children) >= 2 and self.level > 0:
            l = list(node.children.values())
            if (l[0].value is not None and l[1].value is not None):
                # print("+", l[0].value, l[1].value)
                res += 2
                node.children = {}

t = int(input())  # read a line with a single integer
for i in range(1, t + 1):
    res = 0
    root = Node(0)
    n = int(input())
    ws = [input() for w in range(n)]
    for w in ws:
        root.insert(w[::-1])
    # root.print()
    root.compact()
    # root.print()
    print("Case #{}: {}".format(i, res))


from django.urls import path

from users import views

urlpatterns = [
    path('signup/<str:public_id>/', views.SignUpView.as_view(), name='signup'),
    path('profile/edit/', views.EditProfileView.as_view(), name='profile_edit'),
    path('currencies/', views.ListProfileCurrencyView.as_view(), name='currencies_list'),
    path('currencies/new/', views.CreateProfileCurrencyView.as_view(), name='currency_create'),
    path('currencies/<int:pk>/delete/', views.DeleteProfileCurrencyView.as_view(), name='currency_delete'),
    path('invitations/', views.ShowInvitationsView.as_view(), name='invitations'),
    path('submissions/', views.BandSubmissionsView.as_view(), name='submissions'),
    path('submission-details/<int:pk>', views.BandSubmissionDetailView.as_view(), name='submission_details'),
    path('trade-requests/', views.TradeRequestListView.as_view(), name='trade_requests'),
    path('trade-details/<int:pk>/', views.TradeRequestDetailView.as_view(), name='trade_details'),
    path('user-trade-details/<int:pk>/', views.UsersTradeRequestDetailView.as_view(), name='user_trade_details'),
]


from django.contrib.auth import authenticate, logout
from django.shortcuts import render, get_object_or_404
from rest_framework import generics, status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from users.models import User, Friendship
from users.serializers import UserDetailSerializer, UsersListSerializer, \
    UserFriendRequestSerializer
from users.utils import friend_accept_util

@api_view(['GET'])
def user_list(request):
    all_users = User.objects.all()
    serializer = UsersListSerializer(all_users, many=True)

    return Response(serializer.data)

@api_view(['GET'])
def user_me(request):
    user = request.user
    serializer = UserDetailSerializer(user)

    return Response(serializer.data)

@api_view(['POST'])
def friend_request(request, user_id):
    auth_user = request.user
    another_user = User.objects.filter(id=user_id).first()
    auth_user.friends.add(another_user)

    serializer = UserFriendRequestSerializer(another_user)

    return Response(serializer.data)

@api_view(['POST'])
def friend_accept(request, user_id):
    to_user_id = user_id
    from_user = request.user
    status_to_change = request.data['status']

    friend_accept_util(from_user, to_user_id, status_to_change)

    return Response(True)

@api_view(['GET'])
def friends(request):

    user = request.user

    serializer = UsersListSerializer(user.friends, many=True)
    return Response(serializer.data)


#!/usr/bin/python
import rospy
import numpy as np
from std_msgs.msg import Float32
from sensor_msgs.msg import PointCloud

class WallDetectorNode:
	def __init__(self):
		# Subscribe to laser data
		rospy.Subscriber("point_cloud", PointCloud, self.point_cloud_callback)

		# Publish a distance to wall and signed angle(radians) to turn
		self.wall_pub_dist = rospy.Publisher("wall_detector/distance", Float32, queue_size=10)
		self.wall_pub_theta = rospy.Publisher("wall_detector/theta", Float32, queue_size=10)

	def point_cloud_callback(self, msg):
		x = []
		y = []
		for point in msg.points:
			if -3 <= point.x <= 3 and -10 < point.y < -0.3:
				x.append(point.x)
				y.append(point.y)

		if(len(x) < 5):
			return;

		m, b = np.polyfit(x,y,1)

		origin = [0,0]
		norm = [-m, 1]

		distance = abs(np.dot(norm, origin)-b)/np.linalg.norm(norm)
		theta = -np.math.atan2(np.cross(norm, [0,1]), np.dot(norm, [0,1]))

		wall_msg_dist = Float32()
		wall_msg_theta = Float32()
		wall_msg_dist.data = distance
		wall_msg_theta.data = theta

		self.wall_pub_dist.publish(wall_msg_dist)
		self.wall_pub_theta.publish(wall_msg_theta)

if __name__ == "__main__":
	rospy.init_node("wall_detector_node")
	WallDetectorNode()
	rospy.spin()


decrescente = True
anterior = int(input("Digite o primeiro numero da sequencia: "))
valor = 1

while valor != 0 and decrescente:
     valor = int(input("Digite o proximo numero da sequencia: "))
     if valor > anterior:
          decrescente = False
     anterior = valor

if decrescente == True:
     print("SHOW! Ordem descrescente!!")
else:
     print("Ordem nao decrescente!")


from coordinate_system import CoordinateSystem
from fsm import FSM
from vaccine import Vaccine
from operate import Operate
import constants
from report import Report
from multiprocessing import Process
from random import randint

def plan(fileoutName,virusPlotName,runNumber):

	fileT = fileoutName+str(runNumber)+".dat"
	fileT2 = virusPlotName+str(runNumber)

	l = []
	for i in range(0,constants.N_vacc):
		x = randint(constants.cs_minX,constants.cs_maxX)
		y = randint(constants.cs_minY,constants.cs_maxY)
		l.append((x,y))

	operator = Operate(CoordinateSystem(),[FSM(24,1)],Vaccine(l))
	reporter = Report(operator,fileT,fileT2,[0.33,0.42,0.5,0.58,0.67])

	for i in range(constants.N_turns):
		operator.run()
		reporter.update()
		reporter.reveal_virus(i)

	reporter.output()

def main():
	n_cores = 48
	for i in range(100):
		print(i)
		p = Process(target=plan, args=('Feb9_run_','virus_spatial_',i))
		p.start()
		if(i % n_cores == 0 and i != 0):
			p.join()

if __name__ == "__main__":
	main()


# https://www.acmicpc.net/problem/11725

import sys
from collections import deque

input = sys.stdin.readline

N = int(input())

Tree = [[] for _ in range(N+1)]

answer = [-1]*(N+1)
visited = [-1]*(N+1)

for i in range(N-1):
    parent, child = map(int, input().split())
    Tree[parent].append(child)
    Tree[child].append(parent)

queue = deque()

queue.append(1)
visited[1] = 0

while queue:
    new_Node = queue.popleft()
    for i in Tree[new_Node]:
        if(visited[i] == -1):
            answer[i] = new_Node
            visited[i] = 0
            queue.append(i)

for i in answer[2:]:
    print(i)


from flask import Flask, request, jsonify

app = Flask(__name__)

# Sample data (for demonstration purposes)
doctors = [
    {
        "id": 1,
        "name": "Dr. John Smith",
        "specialization": "Internal Medicine",
        "available_days": ["Monday", "Tuesday", "Wednesday"],
        "max_patients": 5,
    },
    {
        "id": 2,
        "name": "Dr. Jane Doe",
        "specialization": "Pediatrics",
        "available_days": ["Tuesday", "Thursday", "Friday"],
        "max_patients": 6,
    },
]

# Defining a route to list all doctors
@app.route("/doctors", methods=["GET"])
def list_doctors():
    return jsonify(doctors)

# Defining a route to retrieve details of a specific doctor
@app.route("/doctors/<int:doctor_id>", methods=["GET"])
def get_doctor(doctor_id):
    doctor = next((doc for doc in doctors if doc["id"] == doctor_id), None)
    if doctor:
        return jsonify(doctor)
    return jsonify({"error": "Doctor not found"}), 404

# Defining a route to book an appointment with a doctor
@app.route("/appointments", methods=["POST"])
def book_appointment():
    data = request.get_json()
    doctor_id = data.get("doctor_id")
    appointment_date = data.get("appointment_date")
    return jsonify({"message": "Appointment booked successfully"})

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


# import packages
import glob
from pathlib import Path
import os
import numpy as np
from datetime import datetime
from datetime import timedelta
import pandas as pd
import calendar
import geopandas as gpd
import cartopy
import matplotlib.pyplot as plt
import math
from pathos.threading import ThreadPool as Pool
from scipy.optimize import least_squares
import sklearn
from sklearn.linear_model import LinearRegression
from scipy.stats import gaussian_kde
import statsmodels.api as sm
from statsmodels.regression.linear_model import OLS
from statsmodels.tools import add_constant
import random
from scipy.optimize import minimize

def snow_calculation(catch_id,work_dir):
    # load p-ep-tas timeseries
    file = glob.glob(f'{work_dir}/output/forcing_timeseries/processed/daily/{catch_id}*.csv')[0]
    ts = pd.read_csv(f'{file}',index_col=0)
    # ts = ts.loc[start_date:end_date] #this should be based on sr - or do this for the full timeseries???
    p = ts.p.values
    tas = ts.tas.values

    # load mean elevation
    file = glob.glob(f'{work_dir}/output/elevation/stats_hydrosheds/ele_{catch_id}.csv')[0]
    elm = pd.read_csv(f'{file}',index_col=0)

    # load elevation zones
    file = glob.glob(f'{work_dir}/output/elevation/el_zones/{catch_id}*.csv')[0]
    elz = pd.read_csv(f'{file}',index_col=0)

    # snow parameters
    TT = 0
    MF = 2

    # make empty matrices with timseries rows and elevation zones columns
    Pm_el = np.zeros((len(p),len(elz))) # melt water
    Pl_el = np.zeros((len(p),len(elz))) # liquid precipitation
    Ps_el = np.zeros((len(p),len(elz))) # solid precipitation

    for j in range(len(elz)):
        Ss = np.zeros(len(p)) # snow storage
        Pm = np.zeros(len(p)) # melt water
        Pl = np.zeros(len(p)) # liquid precipitation
        Ps = np.zeros(len(p)) # solid precipitation
        T = np.zeros(len(p)) # temperature

        # temperature difference for elevation zone
        el_dif = elm.mean_ele - elz.loc[j]['mean_el']
        dt = (el_dif/1000.)*6.4

        # loop over timesteps and compute ps, pm and pl
        for i in range(0,len(p)):
            Tmean = tas[i]
            T[i] = Tmean+dt

            if T[i]>TT:
                Pl[i] = p[i]
                Ps[i] = 0

                Pm[i] = min(Ss[i],MF*(T[i]-TT))
                Ss[i] = max(0, Ss[i]-Pm[i])
            else:
                Ps[i] = p[i]
                Pl[i] = 0
                Ss[i] = Ss[i]+Ps[i]
            if i<len(p)-1:
                Ss[i+1] = Ss[i]

        # scale to coverage of elevation zone and add to matrix
        Ps = Ps * elz.loc[j]['frac']
        Pm = Pm * elz.loc[j]['frac']
        Pl = Pl * elz.loc[j]['frac']
        Pm_el[:,j] = Pm
        Pl_el[:,j] = Pl
        Ps_el[:,j] = Ps

    # sum fractions of pm, pl and ps
    pm = Pm_el.sum(axis=1)
    pl = Pl_el.sum(axis=1)
    ps = Ps_el.sum(axis=1)

    # add to forcing dataframe
    ts['pm'] = pm
    ts['pl'] = pl
    ts['ps'] = ps
    ts.to_csv(f'{work_dir}/output/snow/timeseries/{catch_id}.csv')

def run_function_parallel_snow(
    catch_list=list,
    work_dir_list=list,
    # threads=None
    threads=100
    ):
    """
    Runs function snow_calculation  in parallel.

    catch_list:  str, list, list of catchmet ids
    work_dir_list:     str, list, list of work dir
    threads:         int,       number of threads (cores), when set to None use all available threads

    Returns: None
    """
    # Set number of threads (cores) used for parallel run and map threads
    if threads is None:
        pool = Pool()
    else:
        pool = Pool(nodes=threads)
    # Run parallel models
    results = pool.map(
        snow_calculation,
        catch_list,
        work_dir_list,
    )