from django import forms
from django.forms import CheckboxSelectMultiple

from .models import ProcessoLicitatorio, Material, CPUCompleto

class ProcessoLicitatorioForm(forms.ModelForm):
    class Meta:
        model = ProcessoLicitatorio
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

class MaterialForm(forms.ModelForm):
    required_css_class = 'required'

    proc_licitatorio = forms.ModelChoiceField(
        label='Processo',
        queryset=None,
    )

    class Meta:
        model = Material
        fields = '__all__'
        exclude = ('status',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        #Filtra os processos ativos
        processos_ativos = ProcessoLicitatorio.objects.filter(status='1')

        self.fields['proc_licitatorio'].queryset = processos_ativos

        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

class CPUCompletoForm(forms.ModelForm):
    class Meta:
        model = CPUCompleto
        fields = '__all__'
        exclude = ('status',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'


from os import environ
from diagrams import Diagram, Cluster, Edge
from diagrams.saas.cdn import Cloudflare
from diagrams.onprem.client import User
from diagrams.aws.network import ELB
from diagrams.onprem.network import Nginx
from diagrams.onprem.aggregator import Fluentd
from diagrams.elastic.elasticsearch import Elasticsearch
from diagrams.programming.framework import React
from diagrams.onprem.database import Mongodb
from diagrams.aws.storage import SimpleStorageServiceS3BucketWithObjects
from diagrams.programming.language import Go as Golang, Javascript, Typescript

def create_cloud_infrastructure_diagram(company_name = ""):
    """
    Creates a diagram of the cloud infrastructure for the web application.
    """

    with Diagram(company_name + " Cloud Infrastructure",
                filename="infrastructure_diagram",
                show=False,
                direction="LR",
                outformat="png"
                ):

        with Cluster("EKS Cluster", graph_attr={
            # "pad": "6.0",
            "center": "true"
        }):

            with Cluster("Controller",graph_attr = {
                "bgcolor": "transparent",
            }):
                ingress_controller = Nginx("Ingress \nController")

            with Cluster("Frontend App",graph_attr = {
                "bgcolor": "transparent",
                "fontcolor": "bold",
            }):
                frontend_service = React("Frontend App")

            with Cluster("Backend \nAPI Services",graph_attr = {
                "bgcolor": "transparent",
                "fontcolor": "bold",
            }):
                api_gateway = Typescript("API \nGateway")

                with Cluster(label="Microservices", graph_attr = {
                    "bgcolor": "transparent",
                    "style": "invis",
                }):
                    microservices = [
                        Typescript("Auth API\nService"),
                        Golang("Company API\nService"),
                        Javascript("Notification API\nService")
                    ]

            with Cluster(label="Metrics \nCollection", graph_attr = {
                "bgcolor": "transparent",
                "fontcolor": "bold",
                "comment": "Responsible for logging collection and parsing"
            }):
                aggregator = Fluentd("Fluentd\n(Logging)")

        with Cluster("External", graph_attr = {
                "bgcolor": "transparent",
                "fontcolor": "invis",
            }):

            with Cluster("Database", graph_attr = {
                "bgcolor": "transparent",
            }):
                mongo_db = Mongodb("MongoDB")

            elasticsearch = Elasticsearch("Elasticsearch")
            s3_bucket = SimpleStorageServiceS3BucketWithObjects("S3 Bucket")

        # CONNECTIONS

        __ingres_color__ = "darkgreen"
        __api_gate_conn__ = "darkblue"
        __metrics__ = "darkorange"
        __database__ = "darkblue"

        load_balancer = ELB("Load Balancer")

        User("End User") >> Cloudflare("Cloudflare") >> load_balancer

        load_balancer \
            >> Edge(color=__ingres_color__, style="bold") \
            >>  ingress_controller

        ingress_controller \
            >> Edge(color=__ingres_color__, style="bold") \
            >> frontend_service

        frontend_service \
            >> Edge(color=__metrics__,style="dashed") \
            >> aggregator

        ingress_controller \
            >> Edge(color=__ingres_color__, style="bold") \
            >> api_gateway

        api_gateway \
            >> Edge(color=__metrics__,style="dashed") \
            >> aggregator

        api_gateway \
            >> Edge(color=__api_gate_conn__, label="REST") \
            >> microservices

        microservices \
            >> Edge(color=__metrics__,style="dashed") \
            >> aggregator

        microservices \
            >> Edge(color=__database__, style="dashed") \
            >> mongo_db

        aggregator \
            >> elasticsearch

        aggregator \
            >> s3_bucket

company_name = environ.get("COMPANY_NAME")
create_cloud_infrastructure_diagram(company_name=company_name)


#!/usr/bin/env python3
"""
Convert the format of input file to output file.

It infers the input and output file types from their extension:
  py, csv, json

Please run in an environment set for Python 3.7, and navigate to this module in the lib directory.
example:
    convert.py --in "C:\\Users\\username\\Downloads\\converter\\tests\\files_input\\file00.py"
    --out "C:\\Users\\username\\Downloads\\converter\\temp\\files_ouput\\file00.csv"
"""
import os
import io
import argparse
import ast
import csv
import json

class BaseConverter:
    @staticmethod
    def deserialise(s):
        """Deserialise string into a dict"""
        return {}

    @staticmethod
    def serialise(d):
        """Serialise dict into a string"""
        return ""

class PyConverter(BaseConverter):
    @staticmethod
    def deserialise(s):
        return ast.literal_eval(s)

    @staticmethod
    def serialise(d):
        return repr(d)

class CsvConverter(BaseConverter):
    @staticmethod
    def deserialise(s):
        reader = csv.DictReader(s.splitlines())
        return list(reader)

    @staticmethod
    def serialise(d):
        output = io.StringIO()
        writer = csv.DictWriter(output, fieldnames=d[0].keys())
        writer.writeheader()
        writer.writerows(d)
        return output.getvalue()

class JsonConverter(BaseConverter):
    @staticmethod
    def deserialise(s):
        return json.loads(s)

    @staticmethod
    def serialise(d):
        return json.dumps(d)

# todo: implement yaml support
class YamlConverter(BaseConverter):
    @staticmethod
    def deserialise(s):
        raise NotImplemented

    @staticmethod
    def serialise(d):
        raise NotImplemented

class ConvertInput:
    """ Convert input file for serialisation or deserialisation."""
    def __init__(self):
        # mapping between file type extension and converter class
        self.converter_type_map = {
            ".py": PyConverter,
            ".csv": CsvConverter,
            ".json": JsonConverter
        }

    def get_supported_extensions(self, printout=False):
        ext_list = []
        for ext in self.converter_type_map:
            ext_list.append(ext)
        if printout:
            print("The following extensions are supported: {ext_list}")
        return ext_list

    def get_converter(self, filename):
        """ Raise error if the conversion type does not match those specified."""
        try:
            file_ext = os.path.splitext(filename)[1]
            return self.converter_type_map[file_ext]
        except KeyError:
            raise Exception(f"Unrecognised file type: {filename}")

    def do_conversion(self, input_file, output_file):
        """ Detect file types, if compatible, run conversion.
        Reads input file, writes output file, in the chosen format.
        Returns the converted data as a Python dict.
        """
        # get input deserialiser
        deserialise = self.get_converter(input_file).deserialise
        # get output serialiser
        serialise = self.get_converter(output_file).serialise
        # read input
        with open(input_file) as file:
            input_string = file.read()
        # deserialise input to Python dict
        data = deserialise(input_string)
        # serialise to output
        output_string = serialise(data)
        # save output
        with open(output_file, "w") as write_file:
            write_file.write(output_string)
        return data

def main(args):
    convert = ConvertInput()
    outputData = convert.do_conversion(args.input_file, args.output_file)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Take input file and serialise/deserialise to output file")
    parser.add_argument("--in", help="input filename", dest="input_file", type=str, required=True)
    parser.add_argument("--out", help="output filename", dest="output_file", type=str, required=True)
    parser.set_defaults(func=main)
    args = parser.parse_args()
    try:
        outputData = args.func(args)
        print(f"Converted {args.input_file} to {args.output_file}")
    except Exception as e:
        print(f"Failed to convert {args.input_file} to {args.output_file}: {e}")


import gettext
import os

from jinja2 import Environment, FileSystemLoader
from jupyter_server.base.handlers import FileFindHandler, path_regex
from jupyter_server.utils import url_path_join
from jupyterlab_server.themes_handler import ThemesHandler

from .tornado.contentshandler import VoilaContentsHandler

from .configuration import VoilaConfiguration
from .tornado.handler import TornadoVoilaHandler
from .paths import ROOT, collect_static_paths, collect_template_paths, jupyter_path
from .shutdown_kernel_handler import VoilaShutdownKernelHandler
from .static_file_handler import (
    MultiStaticFileHandler,
    TemplateStaticFileHandler,
    AllowListFileHandler,
)
from .tornado.treehandler import TornadoVoilaTreeHandler
from .utils import get_data_dir, get_server_root_dir, pjoin

def _jupyter_server_extension_points():
    """
    Returns a list of dictionaries with metadata describing
    where to find the `_load_jupyter_server_extension` function.
    """
    return [{"module": "voila.server_extension"}]

def _load_jupyter_server_extension(server_app):
    web_app = server_app.web_app
    # common configuration options between the server extension and the application
    voila_configuration = VoilaConfiguration(parent=server_app)
    template_name = voila_configuration.template
    template_paths = collect_template_paths(["voila", "nbconvert"], template_name)
    static_paths = collect_static_paths(["voila", "nbconvert"], template_name)

    jenv_opt = {"autoescape": True}
    env = Environment(
        loader=FileSystemLoader(template_paths),
        extensions=["jinja2.ext.i18n"],
        **jenv_opt,
    )
    web_app.settings["voila_jinja2_env"] = env

    nbui = gettext.translation(
        "nbui", localedir=os.path.join(ROOT, "i18n"), fallback=True
    )
    env.install_gettext_translations(nbui, newstyle=False)

    host_pattern = ".*$"
    base_url = url_path_join(web_app.settings["base_url"])

    tree_handler_conf = {"voila_configuration": voila_configuration}

    themes_dir = pjoin(get_data_dir(), "themes")
    web_app.add_handlers(
        host_pattern,
        [
            (
                url_path_join(base_url, "/voila/render/(.*)"),
                TornadoVoilaHandler,
                {
                    "config": server_app.config,
                    "template_paths": template_paths,
                    "voila_configuration": voila_configuration,
                },
            ),
            (
                url_path_join(base_url, "/voila"),
                TornadoVoilaTreeHandler,
                tree_handler_conf,
            ),
            (
                url_path_join(base_url, "/voila/tree" + path_regex),
                TornadoVoilaTreeHandler,
                tree_handler_conf,
            ),
            (
                url_path_join(base_url, "/voila/templates/(.*)"),
                TemplateStaticFileHandler,
            ),
            (
                url_path_join(base_url, r"/voila/api/themes/(.*)"),
                ThemesHandler,
                {
                    "themes_url": "/voila/api/themes",
                    "path": themes_dir,
                    "labextensions_path": jupyter_path("labextensions"),
                    "no_cache_paths": ["/"],
                },
            ),
            (
                url_path_join(base_url, "/voila/static/(.*)"),
                MultiStaticFileHandler,
                {"paths": static_paths},
            ),
            (
                url_path_join(base_url, r"/voila/api/shutdown/(.*)"),
                VoilaShutdownKernelHandler,
            ),
            (
                url_path_join(base_url, r"/voila/files/(.*)"),
                AllowListFileHandler,
                {
                    "allowlist": voila_configuration.file_allowlist,
                    "denylist": voila_configuration.file_denylist,
                    "path": os.path.expanduser(get_server_root_dir(web_app.settings)),
                },
            ),
            (
                url_path_join(base_url, r"/voila/api/contents%s" % path_regex),
                VoilaContentsHandler,
                tree_handler_conf,
            ),
        ],
    )

    # Serving lab extensions
    # TODO: reuse existing lab server endpoint?
    # First look into 'labextensions_path' configuration key (classic notebook)
    # and fall back to default path for labextensions (jupyter server).
    if "labextensions_path" in web_app.settings:
        labextensions_path = web_app.settings["labextensions_path"]
    else:
        labextensions_path = jupyter_path("labextensions")

    web_app.add_handlers(
        host_pattern,
        [
            (
                # TODO: update handler
                url_path_join(base_url, r"/voila/labextensions/(.*)"),
                FileFindHandler,
                {
                    "path": labextensions_path,
                    "no_cache_paths": ["/"],  # don't cache anything
                },
            )
        ],
    )

# For backward compatibility
load_jupyter_server_extension = _load_jupyter_server_extension


import gettext
import os
import json
import pkg_resources

warning_messages = []
def warn(out):
    warning_messages.append(out)

try:
    import ufw.util
    ufw.util.warn = warn  # monkey patch 'warn' to avoid garbage in console output.
    import ufw.frontend
    import ufw.common
    import ufw.parser
except:
    print("Error: ufw must be available. Aborting")
    sys.exit(126)

gettext.install(ufw)

__version__ = '0.2'

ufw_frontend = ufw.frontend.UFWFrontend(dryrun=False)
ufw_backend = ufw_frontend.backend

def is_ufw_active():
    for direction in ["input", "output", "forward"]:
        (rc, out) = ufw.util.cmd([
            ufw_backend.iptables,
            '-L',
            'ufw-user-%s' % direction,
            '-n'
        ])
        if rc == 1:
            return False
        elif rc != 0:
            raise ufw.common.UFWError("iptables: %s\n" % out)
    return True

def get_rules_as_dict():
    """ Returns all attributes of all rules as a list of dict """
    all_rules = ufw_backend.get_rules()
    all_rules_dict = []
    rule_number = 1
    for rule in all_rules:
        rule.number = rule_number
        rule.command = ufw.parser.UFWCommandRule.get_command(rule)
        rule_dict = {attrname: rule.__dict__[attrname] for attrname in rule.__dict__.keys()}
        all_rules_dict.append(rule_dict)
        rule_number += 1
    return all_rules_dict

def get_ufw_version():
    try:
        version = pkg_resources.get_distribution('ufw').version
    except:
        version = None
    return version

if __name__ == '__main__':
    rdl = get_rules_as_dict()
    output = {
        "ufw_get_status_json_version": __version__,
        "ufw_version": get_ufw_version(),
        "ufw_active": is_ufw_active(),
        "rules": rdl,
        "warnings": warning_messages
    }
    print(json.dumps(output, indent=4))


"""
Simple HTTP server for prediction.

Bottle does not play well with classes, so let's use plain methods

Requirements:
- bottle
- the Dataset object must implement
  - s_parse_request(q) --> batch (list[Example])
    where q = The request's forms MultiDict
    (https://bottlepy.org/docs/dev/api.html#bottle.BaseRequest.forms)
  - s_generate_response(q, batch, logit, prediction) --> any
"""
from __future__ import (absolute_import, division, print_function)
from bottle import post, request, run

@post('/pred')
def process():
    q = request.forms
    batch = EXP.dataset.s_parse_request(q)
    logit = EXP.model(batch)
    prediction = EXP.model.get_pred(logit, batch)
    return EXP.dataset.s_generate_response(q, batch, logit, prediction)

def start_server(exp, port):
    global EXP
    EXP = exp
    # This will open a global port!
    # Feel free to use a better server backend than wsgiref.
    # https://bottlepy.org/docs/dev/deployment.html
    run(server='wsgiref', host='0.0.0.0', port=port)
    print('\nGood bye!')


class Solution:
    """
    @param nums: an array of integer
    @param target: An integer
    @return: An integer
    """
    def twoSum6(self, nums, target):
        # write your code here
        nums.sort()
        l = 0
        r = len(nums) - 1
        output = 0
        while l < r:
            if nums[l] + nums[r] == target:
                while l + 1 < len(nums) and nums[l] == nums[l + 1]:
                    l += 1
                while r >= 0 and nums[r] == nums[r - 1]:
                    r -= 1
                output += 1
                if l >= r: break
                l += 1
                r -= 1
            elif nums[l] + nums[r] > target:
                r -= 1
            else:
                l += 1
        return output

sol = Solution()
sol.twoSum6([7, 11, 11, 1, 2, 3, 4], 22)


import sqlite3
import os, sys, re
import fnmatch
import argparse

MIME_TYPES = {
    "html": 'text/html',
    "txt": 'text/plain',
    "inc": 'text/plain',
    "js": 'application/javascript',
    "css": 'text/css',
    "mp3": "audio/mpeg",
    "json": "application/json",
    "woff": "application/font-woff",
    "svg": "image/svg+xml",
    "png": "image/png",
    "jpg": "image/jpeg",
    "jpeg": "image/jpeg",
    "gif": "image/gif",
    "ttf": "application/x-font-ttf",
    "ttc": "application/x-font-ttf",
    "otf": "application/x-font-opentype"
}

def recursive_glob(treeroot, pattern):
    results = []
    for base, dirs, files in os.walk(treeroot):
        goodfiles = fnmatch.filter(files, pattern)
        results.extend(os.path.join(base, f) for f in goodfiles)
    return results

def generateResDb(conn, path, dryrun, patch):
    c = conn.cursor()

    c.execute('''CREATE TABLE if not exists resources
                 (name text PRIMARY KEY, type text, content blob)''')

    for f in recursive_glob(path, "*"):
        filename, file_extension = os.path.splitext(f)
        if os.path.isfile(f):
            tp = MIME_TYPES[file_extension[1:]]
            name = re.sub(r'^[^/]*/', '~/', f)
            if patch == None:
              if dryrun:
                  print(f + " inserted")
              else:
                  c.execute("INSERT INTO resources VALUES (?, ?, ?)", (name, tp, sqlite3.Binary(open(f).read())))
            elif f == patch:
              if dryrun:
                  print(f + " updated")
              else:
                  c.execute("UPDATE resources SET content = ? WHERE name = ?", (sqlite3.Binary(open(f).read()), name))

    conn.commit()

def generateDb(args):
  conn = sqlite3.connect(args.output_file)
  conn.text_factory = str
  c = conn.cursor()
  c.execute('''CREATE TABLE if not exists words
               (key text PRIMARY KEY, value text)''')
  with open(args.input_file) as fp:
    line = fp.readline()
    entryState = "Key"
    while line:
        line = line.strip()
        if entryState == "Key":
            key = line
            value = ""
            entryState = "Value"
        elif entryState == "Value":
            if line == "</>":
              if args.patch == None:
                if args.dryrun:
                  print(key + " inserted")
                else:
                  c.execute("INSERT INTO words VALUES (?, ?)", (key, value))
              elif key == args.patch:
                if args.dryrun:
                    print(key + " updated")
                else:
                    c.execute("UPDATE words SET value = ? WHERE key = ?", (value, key))
              entryState = "Key"
            else:
                value += line
        line = fp.readline()
    conn.commit()

    if args.resource_dir:
        generateResDb(conn, args.resource_dir, args.dryrun, args.patch)

    conn.close()

parser = argparse.ArgumentParser(
    prog='gen-dict',
    description='generate sqlite3 dict'
)
parser.add_argument('input_file', help="input text file")
parser.add_argument('output_file', help="file name for generated db")
parser.add_argument('--resource_dir', help="resource files in the dir will be inserted into the db")
parser.add_argument('--patch', help="specify the keyword for which to patch")
parser.add_argument('--dryrun', default=False, action='store_true', help="test the command line")

args = parser.parse_args()
generateDb(args)


import json
import os

# Configuration with default values
import configargparse

cfg = {
    'host': '127.0.0.1',
    'port': 4242,
    'proxies_file': '',
    'require_min_trainer_level': 30,
    'login_retries': 3,
    'login_delay': 6
}

def cfg_get(key, default=None):
    return cfg.get(key, default)

parser = configargparse.ArgParser()
parser.add_argument('-c', '--config',
                    help=('Specify different config file. Default: config.json'),
                    default='config.json')
args = parser.parse_args()

with open(args.config, 'r') as f:
    user_cfg = json.loads(f.read())
    cfg.update(user_cfg)


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

"""

 This script is used to send Telegram notifications
 when a Monit alert is raised.

 Author = Peter Ibragimov
 Forked from = https://github.com/Matei-Ciobotaru/Monit-Telegram-Alerts
"""

import os

import requests

# Monit alert bot info
BOT_TOKEN = "***:***"  # noqa: S105
CHAT_ID = "***"

# Monit Telegram message information fields
ALERT_FIELDS = ["HOST", "DATE", "EVENT", "SERVICE", "DESCRIPTION"]

# Telegram url
BASE_URL = "https://api.telegram.org"

def alert_message(alert_fields):
    """
    Obtain Monit alert details via environment variables
    """

    header = "ðŸ”” <b>MONIT ALERT</b> ðŸ””\n\n"
    message_lines = []

    for field in alert_fields:

        variable = "MONIT_" + field
        field_value = os.environ.get(variable, "N/A")

        field_name = "<b>{0}: </b>".format(field.title())
        line = field_name + field_value.upper()

        message_lines.append(line)

    message = header + "\n".join(message_lines)

    return message

def send_alert(token, chat_id, message):
    """
    Send Telegram alert message
    """
    requests.get(
        f"{BASE_URL}/bot{token}/sendMessage",
        params={"text": "{}".format(message), "chat_id": chat_id, "parse_mode": "html"},
    )

def main():
    """
    Script excecution
    """
    message = alert_message(ALERT_FIELDS)
    send_alert(BOT_TOKEN, CHAT_ID, message)

if __name__ == "__main__":
    main()


import logging
import os
import yaml

import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common import armbian_utils
from jinja2 import Environment
from jinja2 import StrictUndefined

# Prepare logging
armbian_utils.setup_logging()
log: logging.Logger = logging.getLogger("output-gha-workflow-template")

# Parse cmdline

output_file = sys.argv[1]
config_yaml_file = sys.argv[2]
template_dir = sys.argv[3]
num_chunks_artifacts = int(sys.argv[4])
num_chunks_images = int(sys.argv[5])

log.info(f"output_file: {output_file}")
log.info(f"template_dir: {template_dir}")
log.info(f"num_chunks_artifacts: {num_chunks_artifacts}")
log.info(f"num_chunks_images: {num_chunks_images}")

# load the yaml config (context for all entries)
config = {}
with open(config_yaml_file, "r") as f:
	config_yaml = f.read()
	config = yaml.load(config_yaml, Loader=yaml.FullLoader)

# get a list of the .yaml files in the template dir
template_files = [f for f in os.listdir(template_dir) if f.endswith(".yaml") or f.endswith(".yml")]
# sort it
template_files.sort()
log.info(f"template_files: {template_files}")

out: str = ""

# here is a list of the filenames we expect:
# 050.single_header.yaml
# 150.per-chunk-artifacts_prep-outputs.yaml
# 151.per-chunk-images_prep-outputs.yaml
# 250.single_aggr.jobs.yaml
# 550.per-chunk-artifacts_job.yaml
# 650.per-chunk-images_job.yaml
def handle_template(template_content: str, context: dict) -> str:
	env = Environment(block_start_string='[%', block_end_string='%]',
					  variable_start_string='[[', variable_end_string=']]', comment_start_string='[#', comment_end_string='#]',
					  undefined=StrictUndefined)
	jinja_template = env.from_string(template_content)

	rendered = jinja_template.render(context)

	# Now, strip all the lines that contain the string "<TEMPLATE-IGNORE>"
	rendered = "\n".join([line for line in rendered.split("\n") if "<TEMPLATE-IGNORE>" not in line])

	# More crazy. For the string '"TEMPLATE-JOB-NAME": # <TEMPLATE-JOB-NAME>' we will replace it with the actual job name
	rendered = rendered.replace('"TEMPLATE-JOB-NAME": # <TEMPLATE-JOB-NAME>', f'"{context["job_name"]}": # templated "{context["job_name"]}"')

	# ensure it ends with a newline
	if not rendered.endswith("\n"):
		rendered += "\n"

	return rendered

# loop over the template files
for template_file in template_files:
	# parse the filename according to the above list
	template_order, rest = template_file.split(".", 1)
	template_order = int(template_order)
	# parse the type of template, separated by "_"
	template_type, rest = rest.split("_", 1)
	# parse the name of the template and the extension. the extension is anything after the first "."
	template_name, template_ext = rest.split(".", 1)
	# read the full contents of the template file as UTF-8
	with open(os.path.join(template_dir, template_file), "r") as f:
		template_content = f.read()

	log.info(
		f"Processing template file: {template_file} (order: {template_order}, type: {template_type}, name: {template_name}, ext:{template_ext}, len:{len(template_content)} bytes)")

	# prepare quoted comma lists of the chunks, remove the first and last quotes
	quoted_comma_list_artifact_chunk_jobs = ",".join([f"\"build-artifacts-chunk-{chunk + 1}\"" for chunk in range(num_chunks_artifacts)])[1:-1]

	# same, but for images, remove the first and last quotes
	quoted_comma_list_image_chunk_jobs = ",".join([f"\"build-images-chunk-{chunk + 1}\"" for chunk in range(num_chunks_images)])[1:-1]

	context = {
		"num_chunks_artifacts": num_chunks_artifacts,
		"num_chunks_images": num_chunks_images,
		"quoted_comma_list_artifact_chunk_jobs": quoted_comma_list_artifact_chunk_jobs,
		"quoted_comma_list_image_chunk_jobs": quoted_comma_list_image_chunk_jobs
	}

	# all 'config' dict on top, for common things re-used everywhere
	context.update(config)

	out += f"\n# template file: {template_file}\n\n"

	if template_type == "single":
		context["job_name"] = "ERROR_IN_TEMPLATE!!!"
		out += handle_template(template_content, context)
	elif template_type == "per-chunk-artifacts":
		for chunk in range(num_chunks_artifacts):
			context["chunk"] = chunk + 1
			context["num_chunks"] = num_chunks_artifacts
			context["job_name"] = f"build-artifacts-chunk-{chunk + 1}"
			out += handle_template(template_content, context)
	elif template_type == "per-chunk-images":
		for chunk in range(num_chunks_images):
			context["chunk"] = chunk + 1
			context["num_chunks"] = num_chunks_images
			context["job_name"] = f"build-images-chunk-{chunk + 1}"
			out += handle_template(template_content, context)
	else:
		raise Exception(f"Unknown template type: {template_type}")

# write the out str to the output file
with open(output_file, "w") as f:
	f.write(out)

log.info(f"Done. Wrote {len(out)} bytes to {output_file}")


from app.services.api.entities.conference import Conference
from app.services.api.conference_admin import ConferenceAdminApiService
from app.core.context import Context

class ActiveMixin:
    def command_active_conference(
        self, context: Context, service: ConferenceAdminApiService
    ):
        conference_id = context.user.handler_data["conference_id"]
        conference: Conference = service.get_by_id(conference_id, user=context.user)
        active_desactive_lb = (
            self._("conference_desactive_btn")
            if conference.active
            else self._("conference_active_btn")
        )
        buttons = [
            [
                context.create_button(
                    active_desactive_lb, callback_data="/do_active_conference"
                ),
                self.create_back_button(context=context),
            ]
        ]
        header = self._get_header_text(conference=conference, context=context)
        return context.build_buttons(
            buttons,
            message=header + self._("conference_active_lb"),
        )

    command_active_conference.use_history = True

    def command_do_active_conference(
        self, context: Context, service: ConferenceAdminApiService
    ):
        conference_id = context.user.handler_data["conference_id"]
        conference: Conference = service.get_by_id(conference_id, user=context.user)
        conference.active = not conference.active
        service.update(conference, user=context.user)
        return context.forward(f"/conference {conference_id}")

    command_do_active_conference.use_history = True


def path(x, y, blocked, hops):
    grid = [
            [[0,'unvisited'] for _ in range(x)]
            for _ in range(y)
            ]
    for i in blocked:
        print(i)
        grid[i[0]][i[1]] = [0, 'blocked']

    grid[x-1][y-1][1] = 'visited'
    for i in range(x - 1):
        if grid[y - 1][i][1] != 'visited' and grid[y - 1][i][1] != 'blocked':
            grid[y - 1][i] = [1,'visited']
    for i in range(y - 1):
        if grid[i][x - 1][1] != 'visited' and grid[i][x - 1][1] != 'blocked':
            grid[i][x - 1] = [1,'visited']

    for i in range(x - 1, -1, -1):
        for j in range(y - 1, -1, -1):
            if grid[i][j][1] != 'visited' and grid[i][j][1] != 'blocked':
                grid[i][j][0] = grid[i+1][j][0] + grid[i][j+1][0]
                grid[i][j][1] = 'visited'

    if len(hops) > 0:
        for i in hops:
            print(i)
            grid[i[0][0]][i[0][1]][0] = grid[i[1][0]][i[1][1]][0]
            grid[i[0][0]][i[0][1]][1] = 'hop'
        for line in grid:
            print(line)
        for i in range(x - 1):
            for j in range(y - 1):
                if grid[i][j][1] != 'hop' and grid[i][j][1] != 'blocked':
                    grid[i][j] = [0, 'unvisited']
        for line in grid:
            print(line)

        grid[x-1][y-1][1] = 'visited'
        for i in range(x - 1):
            if grid[y - 1][i][1] != 'blocked' and grid[y - 1][i][1] != 'hop':
                grid[y - 1][i] = [1,'visited']
        for i in range(y - 1):
            if grid[i][x - 1][1] != 'blocked' and grid[i][x - 1][1] != 'hop':
                grid[i][x - 1] = [1,'visited']

        for i in range(x - 1, -1, -1):
            for j in range(y - 1, -1, -1):
                if grid[i][j][1] != 'blocked' and grid[i][j][1] != 'hop' and grid[i][j][1] != 'visited':
                    grid[i][j][0] = grid[i+1][j][0] + grid[i][j+1][0]
                    grid[i][j][1] = 'visited'

    for line in grid:
        print(line)
    num_paths = grid[0][0][0]
    return num_paths

def get_blocked():
    n = input("How many blocked nodes are in this project?: ")
    blocked = []
    for i in range(int(n)):
       print("Enter the coordinates of a blocked node: ")
       x = int(input("X: "))
       y = int(input("Y: "))
       blocked.append((x,y))
    return blocked

def get_hops():
    n = input("How many jumps are in this project?: ")
    hops = []
    for i in range(int(n)):
        print("Enter the x and y values of the starting point of a jump followed by the x and y values of the end point: ")
        x1 = int(input("starting X: "))
        y1 = int(input("starting Y: "))
        x2 = int(input("ending X: "))
        y2 = int(input("ending Y: "))
        hops.append(((x1,y1),(x2,y2)))
    return hops

def main():
    print("This program will calculate the total number of paths to complete a project")
    x = int(input('Enter the x value of the grid: '))
    y = int(input('Enter the y value of the grid: '))
    blocked = get_blocked()
    if x == 1 or y == 1:
        if len(blocked) > 0:
            print("You cannot complete this project")
        else:
            print("There is only one path to complete this project")
    hops = get_hops()
    num_paths = path(x,y,blocked,hops)
    print('There are {} paths to complete the project.'.format(str(num_paths)))

if __name__ == '__main__':
    main()


""" Script contains all the core implementation """
import requests
import dojahcore as core
from dojahcore.server_error import ServerError
class DojahBase:
    """ Base class"""

    def __init__(self, **kwargs) -> None:
        """ Prepare the requests """

        api_key  =  kwargs.get('api_key',core.API_KEY)
        api_url  =  core.API_URL
        api_id  =  kwargs.get('app_id',core.APP_ID)

        headers  =  {'Authorization': api_key, 'AppId': api_id}
        arguments  = {"headers":headers, "api_url": api_url}

        self.requests  =  DojahRequests(**arguments)

class DojahRequests(object):
    """" Contains request implementation """

    def __init__(self, api_url, headers=None) -> None:
        """ Initialize requests object
        params:
                api_url: str
                headers : dict

        """
        self.BASE_URL  =  api_url
        self.headers  =  headers

    def _request(self, method, uri, **kwargs):

        """ Call a method on the specified resource uri

        params:
                method: GET | POST | PUT
                uri : endpoint
        Raises :
                HTTPError
        Returns :
                JSON
         """

        body  =  kwargs.get('body')
        query =  kwargs.get('query')
        response   = method(self.BASE_URL + uri, json=body,headers=self.headers, params=query)

        if response.status_code != 200:
                raise ServerError(
                        "Failed to complete request, status={}, error_message={}".format(response.status_code, response.json()['error'])
                )
        return response.json()['entity']

    def get(self, endpoint,**kwargs):
        """ GET request method

        params :
                endpoint : uri pointing to the resource

        """

        return self._request(requests.get,endpoint,**kwargs)
    def put(self,endpoint,**kwargs):
            """ PUT request method

            params :
                      endpoint : uri pointing to the resource

            """

            return self._request(requests.put,endpoint, **kwargs)

    def post(self, endpoint, **kwargs):
        """ POST request method

        params :
                endpoint : uri for the resource

        """

        return self._request(requests.post,endpoint,**kwargs)


from .possible_path_generator import *
from .diversifier import *
from ..df_loader import local_path
import pickle

class DiversifiedResultsLoader:
    PRECOMPUTED_PATH = {  "answer1": {'primitive_type'},
                          "answer2": {'object_class'},
                          "answer3": {},
                          "answer4": {'primitive_type', 'operator'},
                          "answer5": {'primitive_type', 'variable'},
                          "answer6": {'primitive_type', 'object_class'},
                          "answer7": {'primitive_type', 'operator', 'object_class'},
                          "answer8": {'primitive_type', 'operator', 'branch'},
                          "answer9": {'primitive_type', 'operator', 'variable'},
                          "answer10": {'primitive_type', 'variable', 'object_class'},
                          "answer11": {'primitive_type', 'variable', 'array'},
                          "answer12": {'primitive_type', 'variable', 'object_class', 'operator'},
                          "answer13": {'primitive_type', 'variable', 'array', 'object_class'},
                          "answer14": {'primitive_type', 'variable', 'array', 'operator'},
                          "answer15": {'primitive_type', 'variable', 'object_class', 'instance_variable'}
                       }
    CONCEPT_EDGES = {
        "primitive_type": ["operator", "array", "variable"],
        "operator": ["branch"],
        "branch": ["loop"],
        "array": ["nd_array", "string"],
        "variable": ["array", "instance_variable"],
        "object_class": ["instance_variable", "method"],
        "instance_variable": ["method"],
        "method": ["recursion"],
        "loop": [],
        "nd_array": [],
        "string": [],
        "recursion": []
    }
    PPG = PossiblePathGenerator()
    diversifier = Diversifier()
    def load(self, learned_object):
        if len(learned_object) == 0:
            file_name = local_path('./diversified/answer/answer3.pkl')
            with open(file_name, 'rb') as f:
                node_name_map, res = pickle.load(f)
            L = []
            for seq in res:
                l = []
                for idx in seq:
                    l.append(node_name_map[idx])
                L.append(l)
            return L
        else:
            file_name = ''
            for key, value in self.PRECOMPUTED_PATH.items():
                if(learned_object.issubset(value)):
                    file_name = local_path('./diversified/answer/' + key + '.pkl')
                    break
            if(file_name != ''):
                with open(file_name, 'rb') as f:
                    node_name_map, res = pickle.load(f)

                L = []
                for seq in res:
                    l = []
                    for idx in seq:
                        l.append(node_name_map[idx])
                    L.append(l)
                return L
            else:
                unlearn_concepts = self.CONCEPT_EDGES.copy()
                for concept in learned_object:
                    unlearn_concepts.pop(concept, None)
                all_nodes, _, _ = self.PPG.find_node_set(unlearn_concepts)
                node2ind, indmap = self.PPG.create_dependency_map_with_index(unlearn_concepts, all_nodes)
                ret = self.PPG.permutation(all_nodes, node2ind, indmap)
                possible_sequences = [list(elem) for elem in ret]
                if len(possible_sequences) > 200:
                    _, Q = self.diversifier.diversify(possible_sequences, r=len(learned_object))
                else:
                    Q = possible_sequences
                L = []
                node_name_map = list(all_nodes)
                for seq in Q:
                    l = []
                    for idx in reversed(seq):
                        l.append(node_name_map[idx])
                    L.append(l)
                return L


def on_message(msg):
    if msg.text.lower().startswith('call me '):
        msg.from_user.data['callme'] = msg.text[8:].strip()
        msg.from_user.save_data()
        msg.reply('Sure thing, ' + msg.from_user.data['callme'])
        return

    if msg.text.lower().startswith('i have a '):
        words = msg.text.split(' ')
        try:
            msg.from_user.data[' '.join(words[4:])] = words[3]
            msg.reply("Okay, I'll remember that.")
        except IndexError:
            msg.reply("You have a what now?")
        return

    if msg.text.lower() == 'what do you know about me':
        msg.reply('Just this:' + ', '.join('{}: {}'.format(*i) for i in msg.from_user.data.items()))
        return

    if msg.text.lower().startswith('hi'):
        callme = msg.from_user.data.get('callme')
        if callme:
            msg.reply('Hi, ' + callme + '!')
        else:
            msg.reply('Hi!')
        return

    msg.reply("Sorry, I don't understand that...")


import os
import re

import mmsdk
import numpy as np
from loguru import logger
from mmsdk import mmdatasdk as md
from tqdm import tqdm

from slp.config.multimodal import (
    MOSEI_COVAREP_FACET_GLOVE,
    MOSI_COVAREP_FACET_GLOVE,
    MOSI_COVAREP_FACET_RAW,
    MOSI_COVAREP_OPENFACE_GLOVE,
    MOSI_OPENSMILE_OPENFACE_GLOVE,
    POM_COVAREP_FACET_GLOVE,
    POM_COVAREP_FACET_RAW,
)
from slp.config.nlp import SPECIAL_TOKENS
from slp.util.system import pickle_dump, pickle_load, safe_mkdirs

def download_mmdata(base_path, dataset):
    safe_mkdirs(base_path)

    try:
        md.mmdataset(dataset.highlevel, base_path)
    except RuntimeError:
        logger.info("High-level features have been downloaded previously.")

    try:
        md.mmdataset(dataset.raw, base_path)
    except RuntimeError:
        logger.info("Raw data have been downloaded previously.")

    try:
        md.mmdataset(dataset.labels, base_path)
    except RuntimeError:
        logger.info("Labels have been downloaded previously.")

def avg_collapse(intervals, features):
    try:
        return np.average(features, axis=0)
    except Exception as e:
        del e

        return features

def deploy(in_dataset, destination):
    deploy_files = {x: x for x in in_dataset.keys()}
    in_dataset.deploy(destination, deploy_files)

def load_modality(base_path, feature_cfg, modality):
    mfile = feature_cfg[modality]
    path = os.path.join(base_path, "{}.csd".format(mfile))
    logger.info("Using {} for {} modality".format(path, modality))
    data = md.mmdataset(path)

    return data

def get_vocabulary(text_dataset):
    all_words = []

    for seg in text_dataset.keys():
        words = text_dataset[seg]["features"][0]

        for w in words:
            wi = w.decode("utf-8")
            all_words.append(wi)

    all_words = list(set(all_words))

    return all_words

def create_word2idx(all_words):
    word2idx, idx = {}, 0

    for w in sorted(all_words):
        if w not in word2idx:
            word2idx[w] = idx
            idx += 1

    for t in SPECIAL_TOKENS:
        word2idx[t.value] = idx
        idx += 1

    return word2idx

def select_dataset(dataset_name):
    if dataset_name == "mosi":
        dataset = md.cmu_mosi
    elif dataset_name == "mosei":
        dataset = md.cmu_mosei
    elif dataset_name == "pom":
        dataset = md.pom
    else:
        raise ValueError("Unsupported dataset. Use [mosei|mosi|pom]")

    return dataset

def patch_missing_metadata(data):
    # Remove need for annoying input that stops execution
    for k in data.computational_sequences.keys():
        data.computational_sequences[k].metadata[
            "dimension names"
        ] = data.computational_sequences[k].metadata.get("dimension names", None)
        data.computational_sequences[k].metadata[
            "computational sequence version"
        ] = data.computational_sequences[k].metadata.get(
            "computational sequence version", None
        )
        data.computational_sequences[k].metadata[
            "dimension namescomputational sequence version"
        ] = None

def load_and_align(
    base_path,
    dataset="mosi",
    feature_cfg=MOSI_COVAREP_FACET_GLOVE,
    modalities={"audio", "visual", "text"},
    collapse=None,
):
    dataset = select_dataset(dataset)
    download_mmdata(base_path, dataset)
    recipe = {
        f: os.path.join(base_path, "{}.csd".format(f))
        for k, f in feature_cfg.items()
        if k in list(modalities) + ["raw"]
    }
    data = md.mmdataset(recipe)

    patch_missing_metadata(data)

    if collapse is None:
        collapse = [avg_collapse]
    # first we align to words with averaging
    # collapse_function receives a list of functions

    word_align_path = base_path + "_word_aligned"
    safe_mkdirs(word_align_path)

    data.align(feature_cfg["raw"], collapse_functions=collapse)
    data.impute(feature_cfg["raw"])
    deploy(data, word_align_path)
    all_words = get_vocabulary(data[feature_cfg["raw"]])

    word2idx = create_word2idx(all_words)

    label_recipe = {
        feature_cfg["labels"]: os.path.join(
            base_path, "{}.csd".format(feature_cfg["labels"])
        )
    }
    data.add_computational_sequences(label_recipe, destination=None)
    patch_missing_metadata(data)

    data.align(feature_cfg["labels"])
    data.hard_unify()
    align_path = base_path + "_final_aligned"
    safe_mkdirs(align_path)
    deploy(data, align_path)

    return data, word2idx

def load_dataset(
    base_path,
    dataset="mosi",
    feature_cfg=MOSI_COVAREP_FACET_GLOVE,
    modalities={"audio", "text", "visual"},
    already_segmented=False,
):
    dataset = select_dataset(dataset)
    download_mmdata(base_path, dataset)
    recipe = {
        f: os.path.join(base_path, "{}.csd".format(f))
        for k, f in feature_cfg.items()
        if k in list(modalities) + ["raw"]
    }
    data = md.mmdataset(recipe)

    patch_missing_metadata(data)

    all_words = get_vocabulary(data[feature_cfg["raw"]])

    word2idx = create_word2idx(all_words)

    label_recipe = {
        feature_cfg["labels"]: os.path.join(
            base_path, "{}.csd".format(feature_cfg["labels"])
        )
    }
    data.add_computational_sequences(label_recipe, destination=None)

    patch_missing_metadata(data)

    if not already_segmented:
        data.align(feature_cfg["labels"])
        data.hard_unify()

    return data, word2idx

def remove_pause_tokens(mods, modalities, is_raw_text_feature):
    # Handle speech pause
    mods_nosp = {k: [] for k in modalities}

    for m in modalities:
        for i in range(len(mods[m])):
            if mods["raw"][i] != "sp":
                mods_nosp[m].append(mods[m][i])

    return mods_nosp

def replace_sp_token(mods, is_raw_text_feature):
    mods_nosp = mods

    if is_raw_text_feature:
        for i in range(len(mods["text"])):
            if mods["text"][i] == "sp":
                mods_nosp["text"][i] = SPECIAL_TOKENS.PAUSE.value

    return mods_nosp

def pad_modality_features(
    mods, modalities, max_length, pad_front, pad_back, is_raw_text_feature
):
    if pad_front and pad_back:
        raise ValueError("Only one of pad_front and pad_back should be true.")

    def compute_padding(m, seglen):
        t = []

        for i in range(max_length[m] - seglen):
            if is_raw_text_feature and m == "text":
                t.append(SPECIAL_TOKENS.PAD.value)
            else:
                vshape = mods[m][0].shape
                pad = np.zeros(vshape)
                t.append(pad)

        return t

    for m in modalities:
        if isinstance(mods[m], np.ndarray):
            mods[m] = [x for x in mods[m]]
        seglen = len(mods[m])

        if seglen >= max_length[m]:
            t = []

            for i in range(max_length[m]):
                t.append(mods[m][i])
            mods[m] = t
        else:
            if pad_front:
                padding = compute_padding(m, seglen)
                mods[m] = padding + mods[m]

            if pad_back:
                padding = compute_padding(m, seglen)
                mods[m] = mods[m] + padding

    return mods

def clean_split_dataset(
    data,
    dataset="mosi",
    feature_cfg=MOSI_COVAREP_FACET_GLOVE,
    modalities={"audio", "text", "visual"},
    remove_pauses=False,
    max_length=-1,
    pad_front=False,
    pad_back=False,
    aligned=True,
):
    dataset = select_dataset(dataset)
    train_split = dataset.standard_folds.standard_train_fold
    dev_split = dataset.standard_folds.standard_valid_fold
    test_split = dataset.standard_folds.standard_test_fold

    train, dev, test = [], [], []
    num_drop = 0

    segments = data[feature_cfg["labels"]].keys()

    if max_length < 0:
        max_length = {
            m: max([len(data[feature_cfg[m]][s]["features"]) for s in segments])
            for m in list(modalities) + ["raw"]
        }
    else:
        max_length = {m: max_length for m in list(modalities) + ["raw"]}

    for segment in tqdm(segments):
        # get the video ID and the features out of the aligned dataset
        sidx = segment.find("[")

        if sidx > 0:
            vid = segment[:sidx]
        else:
            vid = segment

        # if segment == 'c5xsKMxpXnc':
        mods = {
            k: data[feature_cfg[k]][segment]["features"]
            for k in list(modalities) + ["raw"]
        }

        is_raw_text_feature = isinstance(mods["text"][0][0], bytes)

        raw_text_mods = ["raw", "text"] if is_raw_text_feature else ["raw"]
        mods_with_possible_nan = list(set(modalities) - set(raw_text_mods))
        mods_without_raw_text = list(set(modalities) - set(raw_text_mods))

        for m in mods_with_possible_nan:
            mods[m] = np.nan_to_num(mods[m])

        for m in raw_text_mods:
            words = []

            for i in range(len(mods[m])):
                words.append(mods[m][i][0].decode("utf-8"))
            mods[m] = words

        if aligned:
            num_drop = 0
            # if the sequences are not same length after alignment,
            # there must be some problem with some modalities
            # we should drop it or inspect the data again
            mod_shapes = {k: len(v) for k, v in mods.items()}

            if not len(set(list(mod_shapes.values()))) <= 1:
                logger.warning("Datapoint {} shape mismatch {}".format(vid, mod_shapes))
                num_drop += 1

                continue

            if remove_pauses:
                mods = remove_pause_tokens(mods, modalities, is_raw_text_feature)

        mods = pad_modality_features(
            mods, modalities, max_length, pad_front, pad_back, is_raw_text_feature
        )
        mods = replace_sp_token(mods, is_raw_text_feature)

        for m in mods_without_raw_text:
            mods[m] = np.asarray(mods[m])

        mods["video_id"] = vid
        mods["segment_id"] = segment
        mods["label"] = np.nan_to_num(data[feature_cfg["labels"]][segment]["features"])

        if vid in train_split:
            train.append(mods)
        elif vid in dev_split:
            dev.append(mods)
        elif vid in test_split:
            test.append(mods)
        else:
            logger.warning("{} does not belong to any of the splits".format(vid))
    logger.warning("Dropped {} data points".format(num_drop))

    return train, dev, test

def load_splits(
    base_path,
    dataset="mosi",
    feature_cfg=MOSI_COVAREP_FACET_GLOVE,
    modalities={"audio", "text", "visual"},
    remove_pauses=False,
    max_length=-1,
    pad_front=False,
    pad_back=False,
    already_aligned=False,
    align_features=True,
    cache=None,
):
    if cache is not None:
        try:
            return pickle_load(cache)
        except FileNotFoundError:
            pass

    if not already_aligned and align_features:
        data, word2idx = load_and_align(
            base_path,
            dataset=dataset,
            feature_cfg=feature_cfg,
            modalities=modalities,
            collapse=[avg_collapse],
        )
    else:
        data, word2idx = load_dataset(
            base_path,
            dataset=dataset,
            feature_cfg=feature_cfg,
            modalities=modalities,
            already_segmented=already_aligned or align_features,
        )

    train, dev, test = clean_split_dataset(
        data,
        dataset=dataset,
        feature_cfg=feature_cfg,
        modalities=modalities,
        remove_pauses=remove_pauses,
        max_length=max_length,
        pad_front=pad_front,
        pad_back=pad_back,
        aligned=already_aligned or align_features,
    )

    if cache is not None:
        pickle_dump((train, dev, test, word2idx), cache)

    return train, dev, test, word2idx

def mosi(
    base_path,
    feature_cfg=MOSI_COVAREP_FACET_GLOVE,
    modalities={"audio", "text", "visual"},
    remove_pauses=False,
    max_length=-1,
    pad_front=False,
    pad_back=False,
    cache=None,
    already_aligned=False,
    align_features=True,
):
    return load_splits(
        base_path,
        dataset="mosi",
        feature_cfg=feature_cfg,
        modalities=modalities,
        remove_pauses=remove_pauses,
        max_length=max_length,
        pad_front=pad_front,
        pad_back=pad_back,
        cache=cache,
        already_aligned=already_aligned,
        align_features=align_features,
    )

def mosei(
    base_path,
    feature_cfg=MOSEI_COVAREP_FACET_GLOVE,
    modalities={"audio", "text", "visual"},
    remove_pauses=False,
    max_length=-1,
    pad_front=False,
    pad_back=False,
    cache=None,
    already_aligned=False,
    align_features=True,
):
    return load_splits(
        base_path,
        dataset="mosei",
        feature_cfg=feature_cfg,
        modalities=modalities,
        remove_pauses=remove_pauses,
        max_length=max_length,
        pad_front=pad_front,
        pad_back=pad_back,
        cache=cache,
        already_aligned=already_aligned,
        align_features=align_features,
    )

def pom(
    base_path,
    feature_cfg=POM_COVAREP_FACET_GLOVE,
    modalities={"audio", "text", "visual"},
    remove_pauses=False,
    max_length=-1,
    pad_front=False,
    pad_back=False,
    cache=None,
    already_aligned=False,
    align_features=True,
):
    return load_splits(
        base_path,
        dataset="pom",
        feature_cfg=feature_cfg,
        modalities=modalities,
        remove_pauses=remove_pauses,
        max_length=max_length,
        pad_front=pad_front,
        pad_back=pad_back,
        cache=cache,
        already_aligned=already_aligned,
        align_features=align_features,
    )

def data_pickle(fname):
    data = pickle_load(fname)

    return data["train"], data["valid"], data["test"], None

if __name__ == "__main__":
    import sys

    base_path = sys.argv[1]
    train, dev, test, w2i = mosi(
        base_path,
        feature_cfg=MOSI_OPENSMILE_OPENFACE_GLOVE,
        modalities=["audio", "text", "visual"],
        remove_pauses=True,
        pad_front=False,
        pad_back=True,
        already_aligned=False,
        align_features=True,
    )


import os
import sys
import json
import base64
from contextlib import suppress
from jinja2 import FileSystemLoader, Environment
from selenium.webdriver import Chrome, ChromeOptions as Options

class Template2PDF:
    """
    Renders and converts a Jinja2 template into a PDF file.

    CSS styles in a ´.css´ file are not supported.
    The style must be a remote URL on a ´link´ tag or a style in a ´style´ tag.

    Chromium/Chrome and chromedriver must be installed and added to PATH.
    """

    def __init__(self, template: str):
        r = template.split("/")
        template_name = r[-1]
        path = "/".join(r[0:-1])
        del r

        self.__template = Environment(
            loader=FileSystemLoader(searchpath=path if path else "./")
        ).get_template(template_name)

        self.text = None

    def render(self, data: dict):
        self.text = self.__template.render(**data)
        return self

    def write_pdf(self, target=None, options={}):
        """
        Writes to file. If no ´target´ is given a base64 string is returned.
        """
        try:
            if not self.text:
                raise RuntimeError("The template must be rendered first.")

            driver_options = Options()
            driver_options.headless = True
            driver = Chrome(options=driver_options)

            with open("page.html", "w+t") as fp:
                fp.write(self.text)

            file_path = os.getcwd() + "/page.html"
            driver.get("file:///" + file_path)

            print_options = {
                "landscape": False,
                "displayHeaderFooter": False,
                "printBackground": True,
                "preferCSSPageSize": True,
                **options,
            }

            result = self.__send_devtools(driver, "Page.printToPDF", print_options)

            if target:
                with open(target, "w+b") as fp:
                    fp.write(base64.b64decode(result["data"]))
                return
            else:
                return result["data"]
        except Exception as e:
            raise e
        finally:
            driver.quit()
            with suppress(OSError):
                os.remove(file_path)

    def __send_devtools(self, driver, cmd, params={}):
        resource = (
            "/session/%s/chromium/send_command_and_get_result" % driver.session_id
        )
        url = driver.command_executor._url + resource
        body = json.dumps({"cmd": cmd, "params": params})
        response = driver.command_executor._request("POST", url, body)

        if response.get("status", False):
            raise Exception(response.get("value"))
        return response.get("value")

if __name__ == "__main__":
    program, template, input_, output = sys.argv[0:]
    del program

    with open(input_, "r") as fp:
        data = json.load(fp)

    Template2PDF(template).render(data).write_pdf(output)


import paddle.fluid as fluid

eps = 1e-8

def Basic_Loss(preds, labels, ignore_index=255):
    n, c, h, w = preds.shape

    preds = fluid.layers.transpose(preds, [0, 2, 3, 1])

    mask = labels!=ignore_index
    mask = fluid.layers.cast(mask, 'float32')

    loss = fluid.layers.softmax_with_cross_entropy(preds, labels)
    loss = loss * mask
    avg_loss = fluid.layers.mean(loss) / (fluid.layers.mean(mask) + eps)

    return avg_loss


import heapq

inp = open("input5.txt", mode='r')
out = open("output5.txt", mode='w')
data = inp.readlines()
info = list(map(int, data[0].strip().split()))
a = {i: [] for i in range(info[0]+1)}
for i in range(1, info[1]+1):
    temp = list(map(int, data[i].strip().split()))
    a[temp[0]].append((temp[1], 1))
    a[temp[1]].append((temp[0], 1))

path_len = [float('inf') for _ in range(info[0]+1)]
prev = [None for _ in range(info[0]+1)]

heap = [(0, 1)]
path_len[1] = 0

while heap:
    d, u = heapq.heappop(heap)
    if d > path_len[u]:
        continue
    for v, w in a[u]:
        if path_len[u] + w < path_len[v]:
            path_len[v] = path_len[u] + w
            prev[v] = u
            heapq.heappush(heap, (path_len[v], v))

path = [info[2]]
u = info[2]
while prev[u]:
    path.append(prev[u])
    u = prev[u]
path.reverse()
print(f"Time: {path_len[info[2]]}", file=out)
print(f"Shortest Path: {' '.join(str(i) for i in path)}", file=out)

inp.close()
out.close()


import requests
from bs4 import BeautifulSoup
import math

LIMIT = 20

def get_last_page(url):
    request = requests.get(url)
    soup = BeautifulSoup(request.text, "html.parser")
    total_count = soup.find(
        "strong", {"class": "dev_tot"}).get_text()
    last_page = math.ceil(int(total_count.replace(',', ""))/LIMIT)
    return last_page

def extract_job(li):
    company = li.find(
        "div", {"class": "post-list-corp"}).find("a")["title"]
    job_name = li.find(
        "div", {"class": "post-list-info"}).find("a")["title"]
    location = li.find("p", {"class": "option"}).find(
        "span", {"class": "loc long"}).get_text(strip=True)
    job_id = li["data-gno"]
    return {"name": job_name, "company": company, "location": location, "link": f"http://www.jobkorea.co.kr/Recruit/GI_Read/{job_id}"}

def extract_jobs(url, last_page):
    extracted_jobs = []
    for page in range(last_page):
        print(f"Scrapping page:{page}")
        request = requests.get(f"{url}&Page_No={page}")
        soup = BeautifulSoup(request.text, "html.parser")
        infos = soup.find("div", {"class": "recruit-info"})
        results = infos.find_all("li", {"class": "list-post"})
        for result in results:
            job = extract_job(result)
            extracted_jobs.append(job)
    return extracted_jobs

def get_jobs(word):
    url = f"http://www.jobkorea.co.kr/Search/?stext={word}"
    last_page = get_last_page(url)
    jobs = extract_jobs(url, last_page)
    return jobs


import time

from flask import request, jsonify
from flask_cors import cross_origin

from app.main import main
from app.main.tools import hex2
from server_secrets import LAB_COMPUTER_TOKEN

@main.route('/crypto/pow_mod', methods=["POST"])
@cross_origin()
def calc_pow_mod():
    """
    计算模幂
    返回：text/plain
    :return:
    """
    x = request.form['x']
    y = request.form['y']
    z = request.form['z']

    if x is None or y is None or z is None:
        return jsonify(success=False, reason="参数不全")

    if not x.isdigit() or not y.isdigit() or not z.isdigit():
        return jsonify(success=False, reason="x, y或z至少有一个不是十进制整数")

    try:
        x = int(x)
        y = int(y)
        z = int(z)
        rslt = pow(x, y, z)
        result_dec = str(rslt)
        result_hex = hex2(rslt)
        return jsonify(success=True, result_dec=result_dec, result_hex=result_hex)

    except TypeError:
        return jsonify(success=False, reason="计算过程发生错误，请检查参数是否合法")

@main.route('/crypto/dlp/publish_task', methods=["POST"])
@cross_origin()
def publish_task():
    """
    发布DLP任务
    method: POST
    表单：
    -g: 底数
    返回：json
    - success: 是否成功
    - new_task: 是否是新任务
    - task_id: 任务编号
    - g: 底数
    - finished: 是否完成
    - result: 结果
    :return:
    """
    # FOR DATABASE
    from database.models import Task
    from app_wrapper import db

    g = request.form.get('g')

    if g is None:
        return jsonify(success=False, reason="没有指定g")

    if not g.isdigit():
        return jsonify(success=False, reason="g不是十进制整数")

    task = Task.query.filter(Task.g == g).first()
    if task:
        return jsonify(success=True,
                       new_task=False,
                       task_id=task.id,
                       g=g,
                       finished=task.finished,
                       result=task.result,
                       task_success=task.success)

    # 实验已经结束, 不能再发布新任务
    return jsonify(success=False, reason="DLP实验已经结束, 为了节省计算资源, cado-nfs计算功能已经关闭!")
    # new_task = Task(g=g)
    # db.session.add(new_task)
    # db.session.commit()
    # return jsonify(success=True,
    #                new_task=True,
    #                task_id=new_task.id)

@main.route('/crypto/dlp/get_task', methods=["GET"])
@cross_origin()
def get_task():
    """
    获取DLP任务
    method: GET
    参数：
    -g: 底数
    返回：json
    - success: 是否成功
    - task_id: 任务编号
    - g: 底数
    - finished: 是否完成
    - result: 结果
    :return:
    """
    # FOR DATABASE
    from database.models import Task

    g = request.args.get('g')

    if g is None:
        return jsonify(success=False, reason="没有指定g")

    if not g.isdigit():
        return jsonify(success=False, reason="g不是十进制整数")

    task = Task.query.filter(Task.g == g).first()
    if task:
        return jsonify(success=True,
                       task_id=task.id,
                       g=g,
                       finished=task.finished,
                       result=task.result,
                       task_success=task.success)

    return jsonify(success=False, reason="找不到该任务")

@main.route('/crypto/dlp/pick_task', methods=["GET"])
@cross_origin()
def pick_task():
    """
    获取DLP任务未完成队列中的队头任务
    method: GET
    参数：无
    返回：json
    - task_id: 任务编号
    - g: 底数
    :return:
    """
    token = request.form.get('token')
    if token is None or token != LAB_COMPUTER_TOKEN:
        return jsonify(success=False, reason="token鉴权失败")

    # FOR DATABASE
    from database.models import Task

    task = Task.query.filter(Task.finished == False).first()
    if task:
        return jsonify(success=True,
                       task_id=task.id,
                       g=task.g)

    return jsonify(success=False, reason="没有未完成的任务")

@main.route('/crypto/dlp/publish_task_result', methods=["POST"])
@cross_origin()
def publish_result():
    """
    公布DLP任务结果
    method: POST
    表单：
    -task_id: 任务id
    -task_success: 任务是否成功
    -result: 任务结果
    -operating_time: DLP计算时间
    返回：json
    - success: 是否成功
    :return:
    """
    token = request.form.get('token')
    if token is None or token != LAB_COMPUTER_TOKEN:
        return jsonify(success=False, reason="token鉴权失败")

    # FOR DATABASE
    from database.models import Task
    from app_wrapper import db

    task_id = request.form.get('task_id')

    if task_id is None:
        return jsonify(success=False, reason="没有指定task_id")

    if not task_id.isdigit():
        return jsonify(success=False, reason="task_id不是十进制整数")
    task_id = int(task_id)

    task = Task.query.get(task_id)

    if not task:
        return jsonify(success=False,
                       reason="找不到该任务")
    if task.finished:
        return jsonify(success=False,
                       reason="该任务已经结束")

    task_success_str = request.form.get("task_success")
    result = request.form.get("result")
    operating_time_str = request.form.get("operating_time")

    if task_success_str is None or result is None or operating_time_str is None:
        return jsonify(success=False,
                       reason="缺少参数")
    if not operating_time_str.isdigit():
        return jsonify(success=False,
                       reason="参数operating_time需要为十进制整数")

    task_success = (task_success_str == "1")
    operating_time = int(operating_time_str)

    task.finished = True
    task.result = result
    task.success = task_success
    task.operating_time = operating_time

    db.session.commit()
    return jsonify(success=True)

@main.route('/crypto/dlp/current_task_status', methods=["GET"])
@cross_origin()
def current_status():
    """
    获取DLP任务未完成队列中的队头任务
    method: GET
    参数：无
    返回：json
    - task_id: 任务编号
    - g: 底数
    :return:
    """
    # FOR DATABASE
    from database.models import Task

    task_count = Task.query.count()
    not_finished_count = Task.query.filter(Task.finished == False).count()
    current_operating_task = Task.query.filter(Task.finished == False).first()
    current_operating_task_id = 0
    if current_operating_task:
        current_operating_task_id = current_operating_task.id

    return jsonify(success=True,
                   task_count=task_count,
                   not_finished_count=not_finished_count,
                   current_operating_task_id=current_operating_task_id)


"""
:Title: CVSS prediction
:Description: Load all pre-trained BERT models to predict CVSS scores
:Developer: Teck Lim
:Create date: 05/15/2021
"""
import argparse

from datetime import datetime
from lib.common_utils import CVSS

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--model_path', default='/models/')
    parser.add_argument('--description', default='')
    parser.add_argument('--use_gpu', dest='use_gpu', action='store_true')
    params = parser.parse_args()

    model_path = params.model_path
    description = params.description
    use_gpu = params.use_gpu

    print('*' * 50)
    print('Model path: {}'.format(model_path))
    print('Description: {}'.format(description))
    print('Use GPU if available: {}'.format(use_gpu))
    print('*' * 50)

    cvss = CVSS(model_path=model_path, use_gpu=use_gpu)

    start_time = datetime.now()
    scores, metrics, confidences = cvss.predict(description)
    total_time = datetime.now() - start_time

    score_b, score_i, score_e = scores
    pred_av, pred_ac, pred_pr, pred_ui, pred_sc, pred_ci, pred_ii, pred_ai = metrics
    conf_av, conf_ac, conf_pr, conf_ui, conf_sc, conf_ci, conf_ii, conf_ai = confidences
    print('  Mean: {:.4f}'.format(sum(confidences) / len(confidences)))
    print('  Max : {:.4f}'.format(max(confidences)))
    print('  Min : {:.4f}'.format(min(confidences)))
    print('\nTotal time: {}.{} seconds\n'.format(total_time.seconds, total_time.microseconds))


import TrueRandomAttack as tra
import GameObject
import Timer
import time
import random
import Socket_Client

directions = ["top", "left", "bottom", "right"]
speeds = [7,8,9,10]
gameObject = GameObject.GameObject()

red = (255,0,0)

#Global functions
def select_random_direction():
	direction = random.choice(directions)
	return direction

def select_random_speed():
	speed = random.choice(speeds)
	return speed

class Attack_Wave():
	def __init__(self, pg, gameDisplay, color, units_per_wave):
		self.pg = pg
		self.gameDisplay = gameDisplay
		self.color = color
		self.wave_isActive = False
		self.units_per_wave = units_per_wave
		self.attack_block_list = []
		self.sc = Socket_Client.Sock_Con()

		print("inside an attack wave")

	def generate_wave(self):
		self.sc.get_attack()
		wave_size = len(self.sc.data_list)
		print(wave_size)
		for wave_number in range(0, wave_size):
			print("generating")
			for block_coordinate_index in range(0, len(self.sc.data_list[wave_number])):
				if(block_coordinate_index == 0):
					attack_unit =  tra.AttackBlock("top", select_random_speed(), self.sc.data_list[wave_number][block_coordinate_index])
					self.attack_block_list.append(attack_unit)
				elif(block_coordinate_index == 1):
					attack_unit =  tra.AttackBlock("left", select_random_speed(), self.sc.data_list[wave_number][block_coordinate_index])
					self.attack_block_list.append(attack_unit)
				elif(block_coordinate_index == 2):
					attack_unit =  tra.AttackBlock("bottom", select_random_speed(), self.sc.data_list[wave_number][block_coordinate_index])
					self.attack_block_list.append(attack_unit)
				elif(block_coordinate_index == 3):
					attack_unit =  tra.AttackBlock("right", select_random_speed(), self.sc.data_list[wave_number][block_coordinate_index])
					self.attack_block_list.append(attack_unit)
		return True

	def update_wave_coordinates(self):
			self.wave_isActive = True
			for i in self.attack_block_list:
					i.update_attack_block_coordinates()

	def update_wave_positions(self):
		if(self.wave_isActive):
			for i in self.attack_block_list:
					i.update_attack_block_position(self.pg, self.gameDisplay, self.color)

	def damage_player(self, player):
		for i in self.attack_block_list:
			i.damage(player)
			if(player.health <= 0):
				return 1

	def reset_attack_wave(self, delta=None):
		#always change for attack configuration, not for instance variables
		for i in self.attack_block_list:
			if(i.direction == "top"):
				if(i.top_side_attack_config[1] == i.end_y):
					i.top_side_attack_config[1] = 0
				#self.top_reset_recursion(i)
			elif(i.direction == "bottom"):
				if(i.bottom_side_attack_config[1] == i.end_y):
					i.bottom_side_attack_config[1] = gameObject.display_height
				#self.bottom_reset_recursion(i)
			elif(i.direction == "left"):
				if(i.left_side_attack_config[0] == i.end_x):
					i.left_side_attack_config[0] = 0
				#self.left_reset_recursion(i)
			else:
				if(i.right_side_attack_config[0] == i.end_x):
					i.right_side_attack_config[0] = gameObject.display_width
				#self.right_reset_recursion(i)

	def top_reset_recursion(self, i):
		x = random.choice(range(-100, 100))
		if(i.top_side_attack_config[0] + x >= gameObject.display_width or i.top_side_attack_config[0] + x <= 0):
			self.top_reset_recursion(i)
		else:
			i.top_side_attack_config[0] += x

	def bottom_reset_recursion(self, i):
		x = random.choice(range(-100, 100))
		if(i.bottom_side_attack_config[0] + x >= gameObject.display_width or i.bottom_side_attack_config[0] + x <= 0):
			self.bottom_reset_recursion(i)
		else:
			i.bottom_side_attack_config[0] += x

	def left_reset_recursion(self, i):
		x = random.choice(range(-100, 100))
		if(i.left_side_attack_config[1] + x >= gameObject.display_height or i.left_side_attack_config[1] + x <= 0):
			self.left_reset_recursion(i)
		else:
			i.left_side_attack_config[1] += x

	def right_reset_recursion(self, i):
		x = random.choice(range(-100, 100))
		if(i.right_side_attack_config[1] + x >= gameObject.display_height or i.right_side_attack_config[1] + x <= 0):
			self.right_reset_recursion(i)
		else:
			i.right_side_attack_config[1] += x


import random

def guess(x):
    random_number = random.randint(1, x)
    guess = 0

    while guess != random_number:
        guess = input(f'Guess a number between 1 and {x}: ')
        guess = int(guess)
        if guess < random_number:
            print('Guess was too low. Try again.')
        elif guess > random_number:
            print('Guess was too high. Guess again.')
    print(f'Congrats, you have guessed the right number {random_number} correctly! ')

# letting the computer guess any number we are thinking of
def computer_guess(x):
    low = 1
    high = x
    feedback = ''
    while feedback != 'c': # c -- correct
        if low != high:
            guess = random.randint(low, high)
        else:
            guess = low
        feedback = input(f'Is {guess} too high (H), too low (L), or correct (C)?').lower()
        if feedback == 'h':
            high = guess - 1
        elif feedback == 'l':
            low = guess + 1

    print(f'Yes, the computer guessed the number you were thinking of ({guess}) correctly.')

#guess(10)

computer_guess(10)


import os
import os.path as osp

src_folder = 'xuly_11/data_11_preprocessing'

a = []

instance_car = 0

for i1 in os.listdir(src_folder):
    if i1.endswith(".txt"):
        full_path_txt = osp.join(src_folder, i1)
        with open(full_path_txt) as file:
            lines_in_file = file.readlines()
            number_lines = len(lines_in_file)
            count_lines_lane = 0
            for i2 in lines_in_file:
                info_in_line = i2.strip().split()
                if info_in_line[0] == '1':
                    count_lines_lane += 1
            if count_lines_lane == number_lines:
                a.append(full_path_txt)
                instance_car += count_lines_lane

print(len(a))
print(instance_car)

# for i in a:
#     png_path = i[:-3] + 'png'
#     jpg_path = i[:-3] + 'jpg'
#     os.remove(i)
#     if osp.exists(png_path):
#         os.remove(png_path)
#     elif osp.exists(jpg_path):
#         os.remove(jpg_path)


import os
import json
import pyblish.api

from openpype.client import get_asset_by_name
from openpype.pipeline import legacy_io
from openpype.pipeline.create import get_subset_name

class CollectWorkfile(pyblish.api.ContextPlugin):
    label = "Collect Workfile"
    order = pyblish.api.CollectorOrder - 0.4
    hosts = ["tvpaint"]

    def process(self, context):
        current_file = context.data["currentFile"]

        self.log.info(
            "Workfile path used for workfile family: {}".format(current_file)
        )

        dirpath, filename = os.path.split(current_file)
        basename, ext = os.path.splitext(filename)
        instance = context.create_instance(name=basename)

        # Project name from workfile context
        project_name = context.data["workfile_context"]["project"]

        # Get subset name of workfile instance
        # Collect asset doc to get asset id
        # - not sure if it's good idea to require asset id in
        #   get_subset_name?
        family = "workfile"
        asset_name = context.data["workfile_context"]["asset"]
        asset_doc = get_asset_by_name(project_name, asset_name)

        # Host name from environment variable
        host_name = os.environ["AVALON_APP"]
        # Use empty variant value
        variant = ""
        task_name = legacy_io.Session["AVALON_TASK"]
        subset_name = get_subset_name(
            family,
            variant,
            task_name,
            asset_doc,
            project_name,
            host_name,
            project_settings=context.data["project_settings"]
        )

        # Create Workfile instance
        instance.data.update({
            "subset": subset_name,
            "asset": context.data["asset"],
            "label": subset_name,
            "publish": True,
            "family": "workfile",
            "families": ["workfile"],
            "representations": [{
                "name": ext.lstrip("."),
                "ext": ext.lstrip("."),
                "files": filename,
                "stagingDir": dirpath
            }]
        })
        self.log.info("Collected workfile instance: {}".format(
            json.dumps(instance.data, indent=4)
        ))


# 1. 2579 - 계단 오르기 (https://www.acmicpc.net/problem/2579)
"""
문제 설명
계단 오르기 게임은 계단 아래 시작점부터 계단 꼭대기에 위치한 도착점까지 가는 게임이다.
각각의 계단에는 일정한 점수가 쓰여 있는데 계단을 밟으면 그 계단에 쓰여 있는 점수를 얻게 된다.
계단 오르는 데는 다음과 같은 규칙이 있다.

- 계단은 한 번에 한 계단씩 또는 두 계단씩 오를 수 있다. 즉, 한 계단을 밟으면서 이어서 다음 계단이나, 다음 다음 계단으로 오를 수 있다.
- 연속된 세 개의 계단을 모두 밟아서는 안 된다. 단, 시작점은 계단에 포함되지 않는다.
- 마지막 도착 계단은 반드시 밟아야 한다.

각 계단에 쓰여 있는 점수가 주어질 때 이 게임에서 얻을 수 있는 총 점수의 최댓값을 구하는 프로그램을 작성하시오.
"""

# 내 풀이
n = int(input())
s = [0 for i in range(301)]
dp = [0 for i in range(301)]

for i in range(n):
    s[i] = int(input())

dp[0] = s[0]
dp[1] = s[0] + s[1]
dp[2] = max(s[1] + s[2], s[0] + s[2])

for i in range(3, n):
    dp[i] = max(dp[i - 3] + s[i - 1] + s[i], dp[i - 2] + s[i])

print(dp[n - 1])

"""
insight 정리
1. 다이나믹 프로그래밍의 핵심은 점화식을 찾아 테이블을 구성하는 것. 즉, 규칙을 알아내는 것이 핵심이다.
2. 이 문제가 체감상 어려웠던 이유는 특정 상황에 대한 예외처리 때문(3계단 연속 오르기 금지)
3. n을 구하기 위해 n-1만 고려하는 것은 너무 아마추어스러운 사고방식. 홀/짝수에 따라 경우가 달라질수도 있고,
이전 2 ~ 4개의 값들을 모두 고려해야 하는 경우가 있을수도 있다
4. 이 문제 해결하는데 시간이 많이 걸리긴 했지만, dp의 개념을 체화한 것 같다는 느낌이 들어서 굳
"""

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

# No. 문제번호 - 문제이름 (link)
"""
문제 설명
2xn 직사각형을 1x2, 2x1과 2x2 타일로 채우는 방법의 수를 구하는 프로그램을 작성하시오.
"""

# 내 풀이
import sys
n = int(sys.stdin.readline())
dp = [0] * (n + 1)

def calculate(num) :
    if num == 1 :
        return 1
    if num == 2 :
        return 3
    if dp[num] == 0 :
        dp[num] = calculate(num - 2) * 2 + calculate(num - 1)

    return dp[num]

print(calculate(n) % 10007)

"""
insight 정리
1. 점화식을 구할 때, 왜 이런 식이 나오는지 원리를 꼭 고민할 것.
2. 정답에서 요구하는 접근 방법은 빠르게 찾았는데, 왜 이런 전개가 되는지 원리를 파악하지 못해 점화식을 제대로 구하지 못함
"""


class Solution(object):
    def flipAndInvertImage(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        # General Idea: Use the reverse function to flip each inner list and then flip the 1s and 0s using an if statement.

        for i, list in enumerate(A):
            A[i].reverse();
            for j, num in enumerate(A[i]):
                if num == 1:
                    A[i][j] = 0;
                else:
                    A[i][j] = 1;
        return A


"""Backs up the database to a human-readable JSON file."""

import datetime
import os
import subprocess  # nosec
import sys

if __name__ == "__main__":
    # Define paths
    repo_dir = os.path.join(os.path.dirname(__file__), os.pardir)
    manage_path = os.path.join(repo_dir, "manage.py")
    datestr = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
    out_path = os.path.join(repo_dir, "fixtures", f"data_{datestr}.json")

    # Run django-admin's dumpdata with proper args
    subprocess.call(  # nosec
        [
            sys.executable,
            manage_path,
            "dumpdata",
            "--format=json",
            "--indent=2",
            "--exclude=admin",
            # '--exclude=auth',
            "--exclude=contenttypes",
            "--exclude=sessions",
            "--verbosity=1",
            f"--output={out_path}",
        ]
    )


## 2.

##Import random module
##
##Display welcome message and explain game rules
##
##Set wincount and totalcount zero
##
##Display user selection choice of Rock, Paper, Scissor
##If user selects a nonexisting option, generate error message and ask for selection choice until user chooses one that is available
##
##Computer chooses one random choice
##
##Compare
##
##If user choice = computer choice
##  print "Tie"
##  increment totalcount value
##
##If user choice = "paper" and computer choice = "scissor"
##  print "Computer Win"
##  increment totalcount value
##
##If user choice = "scissor" and computer choice = "rock"
##  print "Computer Win"
##  increment totalcount value
##
##If user choice = "rock" and computer choice = "paper"
##  print "Computer Win"
##  increment totalcount value
##
##If user choice = "paper" and computer choice = "rock"
##  print "User Win"
##  increment wincount value and totalcount value
##
##If user choice = "scissor" and computer choice = "paper"
##  print "User Win"
##  increment wincount value and totalcount value
##
##If user choice = "rock" and computer choice = "scissor"
##  print "User Win"
##  increment wincount value and totalcount value
##
##  Choose to continue game or quit
##  If user selects continue, go back to step 4
##  If no, print user win against total play and end message

## 3.

string = input("Enter the string: ")

duplicated_string = ""

for i in range(len(string)):
    duplicated_string = duplicated_string + string[i]*2

print(duplicated_string)

## 4.

list1 = list(input().split())
list2 = list(input().split())

count = 0

for i in set(list1):
    if i in list2:
        count += 1

print(count)


import json

import pytest
import requests
from middleware.handler import Handler

data = Handler.excel.read_dict('condition')

@pytest.mark.parametrize("info", data)
def test_condition(info):
    if "#register_name#" in info['url']:
        register_name = Handler.user_config['user']['register_name']
        info['url'] = info['url'].replace('#register_name#', register_name)
    if "#unregister_name#" in info['url']:
        unregister_name = Handler.generate_random_str(6)
        info['url'] = info['url'].replace('#unregister_name#', unregister_name)
    if "#register_email#" in info['url']:
        register_email = Handler.user_config['user']['register_email']
        info['url'] = info['url'].replace('#register_email#', register_email)
    if "#unregister_email#" in info['url']:
        unregister_email = Handler.generate_random_str(9)
        unregister_email = unregister_email + "@qq.com"
        info['url'] = info['url'].replace('#unregister_email#', unregister_email)
    res = requests.request(method=info['method'],
                           url=Handler.yaml_config['host'] + info['url'])
    res_body = json.dumps(res.text)
    assert json.loads(res.text)['count'] == info['expected']


"""Collatz Conjecture
By Ted Silbernagel
Start with a number n > 1.
Find the number of steps it takes to reach one using the following process:
  If n is even, divide it by 2.
  If n is odd, multiply it by 3 and add 1.
"""

def collatz(user_no: int) -> None:
  current_no = user_no
  print(current_no)
  steps = 0

  while current_no != 1:
    if current_no % 2 == 0:
      current_no //= 2
    else:
      current_no = (current_no * 3) + 1
    steps += 1
    print(current_no)

  print(f'Took {steps} steps.')

if __name__ == '__main__':
  print('This program will perform the Collatz conjecture on a given whole number.')
  num = int(input('Please enter a number: '))

  collatz(num)


#!/usr/bin/env python
# coding: utf-8

# In[1]:

# import the necessary packages
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2
import os

# In[2]:

def image_to_feature_vector(image, size=(32, 32)):
	# resize the image to a fixed size, then flatten the image into
	# a list of raw pixel intensities
	return cv2.resize(image, size).flatten()

# In[3]:

def extract_color_histogram(image, bins=(8, 8, 8)):
	# extract a 3D color histogram from the HSV color space using
	# the supplied number of `bins` per channel
	hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
	hist = cv2.calcHist([hsv], [0, 1, 2], None, bins,
		[0, 180, 0, 256, 0, 256])
	# handle normalizing the histogram if we are using OpenCV 2.4.X
	if imutils.is_cv2():
		hist = cv2.normalize(hist)
	# otherwise, perform "in place" normalization in OpenCV 3 (I
	# personally hate the way this is done
	else:
		cv2.normalize(hist, hist)
	# return the flattened histogram as the feature vector
	return hist.flatten()

# In[4]:

train_args = {
    'dataset': './train',
    'neighbors': 10,
    'jobs': -1
}

val_args = {
    'dataset': './val',
    'neighbors': 10,
    'jobs': -1
}

test_args = {
    'dataset': './test',
    'neighbors': 10,
    'jobs': -1
}

# In[5]:

# grab the list of images that we'll be describing
print("[INFO] describing images...")
train_imagePaths = list(paths.list_images(train_args["dataset"]))
val_imagePaths = list(paths.list_images(val_args["dataset"]))
test_imagePaths = list(paths.list_images(test_args["dataset"]))

# initialize the raw pixel intensities matrix, the features matrix,
# and labels list
train_rawImages = []
train_features = []
train_labels = []
val_rawImages = []
val_features = []
val_labels = []
test_rawImages = []
test_features = []
test_labels = []

#print(train_imagePaths)

# In[6]:

# Randomizes list and pulls a subset for faster debugging

import random

#random.shuffle(train_imagePaths)
#train_imagePaths = train_imagePaths[:50]

# In[7]:

# loop over the input images
for (i, imagePath) in enumerate(train_imagePaths):
	# load the image and extract the class label (assuming that our
	# path as the format: /path/to/dataset/{class}.{image_num}.jpg
	image = cv2.imread(imagePath)
	label = imagePath.split(os.path.sep)[-2]
	# extract raw pixel intensity "features", followed by a color
	# histogram to characterize the color distribution of the pixels
	# in the image
	pixels = image_to_feature_vector(image)
	hist = extract_color_histogram(image)
	# update the raw images, features, and labels matricies,
	# respectively
	train_rawImages.append(pixels)
	train_features.append(hist)
	train_labels.append(label)
	# show an update every 1,000 images
	if i > 0 and i % 1000 == 0:
		print("[INFO] processed {}/{}".format(i, len(train_imagePaths)))

# loop over the input images
for (i, imagePath) in enumerate(val_imagePaths):
	# load the image and extract the class label (assuming that our
	# path as the format: /path/to/dataset/{class}.{image_num}.jpg
	image = cv2.imread(imagePath)
	label = imagePath.split(os.path.sep)[-2]
	# extract raw pixel intensity "features", followed by a color
	# histogram to characterize the color distribution of the pixels
	# in the image
	pixels = image_to_feature_vector(image)
	hist = extract_color_histogram(image)
	# update the raw images, features, and labels matricies,
	# respectively
	val_rawImages.append(pixels)
	val_features.append(hist)
	val_labels.append(label)
	# show an update every 1,000 images
	if i > 0 and i % 1000 == 0:
		print("[INFO] processed {}/{}".format(i, len(val_imagePaths)))

# loop over the input images
for (i, imagePath) in enumerate(test_imagePaths):
	# load the image and extract the class label (assuming that our
	# path as the format: /path/to/dataset/{class}.{image_num}.jpg
	image = cv2.imread(imagePath)
	label = imagePath.split(os.path.sep)[-2]
	# extract raw pixel intensity "features", followed by a color
	# histogram to characterize the color distribution of the pixels
	# in the image
	pixels = image_to_feature_vector(image)
	hist = extract_color_histogram(image)
	# update the raw images, features, and labels matricies,
	# respectively
	test_rawImages.append(pixels)
	test_features.append(hist)
	test_labels.append(label)
	# show an update every 1,000 images
	if i > 0 and i % 1000 == 0:
		print("[INFO] processed {}/{}".format(i, len(test_imagePaths)))

# In[8]:

# show some information on the memory consumed by the raw images
# matrix and features matrix
train_rawImages = np.array(train_rawImages)
train_features = np.array(train_features)
train_labels = np.array(train_labels)
print("[INFO] pixels matrix: {:.2f}MB".format(
	train_rawImages.nbytes / (1024 * 1000.0)))
print("[INFO] features matrix: {:.2f}MB".format(
	train_features.nbytes / (1024 * 1000.0)))

val_rawImages = np.array(val_rawImages)
val_features = np.array(val_features)
val_labels = np.array(val_labels)
print("[INFO] pixels matrix: {:.2f}MB".format(
	val_rawImages.nbytes / (1024 * 1000.0)))
print("[INFO] features matrix: {:.2f}MB".format(
	val_features.nbytes / (1024 * 1000.0)))

test_rawImages = np.array(test_rawImages)
test_features = np.array(test_features)
test_labels = np.array(test_labels)
print("[INFO] pixels matrix: {:.2f}MB".format(
	test_rawImages.nbytes / (1024 * 1000.0)))
print("[INFO] features matrix: {:.2f}MB".format(
	test_features.nbytes / (1024 * 1000.0)))

# In[20]:

# partition the data into training and testing splits, using 75%
# of the data for training and the remaining 25% for testing
(trainRI, valRI, trainRL, valRL) = train_test_split(
	train_rawImages, train_labels, test_size=0.10, random_state=42)
(trainFeat, valFeat, trainLabels, valLabels) = train_test_split(
	train_features, train_labels, test_size=0.10, random_state=42)

# trainRI = train_rawImages
# trainRL = train_labels
# trainFeat = train_features
# trainLabels = train_labels

# valRI = val_rawImages
# valRL = val_labels
# valFeat = val_features
# valLabels = val_labels

testRI = test_rawImages
testRL = test_labels
testFeat = test_features
testLabels = test_labels

# In[23]:

# Find good k value using val dataset
#train and evaluate a k-NN classifer on the raw pixel intensities
#print("[INFO] evaluating raw pixel accuracy...")
k_acc = [0]
for k in range(1,51):
    model = KNeighborsClassifier(n_neighbors=k,
        n_jobs=train_args["jobs"])
    model.fit(trainRI, trainRL)
    acc = model.score(valRI, valRL)
    k_acc.append(acc)
    print("[INFO] raw pixel accuracy: {:.2f}%".format(acc * 100))

k_opt = k_acc.index(max(k_acc))
print(k_opt)

# In[24]:

#train and evaluate a k-NN classifer on the raw pixel intensities
print("[INFO] evaluating raw pixel accuracy...")
model = KNeighborsClassifier(n_neighbors=k_opt,
	n_jobs=train_args["jobs"])
model.fit(trainRI, trainRL)
acc = model.score(testRI, testRL)
print("[INFO] raw pixel accuracy: {:.2f}%".format(acc * 100))

# In[25]:

# Find good k value using val dataset
#train and evaluate a k-NN classifer on the raw pixel intensities
#print("[INFO] evaluating raw pixel accuracy...")
k_acc = [0]
for k in range(1,51):
    model = KNeighborsClassifier(n_neighbors=k,
        n_jobs=train_args["jobs"])
    model.fit(trainFeat, trainLabels)
    acc = model.score(valFeat, valLabels)
    k_acc.append(acc)
    print("[INFO] raw pixel accuracy: {:.2f}%".format(acc * 100))

k_opt = k_acc.index(max(k_acc))
print(k_opt)

# In[26]:

# train and evaluate a k-NN classifer on the histogram
# representations
print("[INFO] evaluating histogram accuracy...")
model = KNeighborsClassifier(n_neighbors=k_opt,
	n_jobs=train_args["jobs"])
model.fit(trainFeat, trainLabels)
acc = model.score(testFeat, testLabels)
print("[INFO] histogram accuracy: {:.2f}%".format(acc * 100))

# In[ ]:


#!/bin/python3

import os

# Complete the divisibleSumPairs function below.
def divisibleSumPairs(n, k, ar):
    nums = [0] * k
    count = 0
    for a in ar:
        mod = a % k
        count += nums[(k - mod) % k]
        nums[mod] += 1
    return count

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nk = input().split()

    n = int(nk[0])

    k = int(nk[1])

    ar = list(map(int, input().rstrip().split()))

    result = divisibleSumPairs(n, k, ar)

    fptr.write(str(result) + '\n')

    fptr.close()


# coding: utf-8

class Solution:
    # @param root, start, end: The root of segment tree and
    #                          an segment / interval
    # @return: The maximum number in the interval [start, end]
    def query(self, root, start, end):
        # write your code here
        if (root.start == start) and (root.end == end):
            return root.max
        mid = (root.start + root.end) / 2 # 后面根据mid区分去左右子树
        if start > mid:
            return self.query(root.right, start, end)
        elif end <= mid:
            return self.query(root.left, start, end)
        else: # start <= mid and end > mid
            left_max = self.query(root.left, start, mid)
            right_max = self.query(root.right, mid + 1, end)
            return max(left_max, right_max)

# medium: http://lintcode.com/zh-cn/problem/segment-tree-query/


# -*- coding: UTF-8 -*-
import sys
import typing

sys.path.append('..')
import common

BASE_URL = 'https://api.avgle.com'

def get_video_by_id(id: str) -> typing.Tuple[int, dict]:
    '''根据番号从 avgle 获取视频
    :param str id: 番号
    :return tuple[int, dict]: 状态码，视频链接
    视频链接：
    {
        'fv': '', # 完整视频链接
        'pv': ''  # 预览视频链接
    }
    '''
    # 初始化数据
    page = 0
    limit = 3
    url = f'{BASE_URL}/v1/jav/{id}/{page}?limit={limit}'
    res = {'fv': '', 'pv': ''}
    # 获取视频
    code, resp = common.send_req(url)
    if code != 200:
        return code, None
    if resp.json()['success']:
        videos = resp.json()['response']['videos']
        if videos != []:
            for video in videos:
                fv_url = video['video_url'].strip()
                pv_url = video['preview_video_url'].strip()
                if res['fv'] == '' and fv_url != '': res['fv'] = fv_url
                if res['pv'] == '' and pv_url != '': res['pv'] = pv_url
        return code, res
    else:
        return 404, None

def get_pv_by_id(id: str) -> typing.Tuple[int, str]:
    '''根据番号从 avgle 获取预览视频
    :param str id: 番号
    :return tuple[int, str]: 状态码，预览视频链接
    '''
    code, res = get_video_by_id(id)
    if code != 200:
        return code, None
    if res['pv'] != '':
        return 200, res['pv']
    else:
        return 404, None

def get_fv_by_id(id: str) -> typing.Tuple[int, str]:
    '''根据番号从 avgle 获取完整视频
    :param str id: 番号
    :return tuple[int, str]: 状态码，完整视频链接
    '''
    code, res = get_video_by_id(id)
    if code != 200:
        return code, None
    if res['pv'] != '':
        return 200, res['fv']
    else:
        return 404, None

if __name__ == '__main__':
    # code, res = get_fv_by_id('ssni-497')
    # code, res = get_pv_by_id('ssni-497')
    code, res = get_pv_by_id('fc2-ppv-1901670')
    if code == 200:
        print(res)


#! python3
# imageSiteDownloader.py - Takes a category that is inputed by the user
#                          and downloads imgur images of this category
#                          to a folder created by the program.
# Adam Pellot

import requests
import os
import bs4

# Asks for category of pictures.
print('Enter what kind of pictures would you like to download.')
category = input()
url = 'https://imgur.com/search?q=' + category     # Starting url.

os.chdir('C:\\Users\\Adam\\Downloads')

# Store imgur images in ./category_images.
os.makedirs(category + '_images', exist_ok=True)

# Download the page.
print('Downloading page %s...' % url)
res = requests.get(url)
res.raise_for_status()

soup = bs4.BeautifulSoup(res.text, 'html.parser')

# Find the list of images for given category.
images = soup.select('.image-list-link > img')
if images == []:
    print('Could not find images.')
else:
    # Download each image.
    for link in range(len(images)):
        imageSource = 'http://' + images[link].get("src")[2:]
        res = requests.get(imageSource)
        res.raise_for_status()
    # Save each image to ./'category'.
        imageFile = open(os.path.join(category + '_images',
                                      os.path.basename(imageSource)), 'wb')
        for chunk in res.iter_content(100000):
            imageFile.write(chunk)
            imageFile.close()

print('Done.')


#mandatory
from inspect import getsourcefile
import sys
from NLPHelpers import text_analysis
import ccxt

def FetchCoinMarketPrice(params):
    entities = params["entities"]
    request = params["request"]
    sentiment = params["sentiment"]
    context = params["context"]

    exchange = ccxt.gdax({})
    exchanges = text_analysis.find_entity_key(entities, "cryptocurrency_exchange")

    coins = text_analysis.find_entity_key(entities, "cryptocurrency_market")#["entity"]

    if len(exchanges) > 0:
        if exchanges[0]["entity"] == "Not found":
            pass
        elif exchanges[0]["entity"] == "binance":
            exchange = ccxt.binance({})
        elif exchanges[0]["entity"] == "exmo":
            exchange = ccxt.exmo({})

        elif exchanges[0]["entity"] == "kraken":
            exchange = ccxt.kraken({})

    if len(coins) > 0:
        if coins[0]["entity"] == "Not found":
            needed_from_bing = []
            return {"follow_up": True, "response": "You must tell me what coin market you would like a price quote for.", "store":False, "needed_from_bing":needed_from_bing, "request":request}

        market_one = None
        market_two = "USD"
        if exchanges[0]["entity"] == "binance" or exchanges[0]["entity"] == "exmo":
            market_two = "USDT"

        for coin in coins:
            if coin["role"] is None:
                market_one = coin["entity"].upper()
            elif coin["role"] == "product":
                market_one = coin["entity"].upper()
            elif coin["role"] == "market":
                market_two = coin["entity"].upper()

        symbol = market_one + "/" + market_two
        print(symbol)
        try:
            ticker = exchange.fetch_ticker(symbol)["last"]
            return {"follow_up":"false", "response": "The price of " + market_one + " is " + str(ticker) + " " + market_two, "store": False}

        except Exception as e:
            return {"follow_up":"false", "response":e.message}