import multiprocessing
import os
import sys
from abc import ABC, abstractmethod
from email import message
from multiprocessing.pool import AsyncResult
from typing import Iterable, List

from src.config.location import Location
from src.config.test_case_config import TestCaseConfig
from src.config.test_case_failure import TestCaseFailure
from src.config.types.handler_type import HandlerType
from src.config.types.mode_type import ModeType
from src.config.types.path_type import PathType
from src.suite.program import Program
from src.suite.run_time_data import RunTimeData
from src.suite.test_bench_settings import TestBenchSettings
from src.suite.test_case import TestCase
from src.suite.test_case_result import TestCaseResult
from src.utils.common import log_header, log_separator, log_sub_header
from src.utils.errors.test_bench_error import TestBenchError
from src.utils.handlers.handler_factory import HandlerFactory
from src.utils.handlers.resolve_handler import ResolveHandler
from src.utils.logging.i_logger import ILogger
from src.utils.logging.i_main_logger import IMainLogger
from src.utils.logging.test_loggers.i_test_logger import ITestLogger
from src.utils.logging.test_loggers.test_result_type import TestResultType
from src.utils.paths import Paths

class TestSetRunner(ABC):
    """Run test cases in reference or compare mode"""

    def __init__(self, settings: TestBenchSettings, logger: IMainLogger) -> None:
        self.__settings = settings
        self.__logger = logger
        self.programs: List[Program] = []
        self.finished_tests: int = 0

    @property
    def settings(self) -> TestBenchSettings:
        """Settings used for running tests

        Returns:
            TestBenchSettings: Used test settings
        """
        return self.__settings

    def run(self):
        """Run test cases to generate reference data"""
        try:
            self.programs = list(self.__update_programs())
        except Exception:
            if self.__settings.teamcity:
                sys.stderr.write("##teamcity[testStarted name='Update programs']\n")
                sys.stderr.write(
                    "##teamcity[testFailed name='Update programs' message='Exception occurred']\n"
                )

        n_testcases = len(self.__settings.configs)
        log_sub_header("Running tests", self.__logger)

        max_processes = min(len(self.__settings.configs), multiprocessing.cpu_count())

        with multiprocessing.Pool(processes=max_processes) as pool:
            self.finished_tests = 0
            result_futures: List[AsyncResult] = []

            for i_testcase, config in enumerate(self.__settings.configs):
                test_logger = self.__logger.create_test_case_logger(config.name)
                config_result_future = pool.apply_async(
                    self.run_test_case,
                    [config, i_testcase, n_testcases, test_logger],
                    callback=self.__log_successful_test,
                    error_callback=self.__log_failed_test,
                )

                result_futures.append(config_result_future)

            pool.close()
            pool.join()

            results: List[TestCaseResult] = []
            for result in result_futures:
                results.append(result.get())

        log_separator(self.__logger, char="-", with_new_line=True)

        self.show_summary(results, self.__logger)

    def __check_for_skipping(self, config: TestCaseConfig):
        skip_testcase = False  # No check defined still running (so no regression test, test against measurements or other numerical package)
        skip_postprocessing = True  # No check defined still running and do not perform the standard postprocessing

        if len(config.checks) > 0:
            skip_testcase = True
            skip_postprocessing = True

        for file_check in config.checks:
            if not file_check.ignore:
                skip_testcase = False
                skip_postprocessing = False

        if not skip_testcase:
            if config.ignore:
                skip_testcase = True
                skip_postprocessing = True

        return skip_testcase, skip_postprocessing

    def run_test_case(
        self,
        config: TestCaseConfig,
        i_testcase: int,
        n_testcases: int,
        logger: ITestLogger,
    ) -> TestCaseResult:
        """Runs one test configuration (in a separate process)

        Args:
            config (TestCaseConfig): configuration to run
            i_testcase (int): test case index
            n_testcases (int): total amount of test cases
            logger (ITestLogger): logger for this test case
        """
        test_result: TestCaseResult = TestCaseResult(config)

        skip_testcase, skip_postprocessing = self.__check_for_skipping(config)
        if not skip_testcase:
            logger.test_started()
        else:
            logger.test_ignored()

        curr_process = multiprocessing.current_process()
        process_id = "Unknown"
        if curr_process and curr_process.ident:
            process_id = str(curr_process.ident)

        log_header(
            f"Testcase {i_testcase + 1} of {n_testcases} (process id {process_id}): {config.name} ...",
            logger,
        )

        try:
            log_sub_header(f"Updating test case name = '{config.name}'", logger)
            self.__prepare_test_case(config, logger)
            log_separator(logger, char="-")

            # Run testcase
            testcase = TestCase(config, logger)

            if self.__settings.only_post:
                logger.info("Skipping execution of testcase (postprocess only)...\n")
            else:
                if not skip_testcase:
                    log_sub_header("Execute testcase...", logger)
                    testcase.run(self.programs)
                    log_separator(logger, char="-")
                else:
                    logger.info("Testcase not executed (ignored)...\n")

            # Check for errors during execution of testcase
            if len(testcase.getErrors()) > 0:
                errstr = "\n"
                for error in testcase.getErrors():
                    errstr = errstr + str(error) + "\n"
                logger.error("Errors during testcase: " + errstr)
                raise TestCaseFailure("Errors during testcase: " + errstr)

            # Postprocessing
            if not skip_postprocessing:
                log_sub_header(
                    "Postprocessing testcase, checking directories...", logger
                )

                if not os.path.exists(config.absolute_test_case_path):
                    raise TestCaseFailure(
                        "Could not locate case data at: "
                        + str(config.absolute_test_case_path)
                    )

                # execute concrete method in subclass
                test_result = self.post_process(config, logger)
                log_separator(logger, char="-")

            if not skip_testcase:
                logger.test_Result(TestResultType.Passed)

        except Exception as exception:
            logger.error(str(exception))
            test_result = self.create_error_result(config)

            if not skip_testcase:
                logger.test_Result(TestResultType.Exception, exception)
        finally:
            # Debug statements:
            # Something goes wrong on Linux with passing through the output of esm_create to
            # setenv(DIO_SHM_ESM)/esm_delete. It only works fine the first time (and the 6th).
            # It seems that when esm_create is executed for the second testcase, the output in
            # RunTimeData is not overwritten.
            # To tackle this problem:
            # - Only the output of esm_create is being stored (introduced: flag storeOutput="true")
            # - At the end of each testcase (here):
            #   - ALL stored output is dumped to screen
            #   - ALL stored output is removed
            RunTimeData().dump(logger)
            RunTimeData().clean()

        logger.test_finished()
        return test_result

    @abstractmethod
    def post_process(
        self, test_case_config: TestCaseConfig, logger: ITestLogger
    ) -> TestCaseResult:
        """Post process run results (files)

        Args:
            test_case_config (TestCaseConfig): configuration of the run
            logger (ITestLogger): logger to log to

        Returns:
            TestCaseResult: Result of the post processing
        """
        logger.debug(
            f"Reference directory:{test_case_config.absolute_test_case_reference_path}"
        )
        logger.debug(f"Results   directory:{test_case_config.absolute_test_case_path}")

    @abstractmethod
    def show_summary(self, results: List[TestCaseResult], logger: ILogger):
        """Shows a summery showing the results of all tests that were run

        Args:
            results (List[TestCaseResult]): list of test results to summarize
            logger (ILogger): logger to log to
        """

    @abstractmethod
    def create_error_result(self, testCaseConfig: TestCaseConfig) -> TestCaseResult:
        """Creates an error result

        Args:
            testCaseConfig (TestCaseConfig): test case to use

        Returns:
            TestCaseResult: Error result
        """

    def __log_successful_test(self, test_case_result: TestCaseResult):
        self.finished_tests += 1
        self.__logger.info(
            f"Finished running ({self.finished_tests}/{len(self.__settings.configs)}): {test_case_result.config.name}"
        )

    def __log_failed_test(self, exception: BaseException):
        self.finished_tests += 1
        self.__logger.error(
            f"Error running ({self.finished_tests}/{len(self.__settings.configs)}): {str(exception)}"
        )

    def __update_programs(self) -> Iterable[Program]:
        """Update network programs and initialize the stack"""

        log_sub_header("Updating programs", self.__logger)

        for program_configuration in self.__settings.programs:
            self.__logger.info(f"Updating program: {program_configuration.name}")

            # Local path to program root folder
            program_local_path = None

            # Get the program location
            if len(program_configuration.locations) > 0:
                for loc in program_configuration.locations:
                    # check type of program
                    if (
                        self.__settings.run_mode == ModeType.REFERENCE
                        and loc.type == PathType.REFERENCE
                    ) or (
                        self.__settings.run_mode == ModeType.COMPARE
                        and loc.type == PathType.CHECK
                    ):
                        # if the program is local, use the existing location
                        sourceLocation = Paths().mergeFullPath(loc.root, loc.from_path)
                        if Paths().isPath(sourceLocation):
                            absLocation = os.path.abspath(
                                Paths().mergeFullPath(
                                    sourceLocation, program_configuration.path
                                )
                            )
                            if (
                                ResolveHandler.detect(absLocation, self.__logger, None)
                                == HandlerType.PATH
                            ):
                                if not os.path.exists(absLocation):
                                    self.__logger.warning(
                                        f"could not yet detect specified program {absLocation}"
                                    )
                                #                                   raise SystemExit("Program does not exist")
                                else:
                                    self.__logger.debug(
                                        f"detected local path for program {program_configuration.name}, using {absLocation}"
                                    )
                                program_configuration.absolute_bin_path = absLocation
                        # else download it from a remote location
                        else:
                            if loc.version:
                                to = loc.to_path + "_" + loc.version
                            else:
                                to = loc.to_path
                            program_local_path = Paths().rebuildToLocalPath(
                                os.path.join(
                                    self.__settings.local_paths.engines_path, to
                                )
                            )

                            # if the program is remote (network or other) and it does not exist locally, download it
                            if not os.path.exists(program_local_path):
                                self.__logger.debug(
                                    f"Downloading program, {program_configuration.name} from {sourceLocation}"
                                )
                                HandlerFactory.download(
                                    sourceLocation,
                                    program_local_path,
                                    self.programs,
                                    self.__logger,
                                    loc.credentials,
                                    loc.version,
                                )
                            program_configuration.absolute_bin_path = os.path.abspath(
                                Paths().mergeFullPath(
                                    program_local_path, program_configuration.path
                                )
                            )

            # If a program does not have a network path, and path is not a relative or absolute path, we assume the system can find it
            elif not Paths().isPath(program_configuration.path):
                program_configuration.absolute_bin_path = program_configuration.path
            # Otherwise we need to construct the path from the given information
            else:
                # Construct the absolute binary path for the program
                absbinpath = os.path.abspath(
                    Paths().rebuildToLocalPath(program_configuration.path)
                )
                if os.path.exists(absbinpath):
                    program_configuration.absolute_bin_path = absbinpath
                # If the local program does not exist, and a network path is not given we are going to crash
                else:
                    raise SystemExit(
                        "Could not find "
                        + program_configuration.name
                        + " at given location "
                        + absbinpath
                    )
            self.__logger.debug(
                f"Binary path for program {program_configuration.name}: {program_configuration.absolute_bin_path}"
            )

            # Rebuild the environment variables (specified for this program) to local system variables
            # This is the only place containing all relevant information
            # Do not rebuild the environment variable when it contains a keyword surrounded by "[" and "]",
            # they will be replaced later on
            envparams = program_configuration.environment_variables
            for envparam in envparams:
                if (
                    envparams[envparam][0] == "path"
                    and str(envparams[envparam][1]).find("[") == -1
                ):
                    pp = Paths().rebuildToLocalPath(envparams[envparam][1])
                    if not Paths().isAbsolute(pp):
                        if program_local_path:
                            pp = os.path.abspath(
                                Paths().mergeFullPath(program_local_path, pp)
                            )
                        envparams[envparam] = [envparams[envparam][0], pp]
                    else:
                        envparams[envparam] = [
                            envparams[envparam][0],
                            envparams[envparam][1],
                        ]

            # Add search paths to the program(configure)
            # Search for (the last) win/lnx/linux in AbsoluteBinPath,
            # add all subdirectories from this level downwards to searchPaths
            # It's quite crude, but this way, all Delft3D programs are able to find each other.
            if program_configuration.add_search_paths:
                pltIndex = max(
                    program_configuration.absolute_bin_path.rfind("win"),
                    program_configuration.absolute_bin_path.rfind("lnx"),
                    program_configuration.absolute_bin_path.rfind("linux"),
                    program_configuration.absolute_bin_path.rfind("x64"),
                )
                if pltIndex > -1:
                    separatorIndex = max(
                        program_configuration.absolute_bin_path[pltIndex:].find("\\"),
                        program_configuration.absolute_bin_path[pltIndex:].find("/"),
                    )
                    pltPath = program_configuration.absolute_bin_path[
                        : pltIndex + separatorIndex
                    ]
                    self.__logger.debug("Path: " + pltPath)
                    searchPaths = Paths().findAllSubFolders(
                        pltPath, program_configuration.exclude_search_paths_containing
                    )
                else:
                    # No win/lnx/linux found in AbsoluteBinPath:
                    # Just add AbsoluteBinPath and its subFolders
                    searchPaths = Paths().findAllSubFolders(
                        program_configuration.absolute_bin_path,
                        program_configuration.exclude_search_paths_containing,
                    )
                # Add explicitly named searchPaths, rebuild when needed
                for aPath in program_configuration.search_paths:
                    aRebuildPath = Paths().rebuildToLocalPath(aPath)
                    if not Paths().isAbsolute(aRebuildPath) and program_local_path:
                        aRebuildPath = Paths().mergeFullPath(
                            program_local_path, aRebuildPath
                        )
                    searchPaths.append(aRebuildPath)
                program_configuration.search_paths = searchPaths

            # Initialize the program
            yield Program(program_configuration, self.settings)
        log_separator(self.__logger, char="-", with_new_line=True)

    def __prepare_test_case(self, config: TestCaseConfig, logger: ILogger):
        """Prepare test case based on provided config
        (download input & reference data)

        Args:
            config (TestCaseConfig): test configuration to prepare

        Raises:
             TestBenchError : if test can not be prepared
        """
        logger.info(f"Updating case: {config.name}")

        if len(config.locations) == 0:
            error_message: str = (
                f"Could not update case {config.name}," + " no network paths given"
            )
            raise TestBenchError(error_message)

        for location in config.locations:
            if location.root == "" or location.from_path == "":
                error_message: str = (
                    f"Could not update case {config.name}"
                    + ", invalid network input path part (root:{location.root},"
                    + " from:{location.from_path}) given"
                )
                raise TestBenchError(error_message)

            # Build the path to download from: Root+From+testcasePath:
            # Root: https://repos.deltares.nl/repos/DSCTestbench/cases
            # From: trunk/win32_hp
            # testcasePath: e01_d3dflow\f01_general\c03-f34
            remote_path = Paths().mergeFullPath(
                location.root, location.from_path, config.path
            )

            if Paths().isPath(remote_path):
                remote_path = os.path.abspath(remote_path)

            # Downloading the testcase input/refdata may fail when it is already present and have to be
            # deleted first. This probably has to do with TortoiseSVNCache, accessing that directory.
            # When trying a second time it normally works. Safe side: try 3 times.
            success = False
            attempts = 0
            while attempts < 3 and not success:
                attempts += 1
                try:
                    destination_dir = None
                    input_description = ""

                    if location.type == PathType.INPUT:
                        destination_dir = self.__settings.local_paths.cases_path
                        input_description = "input of case"

                    if location.type == PathType.REFERENCE:
                        destination_dir = self.__settings.local_paths.reference_path
                        input_description = "reference result"

                    if destination_dir is not None:
                        # Build localPath to download to: To+testcasePath
                        localPath = Paths().rebuildToLocalPath(
                            Paths().mergeFullPath(
                                destination_dir,
                                location.to_path,
                                config.path,
                            )
                        )
                        self.__download_file(
                            location, remote_path, localPath, input_description, logger
                        )

                        if location.type == PathType.INPUT:
                            config.absolute_test_case_path = localPath

                        if location.type == PathType.REFERENCE:
                            config.absolute_test_case_reference_path = localPath

                    success = True

                except Exception:
                    error_message = (
                        f"Unable to download testcase (attempt {attempts + 1})"
                    )

                    if attempts < 3:
                        logger.warning(error_message)
                    else:
                        logger.error(error_message)
                        raise TestBenchError("Unable to download testcase")

    def __download_file(
        self,
        location_data: Location,
        remote_path: str,
        local_path: str,
        location_description: str,
        logger: ILogger,
    ):
        if self.__settings.only_post:
            logger.info("Skipping testcase download (postprocess only)")
        else:
            logger.debug(
                f"Downloading {location_description}, {local_path} from {remote_path}"
            )

        # Download location on local system is always cleaned before start
        try:
            HandlerFactory.download(
                remote_path,
                local_path,
                self.programs,
                logger,
                location_data.credentials,
                location_data.version,
            )
        except Exception as exception:
            # We need always case input data
            logger.error(f"Could not download from {remote_path}")
            raise exception


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

from django.conf import settings
from django.urls import reverse
from django.utils.six.moves.urllib.parse import urlparse
from django.utils.translation import ugettext as _

import pytest

from ..factories import AdminFactory, UserFactory

@pytest.mark.django_db
def test_login_required(django_app):
    url = reverse('mobetta:icu_file_list', kwargs={'lang_code': 'nl'})
    response = django_app.get(url, status=302)
    redirect = urlparse(response.location)
    assert redirect.path == settings.LOGIN_URL
    assert redirect.query == 'next={}'.format(url)

@pytest.mark.django_db
def test_no_permission(django_app):
    url = reverse('mobetta:icu_file_list', kwargs={'lang_code': 'nl'})
    django_app.get(url, user=UserFactory.create(), status=403)

@pytest.mark.django_db
def test_file_stats(django_app, real_icu_file):
    user = AdminFactory.create()
    url = reverse('mobetta:icu_file_list', kwargs={'lang_code': 'nl'})
    response = django_app.get(url, user=user, status=200)
    file_row = response.html.find('tr', id='file_detail_{}'.format(real_icu_file.pk))

    col_titles = ['name', 'total_messages', 'filename',
                  'created', 'edit_history', 'download']
    stats_cells = file_row.find_all('td', recursive=False)
    stats_results = dict(zip(col_titles, [cell.text for cell in list(stats_cells)]))

    assert stats_results['name'] == real_icu_file.name
    assert stats_results['total_messages'] == '2'
    assert stats_results['filename'] == real_icu_file.filepath
    assert stats_results['edit_history'] == _('View')
    assert stats_results['download'] == _('Download')

@pytest.mark.django_db
def test_file_download_link(django_app, real_icu_file):
    """
    Assert that the download link works correctly.
    """
    user = AdminFactory.create()
    url = reverse('mobetta:icu_file_list', kwargs={'lang_code': 'nl'})
    response = django_app.get(url, user=user, status=200)
    download = response.click(_('Download'))  # there should only be one entry
    assert download.status_code == 200
    assert download.content_type == 'application/json'
    assert download.content_disposition == 'attachment; filename="{}_nl.json"'.format(
        real_icu_file.name.lower()
    )
    with open(real_icu_file.filepath, 'rb') as json_file:
        expected_content = json_file.read()
    assert download.content == expected_content


"""Common functions for chirp and depending modules."""

import itertools
import logging
import os
import subprocess

import six

LG = logging.getLogger("c4irp")

# Pyhton2 doesn't have ProcessLookupError, we just use some not to generic
# exception instead
if six.PY2:
    MyProcessLookupError = subprocess.CalledProcessError
else:
    MyProcessLookupError = ProcessLookupError  # noqa

class TransparentStrRepr(str):
    """A string implementation with a transparent repr."""

    def __repr__(self):
        """Just return the string: make repr transparent."""
        return self

def collect_processes(procs):
    """Terminate and collect output of subprocesses."""
    TR = TransparentStrRepr
    for proc in procs:
        assert isinstance(proc, subprocess.Popen)
        if proc.returncode is None:
            try:
                proc.kill()
            except MyProcessLookupError:  # pragma: no cover
                pass
        LG.debug(
            "Proc %s returncode: %s",
            proc.args,
            proc.returncode,
        )
        LG.debug(
            "Proc %s stdout: %s",
            proc.args,
            TR(proc.stdout.read().decode("UTF-8")),
        )
        LG.debug(
            "Proc %s stderr: %s",
            proc.args,
            TR(proc.stderr.read().decode("UTF-8")),
        )

def complete_config(config, base):
    """Complete a given config with values from a object.

    like: :class:`.const.Config`.

    :param config: The supplied config as either a object or a dictionary.
    :type  config: :py:class:`object` or :py:class:`dict`
    :param   base: The base object which contains the defaults.
    :type    base: object
    :rtype: :class:`.const.Config`
    """
    if config is None:
        return base
    if isinstance(config, dict):
        config_dict = config
    else:
        config_dict = {
            key: value for (key, value) in itertools.chain(
                vars(config.__class__).items(),
                vars(config).items(),
            ) if not key.startswith("_")
        }
    for (key, value) in config_dict.items():
        setattr(base, key, value)

    return base

def get_crypto_files():
    """Get default cert.pem and dh.pem.

    :rtype: list
    """
    folder = os.path.abspath(__file__).split(
        os.path.sep
    )[:-1]
    cert   = list(folder)
    dh     = list(folder)
    cert.append("cert.pem")
    dh.append("dh.pem")
    return (
        os.path.sep.join(cert),
        os.path.sep.join(dh),
    )


#!/usr/bin/python3
"""
Fabric script methods:
    do_pack(): packs web_static/ files into .tgz archive
    do_deploy(archive_path): deploys archive to webservers
    deploy(): do_packs && do_deploys
    do_clean(n=0): removes old versions and keeps n (or 1) newest versions only
Usage:
    fab -f 3-deploy_web_static.py do_clean:n=2 -i my_ssh_private_key -u ubuntu
"""
from fabric.api import local, env, put, run
from time import strftime
import os.path
env.hosts = ['35.229.54.225', '35.231.225.251']

def do_pack():
    """generate .tgz archive of web_static/ folder"""
    timenow = strftime("%Y%M%d%H%M%S")
    try:
        local("mkdir -p versions")
        filename = "versions/web_static_{}.tgz".format(timenow)
        local("tar -cvzf {} web_static/".format(filename))
        return filename
    except:
        return None

def do_deploy(archive_path):
    """
    Deploy archive to web server
    """
    if os.path.isfile(archive_path) is False:
        return False
    try:
        filename = archive_path.split("/")[-1]
        no_ext = filename.split(".")[0]
        path_no_ext = "/data/web_static/releases/{}/".format(no_ext)
        symlink = "/data/web_static/current"
        put(archive_path, "/tmp/")
        run("mkdir -p {}".format(path_no_ext))
        run("tar -xzf /tmp/{} -C {}".format(filename, path_no_ext))
        run("rm /tmp/{}".format(filename))
        run("mv {}web_static/* {}".format(path_no_ext, path_no_ext))
        run("rm -rf {}web_static".format(path_no_ext))
        run("rm -rf {}".format(symlink))
        run("ln -s {} {}".format(path_no_ext, symlink))
        return True
    except:
        return False

def deploy():
    archive_path = do_pack()
    if archive_path is None:
        return False
    success = do_deploy(archive_path)
    return success

def do_clean(number=0):
    if number == 0:
        number = 1
    with cd.local('./versions'):
            local("ls -lt | tail -n +{} | rev | cut -f1 -d" " | rev | \
            xargs -d '\n' rm".format(1 + number))
    with cd('/data/web_static/releases/'):
            run("ls -lt | tail -n +{} | rev | cut -f1 -d" " | rev | \
            xargs -d '\n' rm".format(1 + number))


import pandas as pd
import csv
import os
import matplotlib.image as mpimg
from matplotlib import gridspec
from skimage import color
import numpy as np
from skimage.util import dtype

def _prepare_rgba_array(arr):
    """Check the shape of the array to be RGBA and convert it to
    floating point representation.
    """
    arr = np.asanyarray(arr)

    if arr.ndim not in [3, 4] or arr.shape[-1] != 4:
        msg = ("the input array must have a shape == (.., ..,[ ..,] 4)), "
               "got {0}".format(arr.shape))
        raise ValueError(msg)

    return dtype.img_as_float(arr)

def rgba2rgb(rgba, background=(1, 1, 1)):
    """RGBA to RGB conversion.
    Parameters
    ----------
    rgba : array_like
        The image in RGBA format, in a 3-D array of shape ``(.., .., 4)``.
    background : array_like
        The color of the background to blend the image with. A tuple
        containing 3 floats between 0 to 1 - the RGB value of the background.
    Returns
    -------
    out : ndarray
        The image in RGB format, in a 3-D array of shape ``(.., .., 3)``.
    Raises
    ------
    ValueError
        If `rgba` is not a 3-D array of shape ``(.., .., 4)``.
    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
    Examples
    --------
    >>> from skimage import color
    >>> from skimage import data
    >>> img_rgba = data.logo()
    >>> img_rgb = color.rgba2rgb(img_rgba)
    """
    arr = _prepare_rgba_array(rgba)
    if isinstance(background, tuple) and len(background) != 3:
        raise ValueError('the background must be a tuple with 3 items - the '
                         'RGB color of the background. Got {0} items.'
                         .format(len(background)))

    alpha = arr[..., -1]
    channels = arr[..., :-1]
    out = np.empty_like(channels)

    for ichan in range(channels.shape[-1]):
        out[..., ichan] = np.clip(
            (1 - alpha) * background[ichan] + alpha * channels[..., ichan],
            a_min=0, a_max=1)
    return out

def load_type_dict():
    data_path = "./data"
    types_file = "types.csv"
    types_path = os.path.join(data_path,types_file)
    type_dict = {}
    with open(types_path,"r") as f:
        reader = csv.reader(f)
        next(reader,None) #Skip the header
        for row in reader:
            type_dict[int(row[0])] = {
                "label": row[1],
                "color" : row[4]
            }
    return type_dict

def load_pokemon_dict():
    """Loads the Pokemon Dictionary into memory. This dictionary contains
    information of Pokemon Typing, stored as:

    ID: {type_01: value, type_02: value}

    """
    data_path = "./data"
    pokemon_file = "pokemon_types.csv"
    pokemon_path = os.path.join(data_path,pokemon_file)
    pokemon_dict = {}
    with open(pokemon_path,"r") as f:
        reader = csv.reader(f)
        next(reader,None) #Skip the header
        for row in reader:
            pkm_id = int(row[0])
            type_slot = int(row[2])
            pkm_type = int(row[1])
            if pkm_id not in pokemon_dict:
                pokemon_dict[pkm_id] = {"type_01": None, "type_02": None}
            if type_slot == 1:
                pokemon_dict[pkm_id]["type_01"] = pkm_type
            elif type_slot == 2:
                pokemon_dict[pkm_id]["type_02"] = pkm_type
            else:
                raise ValueError("Unexpected type slot value")
    return pokemon_dict

def load_dataframe(gen_folders):
    pkm_dict = load_pokemon_dict()
    df_dict = {"id" : [], "gen": [], "type_01": [], "type_02": [], "sprite" : []}
    sprites_folder = "./sprites/pokemon/centered-sprites/"
    for gen, max_pkm in gen_folders.items():
        gen_folder = os.path.join(sprites_folder,gen)
        for pkm_id in range(1,max_pkm+1):
            image_file = "{id}.png".format(id=pkm_id)
            image_path = os.path.join(gen_folder,image_file)
            image = mpimg.imread(image_path)
            if image.shape[2] == 4:
                image = rgba2rgb(image)
            image = color.rgb2hsv(image)
            df_dict["id"].append(pkm_id)
            df_dict["type_01"].append(pkm_dict[pkm_id]["type_01"])
            df_dict["type_02"].append(pkm_dict[pkm_id]["type_02"])
            df_dict["sprite"].append(image)
            df_dict["gen"].append(gen)
    return pd.DataFrame.from_dict(df_dict)


import streamlit as st
import glob
from nltk.sentiment import SentimentIntensityAnalyzer
from pathlib import Path
import plotly.express as px

analyzer = SentimentIntensityAnalyzer()
filepaths = glob.glob("diary/*.txt")
filenames = []
positve_scores = []
negative_scores = []

for filepath in filepaths:
    filenames.append(Path(filepath).stem)
    with open(filepath, 'r') as file:
        text = file.read()

    score = analyzer.polarity_scores(text)
    positve_scores.append(score['pos'])
    negative_scores.append(score['neg'])

st.header("Diary Tone")
st.subheader("Positivity")
fig = px.line(x=filenames, y=positve_scores, labels={"x": "Dates", "y": "Positivity"})
st.plotly_chart(fig)
st.subheader("Negativity")
fig = px.line(x=filenames, y=negative_scores, labels={"x": "Dates", "y": "Negativity"})
st.plotly_chart(fig)


from typing import List
import heapq

class Solution:
    # Does not work
    # O(N^2) time | O(1) space
    def minMeetingRooms(self, intervals: List[List[int]]) -> int:
        intervals.sort(lambda x: x[0])

        used_rooms = 0

        for i in range(len(intervals)):
            for j in range(len(intervals)):
                if intervals[j][1] <= intervals[i][0]:
                    used_rooms += 1
                    break

        return used_rooms

class Solution2:
    # O(Nlog(N)) Time | O(N) Space
    def minMeetingRooms(self, intervals: List[List[int]]) -> int:

        start_times = []
        end_times = []

        for start, end in intervals:
            start_times.append(start)
            end_times.append(end)

        start_times.sort()
        end_times.sort()

        start_ptr = 0
        end_ptr = 0
        used_rooms = 0

        while start_ptr < len(intervals):
            start_room = start_times[start_ptr]
            end_room = end_times[end_ptr]

            if start_room < end_room:
                used_rooms += 1
            else:
                end_ptr += 1

            start_ptr += 1

        return used_rooms

class Solution3:
    # O(NLog(N)) time | O(N) space
    def minMeetingRooms(self, intervals: List[List[int]]) -> int:

        # If there is no meeting to schedule then no room needs to be allocated.
        if not intervals:
            return 0

        # The heap initialization
        free_rooms = []

        # Sort the meetings in increasing order of their start time.
        intervals.sort(key=lambda x: x[0])

        # Add the first meeting. We have to give a new room to the first meeting.
        heapq.heappush(free_rooms, intervals[0][1])

        # For all the remaining meeting rooms
        for i in intervals[1:]:

            # If the room due to free up the earliest is free, assign that room to this meeting.
            if free_rooms[0] <= i[0]:
                heapq.heappop(free_rooms)

            # If a new room is to be assigned, then also we add to the heap,
            # If an old room is allocated, then also we have to add to the heap with updated end time.
            heapq.heappush(free_rooms, i[1])

        # The size of the heap tells us the minimum rooms required for all the meetings.
        return len(free_rooms)

class Solution4:
    def minMeetingRooms(self, intervals: List[List[int]]) -> int:
        sorted_intervals = sorted(intervals)
        meeting_rooms = [sorted_intervals[0]]

        for i in range(1, len(sorted_intervals)):
            conference = sorted_intervals[i]
            meeting_room_is_availble = False
            j = 0
            idx = 0
            while j < len(meeting_rooms) and not meeting_room_is_availble:
                meeting_room = meeting_rooms[j]
                if conference[0] >= meeting_room[1]:
                    idx = j
                    meeting_room_is_availble = True
                j += 1

            if meeting_room_is_availble:
                meeting_rooms[idx] = conference
            else:
                meeting_rooms.append(conference)

        return len(meeting_rooms)

if __name__ == '__main__':
    intervals = [[0, 30], [5, 10], [15, 20]]

    sol = Solution2()

    print(sol.minMeetingRooms(intervals))

    rooms = [3, 4, 1, 2, 5]

    rooms = [-1 * x for x in rooms]

    print(rooms)

    rooms.sort()
    heapq.heapify(rooms)
    print(rooms)

    heapq.heappush(rooms, 7)

    print(rooms)

    print(heapq.heappop(rooms) * -1)

    print(rooms)

    heapq.heappop(rooms)

    print(rooms)

Bloomberg MFA Questions/253. Meeting Rooms II/meeting-rooms-ii.py


from tabla.models import Tabla
from .models import Numerador

def get_numero(id, entidad):
    comprobante = entidad
    """
        Una vez determinado el contador para la entidad, se obtiene el último valor
        Si el contador no existe, se crea, sino se adelanta el número
    """
    if comprobante:
        numerador = Numerador.objects.filter(comprobante=comprobante).values('ultimo_valor')
        if numerador:
            ultimo_valor = numerador[0]['ultimo_valor'] + 1
        else:
            ultimo_valor = 1

        numerador=Numerador(comprobante=comprobante, descripcion=entidad,
                            ultimo_valor=ultimo_valor, activo='S')
        numerador.save()
    else:
        ultimo_valor = 1

    return ultimo_valor


from sklearn.feature_extraction.text import TfidfVectorizer

doc1 = 'She likes python';

doc2 = 'She hates python';

tfv = TfidfVectorizer();
result = tfv.fit_transform([doc1, doc2]).toarray(); # 단어를 벡터형태로

print(tfv.vocabulary_)
print(result)


import torch.nn.functional as F
import torch.nn as nn
import random
import torch
import math

def transform_batch(batch, data_queue, device):
    """
    Slow but easily understandable non-vectorized transformation for *numerical* data only.
    Inspired from SMOTE.
    :param batch: torch.tensor : The batch data to transform.
    :param data_queue: torch.tensor: The labeled data stored in the lab_memory_module object.
    :param device: torch.device : The device.
    :return: torch.Tensor: The transformed data.
    """
    full_data = torch.cat([batch, data_queue])
    transformed_batch = torch.tensor([], device=device, dtype=torch.float32)

    for i in range(len(batch)):
        # Ignore duplicates and current point
        full_data_mask = [j for j in range(len(full_data))]  # if not torch.equal(full_data[j], full_data[i])
        full_data_mask.remove(i)

        # similarities = euclidean_distances(X=batch[i].reshape(1, -1), Y=full_data[full_data_mask])[0]
        similarities = nn.CosineSimilarity()(batch[i].repeat(len(full_data_mask), 1), full_data[full_data_mask])

        closest_point_index = full_data_mask[similarities.argmax()]

        diff_vect = (full_data[closest_point_index] - batch[i]) * random.uniform(0, 1)

        transformed_batch = torch.cat([transformed_batch, (batch[i] + diff_vect).view(1, -1)])

    return transformed_batch

def transform_batch_vectorized(batch, data_queue, device, batch_size=100):
    """
    Faster but harder to understand vectorized transformation for *numerical* data only.
    Inspired from SMOTE.
    See 'transform_batch' to really understand the logic.
    :param batch: torch.tensor: The batch data to transform.
    :param data_queue: torch.tensor: The labeled data stored in the lab_memory_module object.
    :param device: torch.device: The device.
    :param batch_size: int: During computation, the batch is cut in blocs of size batch_size. If you have memory errors, reduce it.
    :return: torch.Tensor: The transformed data.
    """
    full_data = torch.cat([batch, data_queue])

    full_similarities_matrix = torch.tensor([], device=device, dtype=torch.long)
    n_batchs = math.ceil((full_data.shape[0]) / batch_size)
    batch_start_index, batch_end_index = 0, min(batch_size, len(full_data))
    for batch_index in range(n_batchs):
        batch_similarities = F.cosine_similarity(batch.unsqueeze(1), full_data[batch_start_index:batch_end_index], dim=-1)
        full_similarities_matrix = torch.cat([full_similarities_matrix, batch_similarities], dim=1)

        batch_start_index += batch_size
        batch_end_index = min((batch_end_index + batch_size), full_data.shape[0])

    full_similarities_matrix -= torch.eye(len(batch), len(full_data), device=device)  # This way, itself wont be in the most similar instances

    most_similar_indexes = full_similarities_matrix.argmax(dim=1)

    batch_diff_vect = (full_data[most_similar_indexes] - batch) * torch.rand(len(batch), device=device).view(-1, 1)

    return batch + batch_diff_vect

def smotenc_transform_batch(batch, cat_features_mask, data_queue, device, k_neighbors=5, dist='cosine'):
    """
    Slow but easily understandable non-vectorized transformation for mixed numerical and categorical data.
    Inspired from SMOTE-NC.
    :param batch: torch.tensor: The batch data to transform.
    :param cat_features_mask: Array-like object of length (x.shape[1]). Where each element is False if this column is numerical and True if categorical.
    :param data_queue: torch.tensor: The unlabeled data stored in the unlab_memory_module object.
    :param device: torch.device: The device.
    :param k_neighbors: int: The number of neighbors to consider during the transformation.
    :param dist: The distance metric to use. Choices: ['cosine', 'euclidean'].
    :return: torch.tensor: The transformed data.
    """
    full_data = torch.cat([batch, data_queue])
    transformed_batch = torch.tensor([], device=device, dtype=torch.float32)

    for i in range(len(batch)):
        full_data_mask = torch.arange(len(full_data))
        full_data_mask = full_data_mask[full_data_mask != i]

        if dist == 'cosine':
            similarities = nn.CosineSimilarity()(batch[i].repeat(len(full_data_mask), 1), full_data[full_data_mask])
            topk_res = similarities.topk(k=k_neighbors)
            topk_similar_indexes = topk_res.indices
        elif dist == 'euclidean':
            similarities = torch.cdist(batch[i].view(1, -1), full_data[full_data_mask])
            topk_res = similarities.topk(k=k_neighbors, largest=False)
            topk_similar_indexes = topk_res.indices

        closest_points_indexes = full_data_mask[topk_similar_indexes]  # indexes in masked data

        # Select a random point between the k closest
        closest_point_index = closest_points_indexes[random.randrange(k_neighbors)]

        diff_vect = (full_data[closest_point_index] - batch[i]) * torch.rand(1, device=device)
        augmented_vect = batch[i] + diff_vect  # At this point, the categorical values are wrong

        cat_columns_indexes = torch.arange(len(cat_features_mask))[cat_features_mask]
        augmented_vect[cat_columns_indexes] = full_data[closest_points_indexes][:, cat_columns_indexes].mode(0).values

        transformed_batch = torch.cat([transformed_batch, augmented_vect.view(1, -1)])

    return transformed_batch

def smotenc_transform_batch_2(batch, cat_columns_indexes, data_queue, device, k_neighbors=5, dist='cosine', batch_size=100):
    """
    Faster but harder to understand vectorized transformation for mixed numerical and categorical data.
    See 'smotenc_transform_batch' to really understand the logic.
    Inspired from SMOTE-NC.
    :param batch: torch.tensor: The batch data to transform.
    :param cat_columns_indexes: Array-like object of the indexes of the categorical columns. Only useful when transform_method='new_2'.
    :param data_queue: The unlabeled data stored in the unlab_memory_module object.
    :param device: torch.device: The device.
    :param k_neighbors: int: The number of neighbors to consider during the transformation.
    :param dist: The distance metric to use. Choices: ['cosine', 'euclidean'].
    :param batch_size: int: During computation, the batch is cut in blocs of size batch_size. If you have memory errors, reduce it.
    :return: torch.tensor: The transformed data.
    """
    full_data = torch.cat([batch, data_queue])

    full_similarities_matrix = torch.tensor([], device=device, dtype=torch.long)

    n_batchs = math.ceil((full_data.shape[0]) / batch_size)
    batch_start_index, batch_end_index = 0, min(batch_size, len(full_data))
    for batch_index in range(n_batchs):
        if dist == 'cosine':
            similarities = F.cosine_similarity(batch.unsqueeze(1), full_data[batch_start_index:batch_end_index], dim=-1)
        elif dist == 'euclidean':
            # ToDo (below is the non-vectorized code)
            # similarities = torch.cdist(batch[i].view(1, -1), full_data)
            # similarities[i] += torch.inf  # This way, itself wont be in the most similar instances
            # topk_similar_indexes = similarities.topk(k=k_neighbors, largest=False).indices
            pass

        full_similarities_matrix = torch.cat([full_similarities_matrix, similarities], dim=1)

        batch_start_index += batch_size
        batch_end_index = min((batch_end_index + batch_size), full_data.shape[0])

    full_similarities_matrix -= torch.eye(len(batch), len(full_data), device=device)  # This way, itself wont be in the most similar instances

    batch_topk_similar_indexes = full_similarities_matrix.topk(k=k_neighbors, dim=1).indices

    # Select a random point between the k closest
    batch_closest_point_index = torch.gather(batch_topk_similar_indexes, 1, torch.randint(low=0, high=k_neighbors, size=(len(batch),), device=device).view(-1, 1))
    batch_closest_point_index = batch_closest_point_index.flatten()

    batch_closest_point = full_data[batch_closest_point_index]

    batch_diff_vect = (batch_closest_point - batch) * torch.rand(len(batch), device=device).view(-1, 1)

    augmented_batch = batch + batch_diff_vect  # At this point, the categorical values are wrong, next line fixes that

    augmented_batch[:, cat_columns_indexes] = full_data[:, cat_columns_indexes.flatten()][batch_topk_similar_indexes].mode(1).values

    return augmented_batch


"""
	Computational-Physics.py

	M. Reza Mozaffari
	Physics Group, University of Qom
"""

from math import *

class Diff_1st ():
    def __init__ (self, f, h=0.01):
        self.f = f
        self.h = h

    # 2-point O(h)
    def Forward (self, x):
        return (self.f(x + self.h) - self.f(x))/self.h

    # 2-point O(h)
    def Backward (self, x):
        return (self.f(x) - self.f(x - self.h))/self.h

    # 3-point O(h^2)
    def Central (self, x):
        return 0.5*(self.f(x + self.h) - self.f(x - self.h))/self.h

class Diff_2nd ():
    def __init__ (self, f, h=0.01):
        self.f = f
        self.h = h

    # 3-point O(h)
    def Forward (self, x):
        return (self.f(x + 2.0*self.h) - 2.0*self.f(x + self.h) + self.f(x))/self.h**2

    # 3-point O(h)
    def Backward (self, x):
        return (self.f(x - 2.0*self.h) - 2.0*self.f(x - self.h) + self.f(x))/self.h**2

    # 3-point O(h^2)
    def Central (self, x):
        return (self.f(x + self.h) - 2.0*self.f(x) + self.f(x - self.h))/self.h**2

class Trapezoidal ():
    def __init__ (self, f, a, b, n):
        self.f = f
        self.a = a
        self.b = b
        self.n = n
        self.h = (self.b - self.a)/self.n

    def Integral (self):
        s = 0.0
        for i in range(0, self.n):
            s += (self.f(self.a + i*self.h) + self.f(self.a + (i+1)*self.h))*self.h/2.0
        return s

class Simpson ():
    def __init__ (self, f, a, b, n):
        self.f = f
        self.a = a
        self.b = b
        if n%2 == 0:
            self.n = n
        else:
            self.n = n + 1
        self.h = (self.b - self.a)/self.n

    def Integral (self):
        s = 0.0
        for i in range(0, self.n, 2):
            s += ( self.f(self.a + i*self.h) +  4.0*self.f(self.a + (i+1)*self.h) +  self.f(self.a + (i+2)*self.h))*self.h/3.0
        return s

class GaussianQuadrature ():
    def __init__ (self, f, a, b, n, w, s):
        self.f = f
        self.a = a
        self.b = b
        self.n = n
        self.h = (self.b - self.a)/self.n

        assert len(w) == len(s), "Error in input arguments."
        self.w = []; self.s = []
        for i in range(len(w)):
            self.w.append(w[i])
            self.s.append(s[i])

    def Integral (self):
        s = 0.0
        for i in range(self.n):
            for j in range(len(self.w)):
                s += self.w[j]*self.f(self.a + 0.5*(2*i+1)*self.h + 0.5*self.h*self.s[j])*self.h/2.0
        return s

class Bisection():
    def __init__ (self, f, a, b, tol=1.0e-3):
        self.f = f
        self.a = a
        self.b = b
        self.tol = tol

        assert self.f(a)*self.f(b)<0, "Error in input arguments."

    def FindingRoot(self):
        a, b = self.a, self.b
        c = 0.5*(a + b)
        while abs(self.f(c)) > self.tol:
            if self.f(a)*self.f(c)>0:
                a = c
            elif self.f(a)*self.f(c)<0:
                b = c
            c = 0.5*(a + b)

        return c

class NewtonRaphson():
    def __init__ (self, f, fp, x0, tol=1.0e-3):
        self.f = f
        self.fp = fp
        self.x0 = x0
        self.tol = tol

    def FindingRoot(self):
        x0 = self.x0
        while abs(self.f(x0)) > self.tol:
            x0 = x0 - self.f(x0)/self.fp(x0)
        return x0


import json

from cachelib.simple import SimpleCache
from flask import (
    Blueprint,
    Response,
    redirect,
    render_template,
    request,
    url_for,
)

from resultsdb_frontend import app
from resultsdb_frontend.resultsdb_api import ResultsDBapi

CACHE = SimpleCache()
CACHE_TIMEOUT = 60
RDB_API = ResultsDBapi(app.config["RDB_URL"])

main = Blueprint("main", __name__)

@main.route("/")
@main.route("/index")
def index():
    return redirect(url_for("main.results"))

@main.route("/testcase_tokenizer")
def testcase_tokenizer():
    global CACHE

    cached = CACHE.get("tokenized_testcases")
    if cached is not None:
        return cached
    page = 0
    tc_names = []
    while True:
        names = [
            tc["name"] for tc in RDB_API.get_testcases(page=page, limit=100)["data"]
        ]
        page += 1
        tc_names.extend(names)
        if not names:
            break
    data = sorted(tc_names, key=lambda x: (x.count("."), x))

    response = Response(
        response=json.dumps(data), status=200, mimetype="application/json"
    )
    CACHE.set("tokenized_testcases", response, CACHE_TIMEOUT)
    return response

@main.route("/groups")
def groups():
    groups = RDB_API.get_groups(**dict(request.args))
    return render_template("groups.html", groups=groups)

@main.route("/groups/<group_id>")
def group(group_id):
    group = RDB_API.get_group(group_id)
    groups = dict(prev=None, next=None, data=[group])
    return render_template("groups.html", groups=groups)

@main.route("/results")
def results():
    args = dict(request.args)
    results = RDB_API.get_results(**args)
    for result in results["data"]:
        result["groups"] = (len(result["groups"]), ",".join(result["groups"]))
    return render_template("results.html", results=results)

@main.route("/results/<result_id>")
def result(result_id):
    result = RDB_API.get_result(id=result_id)
    try:
        result["groups"] = (len(result["groups"]), ",".join(result["groups"]))
    except KeyError:
        result["groups"] = (0, "")
    return render_template("result_detail.html", result=result)

@main.route("/testcases")
def testcases():
    args = dict(request.args)
    tcs = RDB_API.get_testcases(**args)
    return render_template("testcases.html", testcases=tcs)

@main.route("/testcases/<path:testcase_name>")
def testcase(testcase_name):
    tc = RDB_API.get_testcase(name=testcase_name)
    tcs = dict(prev=None, next=None, data=[tc])
    return render_template("testcases.html", testcases=tcs)


from typing import List

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        # With list comprehension
        lenn=len(nums)
        temp=[]
        for i in range(lenn):
            pos = lenn-k+i
            while pos<0:
                pos=pos+lenn
            if pos>lenn-1: pos=pos%lenn
            temp.append(nums[pos])
        for i in range(lenn):
            nums[i]=temp[i]

# # Example 1:
# nums = [1,2,3,4,5,6,7]
# k = 3
# # Output: [5,6,7,1,2,3,4]
# # Explanation:
# # rotate 1 steps to the right: [7,1,2,3,4,5,6]
# # rotate 2 steps to the right: [6,7,1,2,3,4,5]
# # rotate 3 steps to the right: [5,6,7,1,2,3,4]
# s = Solution()
# s.rotate(nums, k)
# print(nums)

# # Example 2:
# nums = [-1,-100,3,99]
# k = 2
# # Output: [3,99,-1,-100]
# # Explanation:
# # rotate 1 steps to the right: [99,-1,-100,3]
# # rotate 2 steps to the right: [3,99,-1,-100]
# s = Solution()
# s.rotate(nums, k)
# print(nums)

# Example 3:
nums = [1,2,3]
k = 4
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to the right: [99,-1,-100,3]
# rotate 2 steps to the right: [3,99,-1,-100]
s = Solution()
s.rotate(nums, k)
print(nums)

# Runtime
# Details
# 194ms
# Beats 34.80%of users with Python3
# Memory
# Details
# 27.66MB
# Beats 75.47%of users with Python3


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

from beem import Steem
from beem.comment import Comment
from beem.exceptions import ContentDoesNotExistsException

from steem.settings import STEEM_HOST
from steem.markdown import SteemMarkdown
from utils.logging.logger import logger

class SteemComment:

    def __init__(self, comment=None, author_perm=None, url=None):
        self.comment = comment
        self.author_perm = author_perm
        self.url = url

    def get_author_perm(self):
        if self.author_perm is None:
            self.author_perm = "/".join(self.url.split("/")[-2:])
        return self.author_perm

    def get_comment(self):
        if self.comment is None:
            self.comment = Comment(self.get_author_perm())
        return self.comment

    def get_url(self):
        if self.url is None:
            if self.author_perm:
                self.url = u"{}/{}".format(STEEM_HOST, self.author_perm)
            else:
                c = self.get_comment()
                if c.authorperm:
                    self.url = u"{}/{}".format(STEEM_HOST, c.authorperm)
                else:
                    self.url = u"{}/@{}/{}".format(STEEM_HOST, c.author, c.permlink)

        return self.url

    def get_pic_url(self, regex=False):
        body = self.get_comment().body
        return SteemMarkdown(body).get_top_image(regex)

    def get_text_body(self):
        body = self.get_comment().body
        return SteemMarkdown(body).get_rendered_text()

    def get_compatible_markdown(self):
        body = self.get_comment().body
        return SteemMarkdown(body).get_steem_markdown()

    def get_tags(self):
        c = self.get_comment()
        if c.json_metadata and 'tags' in c.json_metadata:
            return c.json_metadata['tags']
        else:
            self.refresh()
            c = self.get_comment()
            if c.json_metadata and 'tags' in c.json_metadata:
                return c.json_metadata['tags']
        return []

    def has_tag(self, tag):
        return tag in self.get_tags()

    def has_tags(self, tags):
        if not tags or len(tags) == 0:
            return False
        for tag in tags:
            if self.has_tag(tag):
                return True
        return False

    def refresh(self):
        c = self.get_comment()
        try:
            c.refresh()
        except ContentDoesNotExistsException:
            logger.info("Failed when refresh {} with title [{}], which is probably deleted.".format(self.get_url(), c.title))
            return None

        return c

    def log(self):
        c = self.get_comment()
        logger.info("@%s | %s | %s | %s" % (c.author, c.title, self.get_url(), c['created']))

    def is_commented_by(self, account):
        commented_by = [reply['author'] for reply in self.get_comment().get_replies()]
        return account in commented_by

    def is_upvoted_by(self, account):
        voters = self.get_comment().get_curation_rewards()['active_votes'].keys()
        return account in voters

    def is_downvoted_by(self, account):
        has_downvoted = False
        for vote in self.get_comment().get_votes():
            if vote.voter == account and vote.percent < 0:
                has_downvoted = True
        return has_downvoted

    def is_comment(self):
        c = self.get_comment()
        return c["parent_author"] != ''


from random import randint
from readchar import readkey
from readchar.key import CTRL_C

def clear():
    print("\x1bc")

clear()
print("Welcome to Hangman!")
print("Press enter to play")
readkey()

clear()

words=[
    "ready",
    "apple",
    "death",
    "five",
    "app",
    "seattle",
    "salty",
    "nord",
    "coffee"
]

word = words[randint(0, len(words) - 1)]
print("Guess the word\nReady?")

guess = 7
letters = {}

fail = False
while guess > 0:
    print ("You have", guess , "chances left")
    fail = False
    for c in word:
        if c in letters:
            print(c, end="")
        else:
            print("_", end="")
            fail = True

    print("")
    if not fail:
        clear()
        print("Congrates you win the game! The word was", word)
        print("Hit enter to exit hangman")
        readkey()
        exit()

    data = readkey()
    if data == CTRL_C:
        exit(0)

    if data in letters:
        print("Already guessed that letter.")
        guess = guess - 1

    letters[data] = True

    if data not in word:
        guess = guess - 1

if fail:
    clear()
    print("You've failed :(")
    print("The word was", word + ".")


import math

def CASE(in1):
    X, R, C = map(int, in1.split())
    #print X, R, C
    rc = R * C
    result = "RICHARD"
    if X == 4:
        if (R >= 3) and (C >= 3) and (rc % 4 == 0):
            result =  "GABRIEL"
        else:
            result = "RICHARD"
    elif X == 3:
        if (R >= 2) and (C >= 2) and (rc % 3 == 0):
            result =  "GABRIEL"
        else:
            result = "RICHARD"
    else:
        if rc >= 1 and (rc % X == 0):
            result =  "GABRIEL"
        else:
            result = "RICHARD"
    return result
def RUN(IN, OUT):
    t = int(IN.readline().strip())
    for i in xrange(1, t + 1):
        in1 = IN.readline().strip()
        OUT.write("Case #%i: %s\n" % (i, CASE(in1)))

if __name__ == "__main__":
    import sys
    RUN(sys.stdin, sys.stdout)


# Problem Set 2, hangman.py
# Name: Matt Rieke
# Collaborators:
# Time spent: 6 Hours

# Hangman Game
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string

WORDLIST_FILENAME = "words.txt"

def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def choose_word(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code

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

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = load_words()

def is_word_guessed(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing; assumes all letters are
      lowercase
    letters_guessed: list (of letters), which letters have been guessed so far;
      assumes that all letters are lowercase
    returns: boolean, True if all the letters of secret_word are in letters_guessed;
      False otherwise
    '''
    word_guess = False
    letter_match = False
    n = 0

    for schar in secret_word:
        n += 1
        for lchar in letters_guessed:
            if lchar == schar:
                letter_match = True
                break
        if letter_match == True and n == len(secret_word):
            word_guess = True
            break
        elif letter_match == True:
            letter_match = False
            continue
        else:
            break
    return word_guess

def get_guessed_word(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string, comprised of letters, underscores (_), and spaces that represents
      which letters in secret_word have been guessed so far.
    '''
    word_guess = ''
    letter_match = False

    for schar in secret_word:
        for lchar in letters_guessed:
            if lchar == schar:
                letter_match = True
                break
        if letter_match == True:
            word_guess = word_guess + lchar
            letter_match = False
        else:
            word_guess = word_guess + '_ '
    return word_guess

def get_available_letters(letters_guessed):
    '''
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string (of letters), comprised of letters that represents which letters have not
      yet been guessed.
    '''
    all_letters = string.ascii_lowercase
    available_letters = []
    available_string = ''

    for all_char in all_letters:
        letter_available = True
        for val in letters_guessed:
            if val == all_char:
                letter_available = False
                break
        if letter_available == True:
            available_letters.append(all_char)
    for ava_char in available_letters:
        available_string = available_string + ava_char
    return available_string

def letter_already_guessed(current_guess, letters_guessed):
    '''
    current_guess : String
        length of one, alpha only, current user guess
    letters_guessed : List
        list of strings, length one items, alpha only
    returns : boolean True if already guess or False if not already guessed
    '''
    for val in letters_guessed:
        if val == current_guess:
            return True
    return False

def is_in_word(current_guess, secret_word):
    '''
    current_guess : String
        length of one, alpha only, current user guess
    secret_word : String
        randomly selected word, alpha only, any length
    returns: boolean True if in word, boolean False if not in word
    '''
    for char in secret_word:
        if char == current_guess:
            return True
    return False

def hangman(secret_word):
    '''
    secret_word: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many
      letters the secret_word contains and how many guesses s/he starts with.

    * The user should start with 6 guesses

    * Before each round, you should display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.

    * Ask the user to supply one guess per round. Remember to make
      sure that the user puts in a letter!

    * The user should receive feedback immediately after each guess
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the
      partially guessed word so far.

    Follows the other limitations detailed in the problem write-up.
    '''
    print('\nWelcome to the game of Hangman!')
    #secret_word = choose_word(wordlist)
    #secret_word = 'hamburger'
    warning_count = 3
    guess_count = 6
    print('I am thinking of a word that is', len(secret_word), 'letters long.')
    print('\n------------\n')
    letters_guessed = []
    while guess_count > 0 and is_word_guessed(secret_word,letters_guessed) != True:
        print('You have', guess_count, 'guesses left.')
        print('Available letters:', get_available_letters(letters_guessed))
        current_guess = input('Please guess a letter: ')
        if current_guess.isalpha() == False:
            if warning_count > 0:
                warning_count -= 1
                print('Oops! That is not a valid letter. You have', warning_count, 'warnings left.')
                print('\n------------\n',)
                continue
            else:
                guess_count -= 1
                print('Oops! That is not a valid letter. You have', guess_count, 'guesses left.')
                print('\n------------\n',)
                continue
        else:
            current_guess = current_guess.lower()
            already_guessed = letter_already_guessed(current_guess, letters_guessed)
            if already_guessed == True:
                if warning_count > 0:
                    warning_count -= 1
                    print("Oops! You've already guessed that letter. You have", warning_count, 'warnings left.\n' + get_guessed_word(secret_word, letters_guessed))
                    print('\n------------\n',)
                    continue
                else:
                    guess_count -= 1
                    print("Oops! You've already guessed that letter. You have", guess_count, 'guesses left.\n' + get_guessed_word(secret_word, letters_guessed))
                    print('\n------------\n',)
                    continue
            else:
                letters_guessed.append(current_guess)
        in_word = is_in_word(current_guess, secret_word)
        if in_word == True:
            print('Good guess:', get_guessed_word(secret_word, letters_guessed))
            print('\n------------\n',)
            continue
        else:
            if current_guess in ['a','e','i','o','u']:
                guess_count -= 2
                print('Oops! That letter is not in my word:', get_guessed_word(secret_word, letters_guessed))
                print('\n------------\n',)
                continue
            else:
                guess_count -= 1
                print('Oops! That letter is not in my word:', get_guessed_word(secret_word, letters_guessed))
                print('\n------------\n',)
                continue
    if guess_count <= 0:
        print('Sorry you ran out of guesses. The word was', secret_word + '.')
    else:
        print('Congratulations, you won!')
        print('Your total score for this game is:', guess_count*len(secret_word))

    # FILL IN YOUR CODE HERE AND DELETE "pass"

# When you've completed your hangman function, scroll down to the bottom
# of the file and uncomment the first two lines to test
#(hint: you might want to pick your own
# secret_word while you're doing your own testing)

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

def match_with_gaps(my_word, other_word):
    '''
    my_word: string with _ characters, current guess of secret word
    other_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the
        corresponding letters of other_word, or the letter is the special symbol
        _ , and my_word and other_word are of the same length;
        False otherwise:
    '''
    my_word = my_word.replace(' ', '')
    match_word = True
    correct_guess = []
    if len(my_word) != len(other_word):
        match_word = False
        #print('not same length')
        return match_word
    for letter in my_word:
        if letter.isalpha() == True:
            if letter in correct_guess:
                continue
            else:
                correct_guess.append(letter)
    for item in correct_guess:
        for place in range(len(my_word)):
            if other_word[place] == item and my_word[place] != item:
                match_word = False
                #print('not my word')
                return match_word
            if other_word[place] != item and my_word[place] == item:
                match_word = False
                #print('not other word')
                return match_word
    return match_word
    # FILL IN YOUR CODE HERE AND DELETE "pass"

def show_possible_matches(my_word):
    '''
    my_word: string with _ characters, current guess of secret word
    returns: nothing, but should print out every word in wordlist that matches my_word
             Keep in mind that in hangman when a letter is guessed, all the positions
             at which that letter occurs in the secret word are revealed.
             Therefore, the hidden letter(_ ) cannot be one of the letters in the word
             that has already been revealed.

    '''
    match_list = []
    match_string = ''
    for other_word in wordlist:
        if match_with_gaps(my_word, other_word) == True:
            match_list.append(other_word)
    if len(match_list) > 0:
        for item in match_list:
            match_string = match_string + ' ' + item
            match_string = match_string.lstrip()
        return match_string
    else:
        return 'No matches found'

def hangman_with_hints(secret_word):
    '''
    secret_word: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many
      letters the secret_word contains and how many guesses s/he starts with.

    * The user should start with 6 guesses

    * Before each round, you should display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.

    * Ask the user to supply one guess per round. Make sure to check that the user guesses a letter

    * The user should receive feedback immediately after each guess
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the
      partially guessed word so far.

    * If the guess is the symbol *, print out all words in wordlist that
      matches the current guessed word.

    Follows the other limitations detailed in the problem write-up.
    '''
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    print('\nWelcome to the game of Hangman!')
    #secret_word = choose_word(wordlist)
    #secret_word = 'hamburger'
    warning_count = 3
    guess_count = 6
    print('I am thinking of a word that is', len(secret_word), 'letters long.')
    print('\n------------\n')
    letters_guessed = []
    while guess_count > 0 and is_word_guessed(secret_word,letters_guessed) != True:
        print('You have', guess_count, 'guesses left.')
        print('Available letters:', get_available_letters(letters_guessed))
        current_guess = input('Please guess a letter: ')
        if current_guess == '*':
            print('Possible word matches are:')
            print(show_possible_matches(get_guessed_word(secret_word, letters_guessed)))
            continue
        elif current_guess.isalpha() == False:
            if warning_count > 0:
                warning_count -= 1
                print('Oops! That is not a valid letter. You have', warning_count, 'warnings left.')
                print('\n------------\n',)
                continue
            else:
                guess_count -= 1
                print('Oops! That is not a valid letter. You have', guess_count, 'guesses left.')
                print('\n------------\n',)
                continue
        else:
            current_guess = current_guess.lower()
            already_guessed = letter_already_guessed(current_guess, letters_guessed)
            if already_guessed == True:
                if warning_count > 0:
                    warning_count -= 1
                    print("Oops! You've already guessed that letter. You have", warning_count, 'warnings left.\n' + get_guessed_word(secret_word, letters_guessed))
                    print('\n------------\n',)
                    continue
                else:
                    guess_count -= 1
                    print("Oops! You've already guessed that letter. You have", guess_count, 'guesses left.\n' + get_guessed_word(secret_word, letters_guessed))
                    print('\n------------\n',)
                    continue
            else:
                letters_guessed.append(current_guess)
        in_word = is_in_word(current_guess, secret_word)
        if in_word == True:
            print('Good guess:', get_guessed_word(secret_word, letters_guessed))
            print('\n------------\n',)
            continue
        else:
            if current_guess in ['a','e','i','o','u']:
                guess_count -= 2
                print('Oops! That letter is not in my word:', get_guessed_word(secret_word, letters_guessed))
                print('\n------------\n',)
                continue
            else:
                guess_count -= 1
                print('Oops! That letter is not in my word:', get_guessed_word(secret_word, letters_guessed))
                print('\n------------\n',)
                continue
    if guess_count <= 0:
        print('Sorry you ran out of guesses. The word was', secret_word + '.')
    else:
        print('Congratulations, you won!')
        print('Your total score for this game is:', guess_count*len(secret_word))

# When you've completed your hangman_with_hint function, comment the two similar
# lines above that were used to run the hangman function, and then uncomment
# these two lines and run this file to test!
# Hint: You might want to pick your own secret_word while you're testing.

if __name__ == "__main__":
    # pass

    # To test part 2, comment out the pass line above and
    # uncomment the following two lines.

    #secret_word = choose_word(wordlist)
    #hangman(secret_word)

###############

    # To test part 3 re-comment out the above lines and
    # uncomment the following two lines.

    secret_word = choose_word(wordlist)
    hangman_with_hints(secret_word)

6.0001 Introduction to Computer Science and Programming/Problem Set 2/ps2.py


import numpy as np
from numpy import linalg as LA
from scipy import optimize

if __name__ == '__main__':

    def rhs(X, A, alpha):
        return (1 - alpha) * X + alpha / np.sum(X) * np.dot(A, X)

    m = 10  # number of agents
    # A = np.identity(m)  # grade matrix, shape m x m
    A = np.full((m, m), 0.8)
    alpha = 0.1  # convergence parameter

    X0 = np.dot(A, np.full(m, 1/m))
    X = optimize.fixed_point(rhs, X0, args=(A, alpha))
    print(X)

    w, v = LA.eig(A)
    # A.X = np.sum(X)*X


class Node:

    def __init__(self):
        self.end = 0
        self.child = {}

class Trie:

    def __init__(self):

        self.root = Node()

    def insert(self, word: str) -> None:

        root = self.root
        for ch in word:
            if (ch not in root.child):
                root.child[ch] = Node()

            root = root.child[ch]

        root.end = 1

    def search(self, word: str) -> bool:

        root = self.root
        for ch in word:
            if (ch not in root.child):
                return False

            root = root.child[ch]

        return (root.end == 1)

    def startsWith(self, prefix: str) -> bool:

        root = self.root

        for ch in prefix:
            if(ch not in root.child):
                return False
            root = root.child[ch]

        return True

# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)


# # scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100"
# #
# # a_scores = int()
# #
# # individual = scores.split(" ")
# # print(individual)
# #
# # for i in individual:
# #     i = int(i)
# #     if i >= 90:
# #         a_scores+=1
# #
# # print(a_scores)
# #_------------
#
#
# stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', "The"]
# org = "The organization for health, safety, and education"
# acro = str()
# list1 = org.split(" ")
# print(list1)
#
# for i in list1:
#     #print(i)
#     if i in stopwords:
#         continue
#     else:
#         print(i)
#         print(i[0].upper())
#         acro += i[0].upper()
#
# print(acro)
#------------------------------

# stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', 'The']
# sent = "The water earth and air are vital"
# acro = str()
# list1 = sent.split(" ")
# print(list1)
# for i in list1:
#     if i in stopwords:
#         continue
#     else:
#         print(i[0].upper()+i[1].upper()+".")
#         acro+=i[0].upper()+i[1].upper()+". "
#
# acro = acro[0:-2]
# print(acro)

#------------------------
#expected result --> was I tac a ro rac a ti saw
#
# p_phrase = "was it a car or a cat I saw"
# r_phrase = p_phrase[::-1]
#
# print(r_phrase)
#----------------------------------------

inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"]
#first --> item
#second--> how much in stock
#third---> how much it costs
#For example, the first print statment should read The store has 12 shoes, each for 29.99 USD

for i in inventory:
    #print(i)
    a = i.split(", ")
    #print(a)
    print("The store has {} {}, each for {} USD.".format(a[1],a[0],a[2]))


"""
grid_search.py: Do grid search on a model.
Currently implemented only for CNN_GRU on SMR
"""

import os
import argparse
# import models
# import loaders
import numpy as np
from models import CNN_GRU_Model, CNN_Only_Model, EEGNet_model
from loaders import DataLoader
from sklearn.model_selection import GridSearchCV

if __name__ == '__main__':
    os.environ["CUDA_VISIBLE_DEVICES"]="0"
    param_grid = [
            {'num_gru': [2**i for i in range(5,7)],
             'pool1D': [False],
             'has2D': [False],
             'pool2D': [False],
             'poolAvg': [True]},
            {'num_gru': [2**i for i in range(5,7)],
             'pool1D': [True],
             'has2D': [False],
             'pool2D': [False],
             'poolAvg': [True, False]},
            {'num_gru': [32,150],#2**i for i in range(5,7)],
             'pool1D': [True, False],
             'has2D': [True],
             'pool2D': [True,False],
             'poolAvg': [True, False]}
        ]

    loader = DataLoader()
    list_splits = []
    X = []
    X_t = []
    Y = []
    Y_t = []
    train_size = 0
    for i in range(1):
        d = loader.get_smr(subject=i, return_idx=True)
        data = d['data']
        X.append(data[0])
        X_t.append(data[2])
        Y.append(data[1])
        Y_t.append(data[3])
        list_splits.append(d['data_idx'])
        train_size+=data[0].shape[0]

    list_splits = [[i[0], i[1] + train_size] for i in list_splits]
    list_splits = [[np.append(i[0], i[1], axis=0), i[1]] for i in list_splits]

    X = np.concatenate(X, axis=0)
    X_t = np.concatenate(X_t, axis=0)
    X = np.append(X, X_t, axis=0)
    Y = np.concatenate(Y, axis=0)
    Y_t = np.concatenate(Y_t, axis=0)
    Y = np.append(Y, Y_t, axis=0)

    model = CNN_GRU_Model()
    model.suffix = 'SMR_GridSearch'
    model.num_classes = 4
    model.num_epochs=27
    #scorer = make_scorer
    clf = GridSearchCV(model, param_grid, cv = list_splits,
            scoring=None, verbose=4, refit=False)#, n_jobs=3, pre_dispatch='n_jobs')

    clf.fit(X, Y)
    exit(0)

    #TODO: Will do generalisation later
    parser = argparse.ArgumentParser(
        description='Grid Search a model on a dataset(s)'
    )
    parser.add_argument('--data', type=str, default='SMR',
                        help='Dataset to use. SEED, SMR, BrainMNIST, '
                             'ThoughtViz or ALL')
    #parser.add_argument('--retrain', action='store_true',
    #                    help='Retrain the model(s) on the dataset(s)')
    parser.add_argument('--model', type=str, default='CNN_GRU',
                        help='Model to use. CNN, CNN_GRU, EEG_Net, AE or All')
    parser.add_argument('--run_id', type=int, default=-1,
                        help='run ID to use if retraining. Default -1 (timestamp)')
    parser.add_argument('--epochs', type=int, default=100,
                        help='Epochs to use if retraining. Default 100')
    args = parser.parse_args()
    loader = DataLoader()
    datasets_dict = {
        'SEED': loader.get_seed,
        'SMR': lambda validation=False, subject=2: loader.get_smr(subject, validation),     # noqa
        'BMNIST': loader.get_bmnist11,
        'ThoughtViz': loader.get_thoughtviz
    }

    models_dict = {
        'CNN': CNN_Only_Model,
        'CNN_GRU': CNN_GRU_Model,
        'EEG_Net': EEGNet_model
        # AE
    }

    if args.data == 'ALL':
        datasets = [[k, datasets_dict[k]] for k in datasets_dict]
    else:
        datasets = [[args.data, datasets_dict[args.data]]]

    if args.model == 'all':
        models = [[k, models_dict[k]] for k in models_dict]
    else:
        models = [[args.model, models_dict[args.model]]]
    for model_name, Model in models:
        model = Model()
        print('Model', model_name)
        for dataset_name, loader_2 in datasets:
            print('Dataset', dataset_name)
            if not args.retrain:
                """Evaluate saved the saved model(s)"""
                model.load_model_and_evaluate(loader_2, 1)
            else:
                """Train Model and print Evaluations"""
                model.train(loader_2, args.run_id, num_epochs=args.epochs)


from math import sqrt, gcd

def is_square(n):
    root = sqrt(n)
    return int(root) == root

# returns sequence of first 100 numbers
def continued_fraction(n):
    m = 0
    d = 1
    a0 = int(sqrt(n))
    a = a0
    sequence = [a]
    for _ in range(1000):
        m = d * a - m
        d = (n - m*m)/d
        a = int((a0 + m)/d)
        sequence.append(a)
    return sequence

# returns fraction from a sequence
def to_fraction(sequence):
    last = [1, sequence[-1]]
    sequence.pop(-1)
    count = 0
    for i in reversed(sequence):
        last[0] = i * last[1] + last[0]
        last[0], last[1] = last[1], last[0]
        count += 1
    divisor = 0
    while divisor != 1:
        divisor = gcd(last[0], last[1])
        last = [last[0]//divisor, last[1]//divisor]
    return  [last[1], last[0]]

max_x = 0
max_index = 0
for D in range(2,1000):
    if not is_square(D):
        con = continued_fraction(D)
        for j in range(1, len(con)):
            frac = to_fraction(con[:j])
            # frac[0] = x, frac[1] = y
            if frac[0]*frac[0] - D * frac[1]*frac[1] == 1:
                if frac[0] > max_x:
                    max_x = frac[0]
                    max_index = D
                break
print(max_index)


"""
LeetCode: https://leetcode.com/problems/maximum-binary-tree
"""

def constructMaximumBinaryTree(nums: List[int]):
    if not nums:
        return None
    m = max(nums)
    mi = nums.index(m)
    left = nums[:mi]
    right = nums[(mi + 1) :]
    return TreeNode(
        val=m,
        left=constructMaximumBinaryTree(left),
        right=constructMaximumBinaryTree(right),
    )


from block import Block
from settings import *

class Tetromino:
    def __init__(self, shape, group, create_new_tetromino, field_data):

        # setup
        self.shape = shape
        self.block_positions = TETROMINOES[shape]['shape']
        self.color = TETROMINOES[shape]['color']
        self.create_new_tetromino = create_new_tetromino
        self.field_data = field_data

        # create blocks
        self.blocks = [Block(group, pos, self.color)
                       for pos in self.block_positions]

    # collisions
    def next_move_horizontal_collide(self, blocks, amount):
        collision_list = [block.horizontal_collide(
            int(block.pos.x + amount), self.field_data) for block in self.blocks]
        return True if any(collision_list) else False

    def next_move_vertical_collide(self, blocks, amount):
        collision_list = [block.vertical_collide(
            int(block.pos.y + amount), self.field_data) for block in self.blocks]
        return True if any(collision_list) else False

    # movement
    def move_horizontal(self, amount):
        if not self.next_move_horizontal_collide(self.blocks, amount):
            for block in self.blocks:
                block.pos.x += amount

    def move_down(self):
        if not self.next_move_vertical_collide(self.blocks, 1):
            for block in self.blocks:
                block.pos.y += 1
        else:
            for block in self.blocks:
                self.field_data[int(block.pos.y)][int(block.pos.x)] = block
            self.create_new_tetromino()

    # rotate
    def rotate(self):
        if self.shape != 'O':

            # 1. pivot point
            pivot_pos = self.blocks[0].pos

            # 2. new block positions
            new_block_positions = [
                block.rotate(pivot_pos) for block in self.blocks]

            # 3. collision check
            for pos in new_block_positions:
                # horizontal
                if pos.x < 0 or pos.x >= COLUMNS:
                    return

                # field check -> collision with other pieces
                if self.field_data[int(pos.y)][int(pos.x)]:
                    return

                # vertical / floor check
                if pos.y > ROWS:
                    return

            # 4. implement new positions
            for i, block in enumerate(self.blocks):
                block.pos = new_block_positions[i]

Net Ninja/Build a Tetris Clone with Pygame/tetromino.py


"""
iconwiki.py
A very very simple Wiki with icon editor

@author: Tobias Thelen
@contact: tobias.thelen@uni-osnabrueck.de
@licence: public domain
@status: completed
@version: 1 (10/2018)
"""
import re
import os

from server import webserver
from server.apps.static import StaticApp
from server.middlewares.session import SessionMiddleware
from server.middlewares.basic_auth import BasicAuthMiddleware
from server.webserver import StopProcessing

class NoSuchPageError(Exception):
    """Raise if try to access non existant wiki page."""
    pass

class WikiApp(webserver.App):
    """
    Webanwendung zum kollaborativen Schreiben (wiki).

    Diese sehr einfache Anwendung demonstriert ein simples Wiki.
    """

    def register_routes(self):
        self.add_route("", self.show)
        self.add_route("show(/(?P<pagename>\w+))?", self.show)
        self.add_route("edit/(?P<pagename>\w+)", self.edit)
        self.add_route("save/(?P<pagename>\w+)", self.save)

    def pagelist(self):
        print([x for x in os.listdir("data/wikipages")])
        return [self.get_page_icon(x) for x in os.listdir("data/wikipages")]

    def read_page(self, pagename):
        """Read wiki page from data directory or raise NoSuchPageError."""

        try:
            with open("data/wikipages/"+pagename, "r", encoding="utf-8", newline='') as f:
                x = f.read()
                return x
        except IOError:
            raise NoSuchPageError

    def get_page_icon(self, pagename):
        icon = {'data': '', 'title': '', 'pagename': pagename}
        try:
            with open("data/wikipage_icons/"+pagename, "r", encoding="utf-8", newline='') as f:
                icon_name = f.read()
        except FileNotFoundError:
            return icon
        try:
            with open("data/icons/" + icon_name, "r", encoding="utf-8", newline='') as f:
                data = f.read()
            return {'data': data, 'title': icon_name, 'pagename': pagename}
        except FileNotFoundError:
            return {'data': '', 'title': icon_name, 'pagename': pagename}

    def save_page_icon(self, pagename, icon_name):
        f = open("data/wikipage_icons/" + pagename, "w", encoding='utf-8', newline='')
        f.write(icon_name)
        f.close()

    def markup(self, text):
        """Substitute wiki markup in text with html."""

        text = re.sub(r"<",
                      r"<",
                      text)

        # substitute links: [[pagename]] -> pagename
        text = re.sub(r"\[\[([a-zA-Z0-9]+?)\]\]",
                      r"\1",
                      text)

        # substitute headlines: !bang ->
bang

        text = re.sub(r"^!(.*)$", r"
\1
", text, 0, re.MULTILINE)

        # replace two ends of line with

        text = re.sub(r"\r?\n\r?\n", r"
", text)

        # replace one end of line with

        text = re.sub(r"\r?\n\r?\n", r"
", text)

        return text

    def show(self, request, response, pathmatch=None):
        """Evaluate request and construct response."""

        try:
            pagename = pathmatch.group('pagename') or "main"
        except IndexError:
            pagename = "main"  # default pagename

        try:
            text = self.read_page(pagename)
            icon = self.get_page_icon(pagename)
        except NoSuchPageError:
            # redirect to edit view if page does not exist
            response.send_redirect("/edit/" + pagename)
            return

        # page history in session:
        # - history is stored in session under key 'page_history'

        # if key is not present, init with empty list
        try:
            page_history = request.session['page_history']
        except KeyError:
            request.session['page_history'] = page_history = []
        # show page
        response.send_template('wiki/show.tmpl', {'text': self.markup(text),
                                                  'pagename': pagename,
                                                  'icon': icon,
                                                  'pagelist':self.pagelist(),
                                                  'page_history': page_history})

        # add current page after generating page
        # put current page in front of page history and limit length to 3
        request.session['page_history'] = [pagename] + request.session['page_history'][:2]

    def edit(self, request, response, pathmatch=None):
        """Display wiki page for editing."""

        try:
            pagename = pathmatch.group('pagename') or "main"
        except IndexError:
            pagename = "main"

        try:
            text = self.read_page(pagename)
        except NoSuchPageError:
            # use default text if page does not yet exist
            text = "This page is still empty. Fill it."

        icon_list = os.listdir("data/icons")
        icons = []
        for icon_title in icon_list:
            with open("data/icons/"+icon_title, "r") as f:
                icons.append({'data': f.read(), 'title': icon_title})

        page_icon = self.get_page_icon(pagename)

        # fill template and show
        response.send_template('wiki/edit.tmpl', {'text': text,
                                                  'pagename': pagename,
                                                  'pagelist': self.pagelist(),
                                                  'page_icon': page_icon,
                                                  'icons': icons})

    def save(self, request, response, pathmatch=None):
        """Evaluate request and construct response."""

        try:
            pagename = pathmatch.group('pagename')
        except IndexError:
            # no pagename given: error
            response.send_template("wiki/wikierror.html",
                                   {'error': 'No pagename given.', 'text': 'save action needs pagename'},
                                   code=500)
            return

        try:
            wikitext = request.params['wikitext']
        except KeyError:
            # no text given: error
            response.send_template("wiki/wikierror.html",
                                   {'error': 'No wikitext given.', 'text': 'save action needs wikitext'},
                                   code=500)
            return

        # ok, save text
        f = open("data/wikipages/" + pagename, "w", encoding='utf-8', newline='')
        f.write(wikitext)
        f.close()

        # if we have an icon parameter and it's properly formed, save it
        if 'icon' in request.params and re.match(r'^[a-zA-Z0-9]+$', request.params['icon']):
            self.save_page_icon(pagename, request.params['icon'])

        response.send_redirect("/show/"+pagename)

class IconEditorApp(webserver.App):

    def register_routes(self):
        self.add_route("$", self.show)
        self.add_route("save$", self.save)

    def show(self, request, response, pathmatch):
        """Show the editor. Provide list of saved icons."""

        icon_list = os.listdir("data/icons")
        icons = []
        for icon_title in icon_list:
            with open("data/icons/"+icon_title, "r") as f:
                icons.append({'data': f.read(), 'title': icon_title})
        response.send_template("iconeditor.tmpl", {'icons': icons})

    def save(self, request, response, pathmatch):
        """Save base64-encoded representation of icon pixels to a file."""

        if 'title' not in request.params or \
                not re.match(r"^[a-zA-Z0-9]+$", request.params['title']) or \
                'icon' not in request.params or \
                not request.params['icon'].startswith('data:'):
            raise StopProcessing(500, "Invalid parameters")
        else:
            with open("data/icons/"+request.params['title'], "w") as f:
                f.write(request.params['icon'])
        response.send_redirect('/'+self.prefix+'/')

class HelpApp(webserver.App):

    def register_routes(self):
        self.add_route("/", self.help)

    def help(self, request, response, pathmatch):
        response.send_template('help.tmpl')

if __name__ == '__main__':
    s = webserver.Webserver()
    s.set_templating("jinja2")
    s.add_app(HelpApp(prefix='help'))
    s.add_app(IconEditorApp(prefix='iconeditor'))
    s.add_app(StaticApp(prefix='static', path='static'))
    s.add_app(WikiApp(prefix=''))
    s.add_middleware(SessionMiddleware())
    s.add_middleware(BasicAuthMiddleware({'user': 'pass'}))
    s.serve()