#!/usr/bin/env python
# -*- coding:Utf-8 -*-

from sulci.validators import KeyEntityValidator

from sulci_cli import SulciBaseCommand

class Command(SulciBaseCommand):
    """
    Sulci command for training the algoritms.
    """
    help = __doc__

    def define_args(self):
        super(Command, self).define_args()
        self.parser.add_argument(
            "-K",
            "--kev",
            action="store_true",
            dest="keyentities",
            help="Control the KeyEntity"
        )

    def handle(self, *args, **options):
        if self.KEYENTITIES:
            V = KeyEntityValidator()
            V.do()
        if self.IPDB:
            import ipdb
            ipdb.set_trace()

if __name__ == '__main__':
    command = Command()
    command.handle()


import os
import math
import json
import random
from io import BytesIO

import torch
import numpy as np
from torchvision.datasets.vision import VisionDataset
from PIL import Image

from pretrain.utils.distributed import get_rank, get_world_size

class CocoDataset(VisionDataset):
    def __init__(
        self,
        root,
        annFile,
        num_replicas=None,
        rank=None,
        transform=None,
        target_transform=None,
        transforms=None,
        cache_mode=False,
        cache_first=False,
    ):
        super(CocoDataset, self).__init__(root, transforms, transform, target_transform)
        from pycocotools.coco import COCO

        if num_replicas is None:
            num_replicas = get_world_size()
        if rank is None:
            rank = get_rank()

        self.coco_api = COCO(annFile)
        self.ids = list(sorted(self.coco_api.imgs.keys()))
        self.cache_mode = cache_mode
        self.rank = rank
        self.num_replicas = num_replicas
        self.num_samples = int(math.ceil(len(self.ids) * 1.0 / self.num_replicas))
        self.total_size = self.num_samples * self.num_replicas
        if cache_mode:
            self.cache = {}
            if cache_first:
                self.cache_images()

    def cache_images(self):
        indices = torch.arange(len(self.ids)).tolist()
        indices += indices[: (self.total_size - len(indices))]
        assert len(indices) == self.total_size

        offset = self.num_samples * self.rank
        indices = set(indices[offset : offset + self.num_samples])

        self.cache = {}
        for index, img_id in enumerate(self.ids):
            if index not in indices:
                continue

            path = self.coco_api.loadImgs(img_id)[0]["file_name"]
            with open(os.path.join(self.root, path), "rb") as f:
                self.cache[path] = f.read()

    def get_image(self, path):
        if self.cache_mode:
            if path not in self.cache:
                with open(os.path.join(self.root, path), "rb") as f:
                    self.cache[path] = f.read()

            return Image.open(BytesIO(self.cache[path])).convert("RGB")

        return Image.open(os.path.join(self.root, path)).convert("RGB")

    def __getitem__(self, index):
        raise NotImplementedError

    def __len__(self):
        return len(self.ids)

class CocoDetection(CocoDataset):
    def __init__(
        self,
        root,
        annFile,
        num_replicas=None,
        rank=None,
        transform=None,
        target_transform=None,
        transforms=None,
        cache_mode=False,
        cache_first=False,
    ):
        super(CocoDetection, self).__init__(
            root,
            annFile,
            num_replicas=num_replicas,
            rank=rank,
            transform=transform,
            target_transform=target_transform,
            transforms=transforms,
            cache_mode=cache_mode,
            cache_first=cache_first,
        )

    def __getitem__(self, index):
        """
        Args:
            index (int): Index
        Returns:
            tuple: Tuple (image, target). target is the object returned ``coco.loadAnns``,
        """
        coco_api = self.coco_api
        img_id = self.ids[index]
        ann_ids = coco_api.getAnnIds(imgIds=img_id)
        target = coco_api.loadAnns(ann_ids)

        path = coco_api.loadImgs(img_id)[0]["file_name"]

        img = self.get_image(path)
        if self.transforms is not None:
            img, target = self.transforms(img, target)

        return img, target

class CocoMask(CocoDataset):
    def __init__(
        self,
        root,
        maskFolder,
        annFile,
        num_replicas=None,
        rank=None,
        transform=None,
        target_transform=None,
        transforms=None,
        cache_mode=False,
        cache_first=False,
        mask_type=None,
    ):
        super(CocoMask, self).__init__(
            root,
            annFile,
            num_replicas=num_replicas,
            rank=rank,
            transform=transform,
            target_transform=target_transform,
            transforms=transforms,
            cache_mode=cache_mode,
            cache_first=cache_first,
        )
        assert mask_type in ("fh", None)
        self.mask_type = mask_type
        self.maskFolder = maskFolder

    def __getitem__(self, index):
        """
        Args:
            index (int): Index
        Returns:
            tuple: Tuple (image, masks).
        """
        coco_api = self.coco_api
        img_id = self.ids[index]
        path = coco_api.loadImgs(img_id)[0]["file_name"]
        img = self.get_image(path)
        if self.mask_type == "fh":
            mask_path = path.replace("jpg", "npy")
            masks = np.load(os.path.join(self.maskFolder, mask_path))
            masks = torch.from_numpy(masks)
        else:
            masks = None

        return img, masks

class CocoCaption(CocoDataset):
    def __init__(
        self,
        root,
        annFile,
        num_replicas=None,
        rank=None,
        transform=None,
        target_transform=None,
        transforms=None,
        cache_mode=False,
        cache_first=False,
    ):
        super(CocoDetection, self).__init__(
            root,
            annFile,
            num_replicas=num_replicas,
            rank=rank,
            transform=transform,
            target_transform=target_transform,
            transforms=transforms,
            cache_mode=cache_mode,
            cache_first=cache_first,
        )

        with open(annFile, "r") as f:
            self.coco = json.load(f)

        # sort 'images' field so that they are aligned with 'annotations'
        # i.e., in alphabetical order
        self.coco["images"] = sorted(self.coco["images"], key=lambda x: x["id"])
        # sanity check
        if "annotations" in self.coco:
            for img, ann in zip(self.coco["images"], self.coco["annotations"]):
                assert img["file_name"][:-4] == ann["file_name"][:-4]
        assert tuple(map(lambda x: x["id"], self.coco["images"])) == tuple(self.ids)

    def __getitem__(self, index):
        ann_info = (
            self.coco["annotations"][index]
            if "annotations" in self.coco
            else self.coco["images"][index]
        )

        img_path = os.path.join(self.root, ann_info["file_name"]).replace(
            ".png", ".jpg"
        )

        img = self.get_image(img_path)
        w, h = img.size

        target = {}
        target["image_id"] = torch.tensor(
            [ann_info["image_id"] if "image_id" in ann_info else ann_info["id"]]
        )

        target["size"] = torch.as_tensor([int(h), int(w)])
        target["orig_size"] = torch.as_tensor([int(h), int(w)])

        if "captions" in ann_info:
            target["captions"] = ann_info["captions"]

        if self.transforms is not None:
            img, target = self.transforms(img, target)

        return img, target


#!/usr/bin/env python

# Province/State,Country/Region,Lat,Long,1/22/20,1/23/20,...

from datetime import datetime
import json
import sys

import pycountry
import xlrd
import pytz

cases_abs = {}
cases_rel = {}
cases_grw = {}

deaths_abs = {}
deaths_rel = {}
deaths_grw = {}

country_overrides = {
    "JPG11668": "Diamond Princess",
    "CD": "Democratic Republic of the Congo",
    "VA": "Holy See",
    "IR": "Iran",
    "PS": "Palestine",
    "RU": "Russia",
    "KR": "South Korea",
}

def row_to_iso_date(row):
    date = datetime(int(row[3].value), int(row[2].value), int(row[1].value), 10, 0, 0, 0)
    tz_date = pytz.timezone("Europe/Brussels").localize(date)
    return tz_date.isoformat()

with xlrd.open_workbook(sys.argv[1]) as wb:
    sheet = wb.sheet_by_name("COVID-19-geographic-disbtributi")
    rows = list(sheet.get_rows())
    cols = rows.pop(0)

    start_row = min(rows, key=lambda row: row[0].value)
    start_xldate = int(start_row[0].value)
    start_isodate = row_to_iso_date(start_row)

    end_row = max(rows, key=lambda row: row[0].value)
    end_xldate = int(end_row[0].value)
    end_isodate = row_to_iso_date(end_row)

    n_days = end_xldate - start_xldate + 1

    for row in reversed(rows):
        # Excel cells -> Python types
        xldate = int(row[0].value)
        day = int(row[1].value)
        month = int(row[2].value)
        year = int(row[3].value)
        cases = int(row[4].value)
        deaths = int(row[5].value)
        country = row[6].value
        country_id = row[7].value
        if not row[8].value:
            print(country)
        #population = int(row[8].value)

        if country_id in country_overrides:
            country = country_overrides[country_id]
        else:
            iso_country = pycountry.countries.get(alpha_2=country_id)
            if iso_country is None:
                country = country.replace("_", " ")
                print(country)
            else:
                country = getattr(iso_country, "common_name", iso_country.name)

        ## 1. relative
        if country not in cases_rel:
            cases_rel[country] = [0] * n_days
            deaths_rel[country] = [0] * n_days

        date_offset = xldate - start_xldate
        cases_rel[country][date_offset] += cases
        deaths_rel[country][date_offset] += deaths

# Undo the reversal
cases_rel = dict(reversed(cases_rel.items()))
deaths_rel = dict(reversed(deaths_rel.items()))

# Add a meta "Total" country
total_cases_rel = []
for i in range(n_days):
    total_cases_rel.append(sum(cases[i] for cases in cases_rel.values()))
cases_rel["Total"] = total_cases_rel

total_deaths_rel = []
for i in range(n_days):
    total_deaths_rel.append(sum(deaths[i] for deaths in deaths_rel.values()))
deaths_rel["Total"] = total_deaths_rel

## 2. abs
for country, cases in cases_rel.items():
    cases_abs[country] = []
    for i in range(len(cases)):
        cases_abs[country].append(sum(cases[:i+1]))

for country, deaths in deaths_rel.items():
    deaths_abs[country] = []
    for i in range(len(deaths)):
        deaths_abs[country].append(sum(deaths[:i+1]))

## 3. grw
for country, cases in cases_rel.items():
    cases_grw[country] = [0]
    for i, new_cases in enumerate(cases):
        if i == 0:
            continue

        prev_cases = cases[i - 1]
        grw = new_cases / prev_cases if prev_cases else 0
        cases_grw[country].append(round(grw, 2))

for country, deaths in deaths_rel.items():
    deaths_grw[country] = [0]
    for i, new_deaths in enumerate(deaths):
        if i == 0:
            continue

        prev_deaths = deaths[i - 1]
        grw = new_deaths / prev_deaths if prev_deaths else 0
        # Round to 2 digits for friendly user presentation
        deaths_grw[country].append(round(grw, 2))

data = {
    "dates": {
        "start": start_isodate,
        "end": end_isodate,
        "count": n_days,
    },
    "cases": {
        "absolute": cases_abs,
        "relative": cases_rel,
        "growth": cases_grw,
    },
    "deaths": {
        "absolute": deaths_abs,
        "relative": deaths_rel,
        "growth": deaths_grw,
    },
}

with open(sys.argv[2], "w+") as out:
    json.dump(data, out)


"""Unit tests for workload.py."""
import re
import sys
import unittest
from pathlib import Path
from unittest.mock import MagicMock

p = Path(__file__).parents[2]
sys.path.append(f"{p}/")
from common import workload  # noqa

class Test_Workload(unittest.TestCase):
    """Unit tests for workload class."""

    def test_get_commands(self):
        """Test producing workload_generator commands."""
        dummy_workload = workload.Workload(
            load_generators=["wg_1", "wg_2"],
            target_machines=["tm_1", "tm_2", "tm_3"],
            workload=workload.WorkloadDescription(
                canister_ids=["c_a", "c_b", "c_c"],
                method="plus",
                call_method="call",
                rps=10,
                duration=60,
                raw_payload=None,
                json_payload="",
                arguments=[],
                start_delay=10,
                rps_ratio=0.2,
                subnet=1,
            ),
            workload_idx=0,
            outdir="iter_dir",
            f_stdout="no stdout",
            f_stderr="no stderr",
        )
        dummy_workload._Workload__write_commands_to_file = MagicMock()
        commands = [re.sub("  +", " ", c.strip()) for c in dummy_workload.get_commands()]
        assert len(commands) == 2
        commands[0] = commands[0][: commands[0].find("wg_summary_")]
        commands[1] = commands[1][: commands[1].find("wg_summary_")]
        print(commands[0])
        print(commands[1])
        print(commands[0])
        assert (
            commands[0]
            == './ic-workload-generator "http://[tm_1]:8080,http://[tm_2]:8080,http://[tm_3]:8080" -n 60 --no-status-check --query-timeout-secs 30 --ingress-timeout-secs 360 --payload \'\' -m plus --call-method "call" --canister-id c_a -r 5.0 --summary-file '
        )
        assert (
            commands[1]
            == './ic-workload-generator "http://[tm_1]:8080,http://[tm_2]:8080,http://[tm_3]:8080" -n 60 --no-status-check --query-timeout-secs 30 --ingress-timeout-secs 360 --payload \'\' -m plus --call-method "call" --canister-id c_b -r 5.0 --summary-file '
        )

if __name__ == "__main__":
    unittest.main()


# Packages
import numpy as np
import matplotlib.pyplot as plt
import os
from sklearn.linear_model import LinearRegression

class Malthus_estimator_sim(object):
    """
    This class allows to compare different estimators of malthusian coefficient.
    There are four estimators:

    - ln(N_t)/t,
    - [ln(N_{t_1}) - ln(N_{t_0})]/[t_1 - t_0],
    - linear regression between log(number of cellules) and times, with least
    squares, in a range of time [0 t_{max}],
    - linear regression between log(number of cellules) and times, with least
    squares, in a range of time [T_{n_0}, T_{n_1}] where T_n is the first
    time where we have n cells.

    In this class, functions allows to estimate with all of these methods, to
    plot some curves linked to the estimation and to save scores of estimation
    (the score is the relative error). "Norange methods" corresponds to the first
    and the third estimators in the above liste (the only change is the linear
    regression), and "Range methods" corresponds to the second and the fourth
    estimators.

    Attributes
    ------------
    all_times : "np.array"
        2D array where there are all of the times used for all simulations of cells
        dynamics.

    all_cells  : "np.array"
        2D array with the evolution of the cells number for each simulation.

    param_1_k : float
        Parameter k of gamma distribution.

    param_2_theta : float
        Parameter theta of gamma distribution.
    """

    def __init__(
        self,
        all_times: "np.array",
        all_cells: "np.array",
        param_1_k: float,
        param_2_theta: float,
    ):

        # Number of simulations
        self.n_simuls = len(all_times)

        # Load data
        self.all_times = all_times
        self.all_cells = all_cells

        # Save params and true value of malthusian coefficient
        self.param_1_k = param_1_k
        self.param_2_theta = param_2_theta
        self.true_malthus = (2 ** (1 / param_1_k) - 1) / param_2_theta

        # Directory where will be save elements
        self.path_name = (
            "output/param_k_"
            + str(np.round(self.param_1_k, 1))
            + "_param_theta_"
            + str(np.round(self.param_2_theta, 1))
        )
        if not os.path.isdir(self.path_name):
            os.mkdir(self.path_name)

    def estim_malthus_first_method(self, with_regression: bool = False):
        """
        This funtion allows to make an estimation of the malthusian coefficient,
        with:

        - ln(N_t)/t when with_regression = False,
        - linear regression between log(number of cellules) and times, with least
        squares, in a range of time [0 t_{max}] when with_regression = True.

        The final estimator is the mean of all the estimations made for each
        individual simulation.

        Parameters
        ------------
        with_regresion : bool
            Parameter to know if we will use the linear regression or not.
        """

        self.all_malthus_first = np.zeros(self.n_simuls)
        for simul in range(0, self.n_simuls):

            times = self.all_times[simul]
            n_cells = self.all_cells[simul]

            max_time = times[-1]
            index_max_time = np.where(times <= max_time)[0][-1]

            if with_regression:
                linear_regression = LinearRegression().fit(
                    times.reshape(-1, 1), np.log(n_cells)
                )
                self.all_malthus_first[simul] = linear_regression.coef_[0]
            else:

                self.all_malthus_first[simul] = (
                    np.log(n_cells[index_max_time]) / max_time
                )

        self.malthus_first = np.mean(self.all_malthus_first)

    def estim_malthus_second_method(
        self,
        start_cells: int = 1000,
        end_cells: int = 6000,
        with_regression: bool = False,
    ):
        """
        This funtion allows to make an estimation of the malthusian coefficient,
        with:

        - [ln(N_{t_1}) - ln(N_{t_0})]/[t_1 - t_0] when with_regression = False,
        - linear regression between log(number of cellules) and times, with least
        squares, in a range of time [T_{n_0}, T_{n_1}] where T_n is the first
        time where we have n cells (it is a stopping time) when with_regression = True.

        The final estimator is the mean of all the estimations made for each
        individual simulation.

        Parameters
        ------------
        start_cells : int
            Value of the number of cells we will use for the first stopping time.
            It is the lower bound of the range where we will make our linear
            regression.

        end_cells : int
            Value of the number of cells we will use for the second stopping time.
            It is the higher bound of the range where we will make our linear
            regression.

        with_regresion : bool
            Parameter to know if we will use the linear regression or not.
        """
        self.all_malthus_second = np.zeros(self.n_simuls)
        for simul in range(0, self.n_simuls):

            times = self.all_times[simul]
            n_cells = self.all_cells[simul]

            self.index_min_time = np.where(n_cells == start_cells)[0][
                0
            ]  # Self beacause we need it after
            self.index_max_time = np.where(n_cells == end_cells)[0][0]

            # On garde que les derniers temps
            times_reg = times[self.index_min_time : self.index_max_time]
            n_cells_reg = n_cells[self.index_min_time : self.index_max_time]

            if with_regression:
                linear_regression = LinearRegression().fit(
                    times_reg.reshape(-1, 1), np.log(n_cells_reg)
                )
                self.all_malthus_second[simul] = linear_regression.coef_[0]
            else:
                self.all_malthus_second[simul] = (
                    np.log(n_cells_reg[-1] / n_cells_reg[0])
                ) / (times_reg[-1] - times_reg[0])
        self.malthus_second = np.mean(self.all_malthus_second)

    def plot_norange_method(self, index_to_plot: int, with_regression: bool = False):
        """
        This function allows to compute relative error of our estimation, and plot
        some curves to illustrate the estimation we have done with methods without
        range.

        Parameters
        ------------
        index_to_plot : int
            Index of the simulation we will use for the figures.

        with_regression : bool
            If the estimation has been done with Linear Regression, the curves
            will be different (the title). The boolean allows to take this into
            account.
        """

        ### Compute score
        final_relative_error = np.abs(
            (self.malthus_first - self.true_malthus) / self.true_malthus
        )
        self.scores = final_relative_error

        ### Plot
        size_fig = 10
        fig = plt.figure(figsize=(size_fig, size_fig))
        plt.plot(
            self.all_times[index_to_plot],
            np.log(self.all_cells[index_to_plot]) / self.all_times[index_to_plot],
            label="Estimator",
        )
        plt.axhline(
            [self.true_malthus],
            linestyle="dashed",
            color="red",
            label="y = malthus_theo",
        )
        plt.xlabel("Time")
        plt.ylabel("Estimator")
        main_title = plt.title(
            "ln(N_t)/t versus time for one random simulation, relative error: {}".format(
                np.round(
                    np.abs(
                        (self.all_malthus_first[index_to_plot] - self.true_malthus)
                        / self.true_malthus
                    ),
                    3,
                )
            ),
            fontweight="bold",
        )

        ### Save
        name_fig = (
            "random_curve_method_1_param_k_"
            + str(np.round(self.param_1_k, 1))
            + "_param_theta_"
            + str(np.round(self.param_2_theta, 1))
            + ".png"
        )
        if with_regression:  # Name are differents for regression
            name_fig = "regression_" + name_fig
        plt.savefig(
            os.path.join(self.path_name, name_fig), bbox_extra_artists=[main_title],
        )

    def plot_range_method(self, index_to_plot: int, with_regression: bool = False):
        """
        This function allows to compute relative error of our estimation, and plot
        some curves to illustrate the estimation we have done with methods with
        a range for the times.

        Parameters
        ------------
        index_to_plot : int
            Index of the simulation we will use for the figures.

        with_regression : bool
            If the estimation has been done with Linear Regression, the curves
            will be different (the title). The boolean allows to take this into
            account.
        """
        ### Compute score
        final_relative_error = np.abs(
            (self.malthus_second - self.true_malthus) / self.true_malthus
        )
        self.scores = final_relative_error

        ### Plot
        size_fig = 10
        fig = plt.figure(figsize=(size_fig, size_fig))
        plt.plot(
            self.all_times[index_to_plot],
            np.log(self.all_cells[index_to_plot]),
            label="Estimator",
        )
        plt.axvline(
            self.all_times[index_to_plot, self.index_min_time],
            linestyle="dashed",
            color="red",
            label="Range linear regression",
        )
        plt.axvline(
            self.all_times[index_to_plot, self.index_max_time],
            linestyle="dashed",
            color="red",
        )
        plt.xlabel("Time")
        plt.ylabel("log(Cell numbers)")

        main_title = plt.title(
            "ln(N_t) versus time for one simulation, relative error: {}".format(
                np.round(
                    np.abs(
                        (self.all_malthus_second[index_to_plot] - self.true_malthus)
                        / self.true_malthus
                    ),
                    4,
                )
            ),
            fontweight="bold",
        )
        plt.legend()

        ### Save
        name_fig = (
            "random_curve_method_2_param_k_"
            + str(np.round(self.param_1_k, 1))
            + "_param_theta_"
            + str(np.round(self.param_2_theta, 1))
            + ".png"
        )
        if with_regression:  # Name are differents for regression
            name_fig = "regression_" + name_fig
        plt.savefig(
            os.path.join(self.path_name, name_fig), bbox_extra_artists=[main_title],
        )

    def plot_influence_n_simulation(self):
        """
        This function allows to see the influence of number of simulations in the
        performance of the estimator. We will compute the relative error of the
        estimator for several number of simulation, see how it evolves. We will
        plot this evolution and save it after that.
        """

        ## Compute quantities
        malthus_by_n_simul = np.cumsum(self.all_malthus_first) / np.arange(
            1, self.n_simuls + 1
        )
        ecart_n_simul = (
            np.abs(malthus_by_n_simul - self.true_malthus) / self.true_malthus
        )

        ## Plot
        fig = plt.figure()
        plt.plot(
            np.arange(1, self.n_simuls + 1),
            ecart_n_simul * 100,
            label="param_1_k = {}, param_2_theta = {}".format(
                np.round(self.param_1_k, 3), np.round(self.param_2_theta, 3)
            ),
            color="blue",
        )
        plt.xlabel("Numver of simulations")
        plt.ylabel("Relative error (%)")
        main_title = plt.title("Relative error estimator versus number of simulations")
        plt.legend()
        plt.savefig(
            os.path.join(
                self.path_name,
                "influence_n_simulation_param_k_"
                + str(np.round(self.param_1_k, 1))
                + "_param_theta_"
                + str(np.round(self.param_2_theta, 1))
                + ".png",
            ),
            bbox_extra_artists=[main_title],
        )


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:

        if not head or not k:
            return head
        l1 = head
        c1 = head
        new = ListNode()
        head = new
        c = 0
        while c1:
            c+=1
            c1=c1.next
        k = k%c if k>=c else k
        arr = [0]*c
        c = 0
        for i in range(len(arr)):
            arr[i] = l1.val
            l1=l1.next
            if l1 == None:
                break
        print(arr)
        for i in range(-k,len(arr)-k):
            new.next = ListNode(arr[i])
            new = new.next

        return head.next

#             current = ListNode()
#         head = current

#         for i in range(n - k, n):
#             node = ListNode(temp[i])
#             current.next = node
#             current = current.next


from typing import Tuple

from utils import printer
from utils import randomWordGenerator

VOWELS = ('a', 'e', 'i', 'o', 'u')
EMPTY_STRING = ''

def getUpdatedVisibleAlphabets(actualWord: str, visibleAlphabets: str, guess: str) -> str:
    return EMPTY_STRING.join(
        [guess if guess == actualWord[index] else visibleAlphabets[index] for index in range(len(actualWord))]
    )

def updateVisibleAlphabetsWithGuess(actualWord: str, guess: str, visibleAlphabets: str, attemptsRemaining: int) -> Tuple[str, int]:
    if guess in actualWord:
        visibleAlphabets = getUpdatedVisibleAlphabets(actualWord, visibleAlphabets, guess)
    else:
        attemptsRemaining -= 1
    return visibleAlphabets, attemptsRemaining

def gameHasEnded(actualWord, guessedWord, attemptsRemaining):
    if guessedWord == actualWord:
        printer.success('You WON! :D')
        return True
    elif attemptsRemaining <= 0:
        printer.failure('You Lost :(')
        printer.information(f'Word was {actualWord}')
        return True
    return False

def isVowel(character: str) -> bool:
    return character in VOWELS

def createVisibleAlphabets(word: str) -> str:
    return EMPTY_STRING.join([character if isVowel(character) else '_' for character in word])

def startGame(attempts=5):
    actualWord = randomWordGenerator.getRandomWord()
    visibleAlphabets = createVisibleAlphabets(actualWord)

    while not gameHasEnded(actualWord, visibleAlphabets, attempts):
        printer.gameStatus(visibleAlphabets, attempts)
        guess = input('Guess a character: ')
        print()
        visibleAlphabets, attempts = updateVisibleAlphabetsWithGuess(actualWord, guess, visibleAlphabets, attempts)

if __name__ == '__main__':
    startGame(attempts=6)


#!/usr/bin/python3
import operator
import copy
from pygraph.classes.digraph import digraph
from pygraph.algorithms.cycles import find_cycle
from levenshtein import levenshtein

# Classe aresta contendo a origem, o destino, o peso e uma flag indicando se ela e valida para adiocionar no caminho hamiltoniano
class Edge:
  def __init__(self, source, target, weight):
    self.source = source
    self.target = target
    self.weight = weight
    self.valid = True

  def __repr__(self):
    return "{%s, %s, %s, %s}" % (self.source, self.target, self.weight, self.valid)

  def __str__(self):
    return "{%s, %s, %s, %s}" % (self.source, self.target, self.weight, self.valid)

# Classe Grafo, contendo uma lista de vertices e uma lista de arestas
class Graph:
  def __init__(self, vertexes):
    self.edges = []
    self.vertexes = vertexes

  def __repr__(self):
    return "{%s, %s}" % (self.edges, self.vertexes)

  # Metodo para encontrar uma aresta dado origem e destino
  def getEdge(self, x, y):
    for edge in self.edges:
      if edge.source==x and edge.target==y:
            return edge
    return None

  # Metodo para buscar uma aresta dado sua origem
  def getEdgeBySource(self, x):
    for edge in self.edges:
      if edge.source==x:
            return edge
    return None

# Funcao que determina o peso da aresta
def find_overlap(node1, node2):
  overlap = 0;
  for i in range(0, len(node2), 1):
    if (node1.endswith(node2[0:i+1])):
      overlap = i+1 # CASO EXISTA ARESTA, RETORNA O TAMANHO
  return overlap

# Funcao que controi o grafo recebendo a lista de fragmentos como parametro
def build_graph(nodes):
  vertexes = [0 for x in range(len(nodes))]

  for i in range(len(nodes)):
    vertexes[i] = nodes[i]

  graph = Graph(vertexes)
  edges = []

  for x in range(0, len(nodes)):
    for y in range(0, len(nodes)):
      if x!=y:
        edges.append(Edge(x, y, find_overlap(nodes[x], nodes[y])))
  graph.edges = sorted(edges, key=lambda edge: edge.weight, reverse=True)
  return graph

  # Funcao que verifica se um grafo tera um ciclo caso se adiciona uma aresta. O parametro tree representa o grafo antes da adicao da aresta
def hasCycle(trees, edge):
    sT = False
    sS = False

    for t in trees:
        if edge.source in t and edge.target in t:
            return True
        elif edge.target in t:
            sT = t
        elif edge.source in t:
            sS = t

    if sT == False and sS == False:
        trees.append([edge.source, edge.target])
    elif sT != False and sS != False:
        sS.extend(sT)
        trees.remove(sT)
    elif sT != False:
        sT2 = [edge.source]
        trees.remove(sT)
        sT2.extend(sT)
        trees.append(sT2)
    elif sS != False:
        sS = sS.append(edge.target)

    return False

# Funcao para montar a sequencia dado um caminho hamiltoniano
def assemblyFragment(path):
  aux = []
  for x in path.edges:
    aux.append(x.target)

  for edge in path.edges:
    if edge.source not in aux:
      first = edge

  edge = first

  scs = ""
  while edge != None:
    node = path.vertexes[edge.source]
    scs+=node[:len(node)-edge.weight]
    if (path.getEdgeBySource(edge.target) == None):
      scs+=path.vertexes[edge.target]

    edge = path.getEdgeBySource(edge.target)
  return scs

# Funcao para que encontra um caminho hamiltonino. O primeiro parametro representa o arquivo que contem a lista de fragmentos, o segundo
# representa o arquivo onde serao gravados os resultados da execucao e o terceiro e o arquivo que contem os resultados do guloso e do acs para
# posterior comparacao
def solve(fragFileName, outputFile, seqFileName):
    # Montar o grafo
    nodes = []

    fragFile = open(fragFileName, "r")
    fragments = fragFile.readlines()
    fragments = [x.strip('\n') for x in fragments]
    for frag in fragments:
        included = False
        for existing in nodes:
            if frag in existing:
                included = True
                break

        if not included:
            nodes.append(frag)
    fragFile.close()

    graph = build_graph(nodes)

    path = Graph([])
    path.vertexes = [0 for x in range(len(nodes))]
    trees = []

    #### Encontrar o caminho hamiltoniano
    for edge in graph.edges:
        for x in path.edges:
            # Verifica se a origem e o destino da aresta candidata ja existem no grafo
            if edge.source == x.source:
                edge.valid = False
            elif edge.target == x.target:
                edge.valid = False

        # Verifica se a adicao da aresta ira formar ciclo no caminho
        if edge.valid and hasCycle(trees, edge):
            edge.valid = False

        # Se aresta passar pelos testes anteriores ela e adcionada ao caminho
        if (edge.valid):
            path.edges.append(edge)
        if graph.vertexes[edge.source] not in path.vertexes:
            path.vertexes[edge.source] = graph.vertexes[edge.source]
        if graph.vertexes[edge.target] not in path.vertexes:
            path.vertexes[edge.target] = graph.vertexes[edge.target]

        if len(nodes) == len(path.edges) + 1:
            break

    #### Monta a sequencia baseada no caminho encontrado
    assembledSequence = assemblyFragment(copy.deepcopy(path))
    # Tamanho da solução
    result = len(assembledSequence)

    # # Distância da solução
    seqFile = open(seqFileName, "r")
    sequence = seqFile.readlines()
    dist = levenshtein.levenshteinDistance(assembledSequence, sequence[0])

    outputFile.write('\nGreedy: Tamanho da sequencia montada: ' + str(result))
    outputFile.write("\nnGreedy: Levenshtein Distance = " +
    str(dist));
    return result, dist, trees


import sys
import optparse
import logging
import Gnuplot
import numpy as np

import pdb
logging.basicConfig(level=logging.DEBUG)

help_message = '''
Takes as input an svm file whose vectors contain means and variances. Assumes
that the data came from a Gaussian distribution and plots these Gaussian
distributions using gnuplot. Indices should be 1-indexed.
'''

def main():
    usage = """%prog SVM_FILE [options]"""

    opt_parser = optparse.OptionParser(usage=usage)

    opt_parser.add_option("-v", "--verbose", action="store_true",
                       default=False, dest="verbose")

    options, arguments = opt_parser.parse_args()

    if len(arguments) != 3:
        logging.error("There should be 3 arguments, the file, mean index and variance index")
        exit()

    svm_filename = arguments[0]

    distribution_dicts = read_svm_file(svm_filename)

    plot_distributions(distribution_dicts)

def read_svm_file(filename):
    '''
    Returns a list of dicts with three keys: 'class', 'mean', 'variance'
    '''
    dicts = []
    for line in open(filename):
        if line.strip() != '':
            fields = line.split(' ')

            new_dict = {}
            new_dict['class'] = fields[0]

            vector = [float(x.split(':')[1]) for x in fields[1:]]

            new_dict['mean']     = vector[0]
            new_dict['min']      = vector[1]
            new_dict['max']      = vector[2]
            new_dict['variance'] = vector[3]

            dicts.append(new_dict)

    return dicts

def plot_distributions(dist_dicts):
    '''
    Creates a plot with all of the distributions overlayed with different
    classes as different colors.
    '''
    plot_cmd = "plot 1/sqrt(%(variance)f * 2 * pi) * exp(- (x-%(mean)f)**2 / (2 * %(variance)f)) linetype %(class)s;\n"

    min_mean = 99999
    max_mean = 0

    g = Gnuplot.Gnuplot(debug=1)
    g.title('Distributions')
    g('set data style linespoints')
    g('set yrange [0:.1]')
    g('set xrange [130:180]')
    g('set key off')
    g('set ylabel "probability"')
    g('set xlabel "pitch"')
    for index, dist_dict in enumerate(dist_dicts):
        # start replotting
        if index == 1:
            plot_cmd = 're' + plot_cmd

        g(plot_cmd % dist_dict)

        min_mean = min(min_mean, dist_dict['mean'])
        max_mean = max(max_mean, dist_dict['mean'])

    #g.set_range('xrange', (min_mean-1, max_mean+1))
    #g('set xrange [%f:%f]' % (min_mean, max_mean))

def gaussian_pdf(mean, variance, x):
    '''
    Computes the value of a gaussian pdf with specified mean and variance
    at x.
    '''
    return (1 / np.sqrt(variance * 2 * np.pi) ) * np.exp( - (x - mean)^2/(2 * variance))

if __name__ == "__main__":
    main()


# load and display an image with Matplotlib
from matplotlib import image
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
from numpy import asarray
from scipy import signal
from scipy import misc
from scipy import stats
import scipy
# load image as pixel array

mainFrame = Image.open('groupGray.jpg')
mainFrame = mainFrame.convert("L")

baba = Image.open("boothiGray.jpg")
baba = baba.convert("L")
print(baba.format)
print(baba.mode)
mrows,mcols = mainFrame.size
brows,bcols = baba.size
print(f"Baba Jee Rows : {bcols} baba jee cols : {brows}")
babaarray = asarray(baba)
mainarray = asarray(mainFrame)
print(stats.kendalltau(babaarray,mainarray[108:108+35,643:643+29]).correlation)

# mainarray = mainarray - mainarray.mean()
# babaarray = babaarray - babaarray.mean()
# corr = signal.correlate2d(mainarray, babaarray, boundary='symm', mode='same')
# plt.imshow(corr,cmap="gray")
# plt.show()
# print(corr)
# print(np.amax(corr))
# result = np.where(corr == np.amax(corr))
# print(list(result))
# print("asdasda")
cropMain = mainarray[107:107+35,634:634+29]
print(mainarray.shape)
print(mainarray.ndim)
print(mainFrame.size)

print(baba.size)
print(babaarray.shape)
# in np mainarray max dimension (512,1024)
# 512 no of rows and 1024 nmbr of cols

# print("Core")
# r = np.corrcoef(cropMain, babaarray)

# print(type(np.mean(r,axis=(0,1))))
# print("Coreeee")
plt.imshow(mainFrame,cmap="gray")

plt.scatter(634, 107, s=100, c='red', marker='o')

plt.show()

plt.imshow(baba,cmap="gray")
plt.show()

def find_array(template,piece,solution):
    x,y = piece.shape
    startx,starty= solution
    print(startx,starty)
    # if startx+x < (template.shape)[0] and starty+y < (template.shape)[1]:
    result = template[startx:startx+x,starty:starty+y]
    main = []

    return
    for row in range(x):
        rows = []
        for col in range(y):
            # g = float("{:.1f}".format(result[row,col]/template[row,col]))
            if result[row,col] == 0 or piece[row,col] == 0:
                g = 0
            elif  result[row,col] >= piece[row,col]:
                g = (piece[row,col] * 100)// result[row,col]
                g = float("{:.1f}".format(g/100))
            else:
                g = (result[row,col] * 100)// piece[row,col]
                g = float("{:.1f}".format(g/100))
            rows.append(g)
        main.append(rows)
    main = np.mean(main,axis=None)
    return main

# res = find_array(mainarray,babaarray,[122,653])
# # print(res)

x = mainarray[118:118+35,651:651+29]
y = np.copy(babaarray)
tau, p_value = stats.kendalltau(x, y)


class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        points.sort()

        ans = 1
        border = points[0][1]
        for i in range(1, len(points)):
            start = points[i][0]
            end = points[i][1]
            if start > border:
                ans += 1
                border = end
            else:
                border = min(end, border)
        return ans


import os
import time

from parsons.etl.table import Table
from parsons.utilities.check_env import check

from slackclient import SlackClient
from slackclient.exceptions import SlackClientError

import requests

class Slack(object):
    def __init__(self, api_key=None):

        if api_key is None:

            try:
                self.api_key = os.environ["SLACK_API_TOKEN"]

            except KeyError:
                raise KeyError(
                    "Missing api_key. It must be passed as an "
                    "argument or stored as environmental variable"
                )

        else:

            self.api_key = api_key

        self.client = SlackClient(self.api_key)

    def channels(
        self, fields=["id", "name"], exclude_archived=False, types=["public_channel"]
    ):
        """
        Return a list of all channels in a Slack team.

        `Args:`
            fields: list
                A list of the fields to return. By default, only the channel
                `id` and `name` are returned. See
                https://api.slack.com/methods/conversations.list for a full
                list of available fields. `Notes:` nested fields are unpacked.
            exclude_archived: bool
                Set to `True` to exclude archived channels from the list.
                Default is false.
            types: list
                Mix and match channel types by providing a list of any
                combination of `public_channel`, `private_channel`,
                `mpim` (aka group messages), or `im` (aka 1-1 messages).
        `Returns:`
            Parsons Table
                See :ref:`parsons-table` for output options.
        """
        tbl = self._paginate_request(
            "conversations.list",
            "channels",
            types=types,
            exclude_archived=exclude_archived,
        )

        tbl.unpack_dict(
            "topic", include_original=False, prepend=True, prepend_value="topic"
        )
        tbl.unpack_dict(
            "purpose", include_original=False, prepend=True, prepend_value="purpose"
        )

        rm_cols = [x for x in tbl.columns if x not in fields]
        tbl.remove_column(*rm_cols)

        return tbl

    def users(
        self,
        fields=[
            "id",
            "name",
            "deleted",
            "profile_real_name_normalized",
            "profile_email",
        ],
    ):
        """
        Return a list of all users in a Slack team.

        `Args:`
            fields: list
                A list of the fields to return. By default, only the user
                `id` and `name` and `deleted` status are returned. See
                https://api.slack.com/methods/users.list for a full list of
                available fields. `Notes:` nested fields are unpacked.
        `Returns:`
            Parsons Table
                See :ref:`parsons-table` for output options.
        """

        tbl = self._paginate_request("users.list", "members", include_locale=True)

        tbl.unpack_dict(
            "profile", include_original=False, prepend=True, prepend_value="profile"
        )

        rm_cols = [x for x in tbl.columns if x not in fields]
        tbl.remove_column(*rm_cols)

        return tbl

    @classmethod
    def message(cls, channel, text, webhook=None, parent_message_id=None):
        """
        Send a message to a Slack channel with a webhook instead of an api_key.
        You might not have the full-access API key but still want to notify a channel
        `Args:`
            channel: str
                The name or id of a `public_channel`, a `private_channel`, or
                an `im` (aka 1-1 message).
            text: str
                Text of the message to send.
            webhook: str
                If you have a webhook url instead of an api_key
                Looks like: https://hooks.slack.com/services/Txxxxxxx/Bxxxxxx/Dxxxxxxx
            parent_message_id: str
                The `ts` value of the parent message. If used, this will thread the message.
        """
        webhook = check("SLACK_API_WEBHOOK", webhook, optional=True)
        payload = {"channel": channel, "text": text}
        if parent_message_id:
            payload["thread_ts"] = parent_message_id
        return requests.post(webhook, json=payload)

    def message_channel(self, channel, text, as_user=False, parent_message_id=None):
        """
        Send a message to a Slack channel

        `Args:`
            channel: str
                The name or id of a `public_channel`, a `private_channel`, or
                an `im` (aka 1-1 message).
            text: str
                Text of the message to send.
            as_user: str
                Pass true to post the message as the authenticated user,
                instead of as a bot. Defaults to false. See
                https://api.slack.com/methods/chat.postMessage#authorship for
                more information about Slack authorship.
            parent_message_id: str
                The `ts` value of the parent message. If used, this will thread the message.
        `Returns:`
            `dict`:
                A response json
        """
        resp = self.client.api_call(
            "chat.postMessage",
            channel=channel,
            text=text,
            as_user=as_user,
            thread_ts=parent_message_id,
        )

        if not resp["ok"]:

            if resp["error"] == "ratelimited":
                time.sleep(int(resp["headers"]["Retry-After"]))

                resp = self.client.api_call(
                    "chat.postMessage", channel=channel, text=text, as_user=as_user
                )

            raise SlackClientError(resp["error"])

        return resp

    def upload_file(
        self,
        channels,
        filename,
        filetype=None,
        initial_comment=None,
        title=None,
        is_binary=False,
    ):
        """
        Upload a file to Slack channel(s).

        `Args:`
            channels: list
                The list of channel names or IDs where the file will be shared.
            filename: str
                The path to the file to be uploaded.
            filetype: str
                A file type identifier. If None, type will be inferred base on
                file extension. This is used to determine what fields are
                available for that object. See https://api.slack.com/types/file
                for a list of valid types and for more information about the
                file object.
            initial_comment: str
                The text of the message to send along with the file.
            title: str
                Title of the file to be uploaded.
            is_binary: bool
                If True, open this file in binary mode. This is needed if
                uploading binary files. Defaults to False.
        `Returns:`
            `dict`:
                A response json
        """
        if filetype is None and "." in filename:
            filetype = filename.split(".")[-1]

        mode = "rb" if is_binary else "r"
        with open(filename, mode) as file_content:
            resp = self.client.api_call(
                "files.upload",
                channels=channels,
                file=file_content,
                filetype=filetype,
                initial_comment=initial_comment,
                title=title,
            )

            if not resp["ok"]:

                if resp["error"] == "ratelimited":
                    time.sleep(int(resp["headers"]["Retry-After"]))

                    resp = self.client.api_call(
                        "files.upload",
                        channels=channels,
                        file=file_content,
                        filetype=filetype,
                        initial_comment=initial_comment,
                        title=title,
                    )

                raise SlackClientError(resp["error"])

        return resp

    def _paginate_request(self, endpoint, collection, **kwargs):
        # The max object we're requesting at a time.
        # This is an nternal limit to not overload slack api
        LIMIT = 200

        items = []
        next_page = True
        cursor = None
        while next_page:
            resp = self.client.api_call(endpoint, cursor=cursor, limit=LIMIT, **kwargs)

            if not resp["ok"]:

                if resp["error"] == "ratelimited":
                    time.sleep(int(resp["headers"]["Retry-After"]))
                    continue

                raise SlackClientError(resp["error"])

            items.extend(resp[collection])

            if resp["response_metadata"]["next_cursor"]:
                cursor = resp["response_metadata"]["next_cursor"]
            else:
                next_page = False

        return Table(items)


#!/usr/bin/env python

# coding: utf-8
import sys
import csv
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import gaussian_kde
from Utils import CSVreader, Pathname

## Classes

class Plot():
    outfile = None
    imgformat = "png"
    title = None
    xlabel = None
    ylabel = None
    xsize = 10
    ysize = 8

    def parseCommonArgs(self, args):
        other = []
        prev = ""
        for a in args:
            if prev == "-o":
                self.outfile = a
                prev = ""
            elif prev == "-t":
                self.title = a
                prev = ""
            elif prev == "-xl":
                self.xlabel = a
                prev = ""
            elif prev == "-yl":
                self.ylabel = a
                prev = ""
            elif prev == "-xs":
                self.xsize = float(a)
                prev = ""
            elif prev == "-ys":
                self.ysize = float(a)
                prev = ""
            elif prev == "-f":
                self.imgformat = a
                prev = ""
            elif a in ["-o", "-t", "-xl", "-yl", "-f", "-xs", "-ys"]:
                prev = a
            else:
                other.append(a)
        return other

class DensityPlot(Plot):
    infile = None
    log = False
    hasHeader = None
    skipRows = None
    pointSize = 50
    cx = 4
    cy = 3

    def parseArgs(self, args):
        if "-h" in args or "--help" in args:
            return self.usage()
        args = self.parseCommonArgs(args)
        prev = ""
        for a in args:
            if prev == "-cx":
                self.cx = int(a)
                prev = ""
            elif prev == "-cy":
                self.cy = int(a)
                prev = ""
            elif prev == "-s":
                self.skipRows = int(a)
                prev = ""
            elif prev == "-p":
                self.pointSize = int(a)
                prev = ""
            elif a in ["-cx", "-cy", "-s", "-p"]:
                prev = a
            elif a == "-l":
                self.log = np.log(2)
            elif a == "-l10":
                self.log = np.log(10)
            elif a == "-t":
                self.hasHeader = 0
            elif self.infile is None:
                self.infile = a
        return (self.infile and self.outfile)

    def run(self):
        df = pd.read_table(self.infile, header=self.hasHeader, skiprows=self.skipRows)
        sys.stderr.write("Data file read.\n")

        if self.log:
            df[self.cy] = df[self.cy].apply(lambda x: np.log(x+1) / self.log)
            df[self.cx] = df[self.cx].apply(lambda x: np.log(x+1) / self.log)
            min_x = min(df[self.cx])-0.1
            min_y = min(df[self.cy])-0.1

        xy = np.vstack([df[self.cx], df[self.cy]])
        z = gaussian_kde(xy)(xy)

        idx = z.argsort()
        x, y, z = df[self.cx][idx], df[self.cy][idx], z[idx]

        fig, ax = plt.subplots(figsize=(self.xsize, self.ysize))
        ax.scatter(x, y, c=z, s=self.pointSize, edgecolor='')
        if self.log:
            plt.xlim(xmin=min_x)
            plt.ylim(ymin=min_y)
        diag_line, = ax.plot(ax.get_xlim(), ax.get_ylim(), ls="-", c="0.3")
        if self.xlabel:
            plt.xlabel(self.xlabel)
        if self.ylabel:
            plt.ylabel(self.ylabel)
        plt.savefig(self.outfile, format=self.imgformat)

    def usage(self):
        sys.stdout.write("""polyplotter.py dscatt - Draw density scatterplots of paired data.

Usage: polyplotter.py dscatt [options] datafile imgfile

Read data from two columns of file `datafile' and draw a density heatmap
of their scatterplot to `imgfile'.

Options related to input data:

  -cx C | Use column C for X axis coordinates (default: {}).
  -cy C | Use column C for Y axis coordinates (default: {}).
  -s  S | Skip S rows from top of input file (default: {}).
  -l    | If supplied, log-transform data (base 2).
  -l10  | If supplied, log-transform data (base 10).

Graphical options:

  -xs S | Set X dimension of image to S inches (default: {}).
  -ys S | Set Y dimension of image to S inches (default: {}).
  -xl L | Set X axis label to L.
  -yl L | Set Y axis label to L.
  -p P  | Set dot size to P (default: {}).
  -f F  | Set output image format to F (default: {}).

""".format(DensityPlot.cx, DensityPlot.cy, DensityPlot.skipRows, DensityPlot.xsize, DensityPlot.ysize, DensityPlot.pointSize, DensityPlot.imgformat))
        sys.exit(1)

class MethylHist(Plot):
    infile = None

    def parseArgs(self, args):
        if "-h" in args or "--help" in args:
            return self.usage()
        args = self.parseCommonArgs(args)
        prev = ""
        for a in args:
            if self.infile == None:
                self.infile = a
        return (self.infile and self.outfile)

    def makeHistogramFromColumn(self, column, edges, normalize=False):
        nbins = len(edges) - 1
        bins = np.zeros(nbins)
        for line in CSVreader(self.infile):
            x = float(line[column])
            if x < edges[0]:
                continue
            for i in range(nbins):
                if x < edges[i+1]:
                    bins[i] += 1
                    break
        if normalize:
            bins = bins / np.sum(bins)
        return bins

    def run(self):
        path = Pathname(self.infile)
        edges = np.linspace(0.0, 1.0, num=11, endpoint=True)
        bins = self.makeHistogramFromColumn(3, edges, normalize=True)
        xc = [ int((x - 0.05) * 100) for x in edges[1:] ]
        fig, ax = plt.subplots(1, 1, figsize=(self.xsize, self.ysize))
        ax.bar(xc, bins, width=8)
        if self.title:
            ax.set_title(self.title)
        else:
            ax.set_title("{} - histogram of methylation values".format(path.name))
        ax.set_xlabel("% Methylation")
        ax.set_ylabel("% Sites")
        fig.savefig(self.outfile)

    def usage(self):
        sys.stdout.write("""polyplotter.py mhist - Draw histogram of methylation data.

Usage: polyplotter.py mhist [options] datafile

Read data from file `datafile' and draw a histogram.

Options related to input data:

- TODO

Graphical options:

- TODO

""".format(MethylHist.infile))
        sys.exit(1)

class DistPlot(Plot):
    infile = None
    log = False
    plot_type = None
    skipRows = None
    pointSize = 50
    index_col = 0
    cx = 4
    cy = 3

    def parseArgs(self, args):
        if "-h" in args or "--help" in args:
            return self.usage()
        args = self.parseCommonArgs(args)
        prev = ""
        for a in args:
            if prev == "-i":
                self.index_col = a
                prev = ""
            elif prev == "-p":
                self.plot_type = a
                prev = ""
            elif a in ["-i","-p"]:
                prev = a
            if a == "-l":
                self.log = np.log(2)
            elif a == "-l10":
                self.log = np.log(10)
        if self.infile == None:
            self.infile = a
        if self.plot_type == None:
            self.plot_type = "box"
        return (self.infile and self.outfile)

    def run(self):
        df = pd.read_table(self.infile, index_col=self.index_col)
        sys.stderr.write("Data file read\n")
        df = df.melt()
        if self.log:
            df.value = df["value"].apply(lambda x: np.log(x+1) / self.log)
        if self.plot_type == "box":
            ax = sns.boxplot(x="variable", y="value", data=df)
        elif self.plot_type == "violin":
            ax = sns.violinplot(x="variable", y="value", data=df)
        elif self.plot_type == "boxen":
            ax = sns.boxenplot(x="variable", y="value", data=df)
        else:
            sys.stderr.write("Invalid plot_type\n")
            self.usage()
        if self.title:
            plt.title(self.title)
        if self.xlabel:
            plt.xlabel(self.xlabel)
        if self.ylabel:
            plt.ylabel(self.ylabel)
        plt.savefig(self.outfile, format=self.imgformat)

    def usage(self):
        sys.stdout.write("""polyplotter.py distr - Draw distribution plot ("box", "violin" or "boxen") for each column in data matrix.

Usage: polyplotter.py distr [options] datafile

Read data from n x m matrix `datafile' and draw a boxplot for each column
onto single plot.

Options related to input data:

    -l    | If supplied, log-scale values (base 2).
    -l10  | If supplied, log-scale values (base 10).

Graphical options:

    -xs S | Set X dimension of image to S inches (default: {}).
    -ys S | Set Y dimension of image to S inches (default: {}).
    -xl L | Set X axis label to L.
    -yl L | Set Y axis label to L.
    -i N  | Set index column number to N. (default: {})
    -p S  | Set plot type to S. (default: {})
    -f F  | Set output image format to F (default: {}).

""".format(DistPlot.xsize, DistPlot.ysize, DistPlot.index_col, DistPlot.plot_type, DistPlot.imgformat))
        sys.exit(1)

class SwarmPlot(Plot):
    def parseArgs():
        pass
    def run():
        pass
    def usage():
        pass

class JointPlot(Plot):
    pass

class HeatmapPlot(Plot):
    infile = None
    log = False
    plot_type = None
    skipRows = None
    pointSize = 50
    index_col = 0
    cx = 4
    cy = 3

    def parseArgs(self, args):
        pass

    def run(self):
        df = pd.read_table(self.infile, index_col=self.index_col)
        sys.stderr.write("Data file read\n")
        df = df.melt()
        if self.log:
            df.value = df["value"].apply(lambda x: np.log(x+1) / self.log)
        if self.cluster:
            ax = sns.clustermap(x="variable", y="value", data=df)
        else:
            ax = sns.heatmap(x="variable", y="value", data=df)
        if self.title:
            plt.title(self.title)
        if self.xlabel:
            plt.xlabel(self.xlabel)
        if self.ylabel:
            plt.ylabel(self.ylabel)
        plt.savefig(self.outfile, format=self.imgformat)

    def usage(self):
        sys.stdout.write("""polyplotter.py heat - Draw heatmap

Usage: polyplotter.py heat [options] datafile

Read data from n x m matrix `datafile' and draw a heat map.

Options related to input data:

    -l    | If supplied, log-scale values (base 2).
    -l10  | If supplied, log-scale values (base 10).

Graphical options:

    -xs S | Set X dimension of image to S inches (default: {}).
    -ys S | Set Y dimension of image to S inches (default: {}).
    -xl L | Set X axis label to L.
    -yl L | Set Y axis label to L.
    -i N  | Set index column number to N. (default: {})
    -p S  | Set plot type to S. (default: {})
    -f F  | Set output image format to F (default: {}).

""".format(HeatmapPlot.xsize, HeatmapPlot.ysize, HeatmapPlot.index_col, HeatmapPlot.plot_type, HeatmapPlot.imgformat))
        sys.exit(1)

class ScatterPlot(Plot):
    pass

class KDEPlot(Plot):
    pass

class LinearModelPlot(Plot):
    pass

class LinePlot(Plot):
    pass

class BarPlot(Plot):
    pass

def mainUsage():
    sys.stdout.write("""polyplotter.py - command-line tool to generate a variety of useful plots

    Usage: polyplotter.py [command] [command-specific_arguments]

Available subcommands:

    dscatt
    mhist
    dist
    heat  -- coming soon

    Ex. polyplotter.py mhist -h

""")

## Main
if __name__ == "__main__":
    try:
        cmd = sys.argv[1]
        args = sys.argv[2:]
    except IndexError:
        sys.stderr.write("Too few parameters\n")
        mainUsage()
        sys.exit(1)
    if cmd == "dscatt":
        P = DensityPlot()
    elif cmd == "mhist":
        P = MethylHist()
    elif cmd == "dist":
        P = DistPlot()
    else:
        mainUsage()
        sys.exit(1)
    try:
        if P.parseArgs(args):
            P.run()
        else:
            P.usage()
    except NameError as error:
        sys.stderr.write(error)
        mainUsage()
        sys.exit(1)


import argparse
import random

import matplotlib.pyplot as plt
import numpy as np
from gensim.models import KeyedVectors
from gensim.test.utils import datapath
from sklearn.manifold import TSNE

parser = argparse.ArgumentParser()
parser.add_argument('--path', type=str, help='Path to file with polish word embeddings for word2vec', required=True)
args = parser.parse_args()

wv = KeyedVectors.load_word2vec_format(datapath(args.path), binary=False)

with open(args.path) as opened:
    for _ in range(0, 20):
        print(opened.readline())

result_file = open("results.txt", mode="w", encoding="utf-8")

ex3_input = (
    "sąd::noun wysoki::adj",
    "trybunał::noun konstytucyjny::adj",
    "kodeks::noun cywilny::adj",
    "kpk::noun",
    "sąd::noun rejonowy::adj",
    "szkoda::noun",
    "wypadek::noun",
    "kolizja::noun",
    "szkoda::noun majątkowy::adj",
    "nieszczęście::noun",
    "rozwód::noun",
)

print("# 3")
result_file.write("# 3\n")
for word in ex3_input:
    closest = "{}:\t\t{}".format(word, wv.most_similar(positive=word.split(), topn=5))
    print(closest)
    result_file.write(closest + "\n")

print("# 4")
result_file.write("# 4\n")
print("sąd wysoki - kpc + konstytucja")
result_file.write("sąd wysoki - kpc + konstytucja\n")
vector = np.sum((wv.get_vector("sąd::noun"), wv.get_vector("wysoki::adj"), wv.get_vector("konstytucja::noun"),
                 np.negative(wv.get_vector("kpc::noun"))), axis=0)
computed_result = wv.similar_by_vector(vector=vector, topn=5)
print(computed_result)
result_file.write(str(computed_result))
result_file.write("\n")

print("pasażer - mężczyzna + kobieta")
result_file.write("pasażer - mężczyzna + kobieta\n")
vector = np.sum((wv.get_vector("pasażer::noun"), wv.get_vector("kobieta::noun"),
                 np.negative(wv.get_vector("mężczyzna::noun"))), axis=0)
computed_result = wv.similar_by_vector(vector=vector, topn=5)
print(computed_result)
result_file.write(str(computed_result))
result_file.write("\n")

print("samochód - droga + rzeka")
result_file.write("samochód - droga + rzeka\n")
vector = np.sum((wv.get_vector("samochód::noun"), wv.get_vector("rzeka::noun"),
                 np.negative(wv.get_vector("droga::noun"))), axis=0)
computed_result = wv.similar_by_vector(vector=vector, topn=5)
print(computed_result)
result_file.write(str(computed_result))
result_file.write("\n")

print("# 5")
wordlist = (
    'szkoda::noun',
    'strata::noun',
    'uszczerbek::noun',
    'szkoda::noun majątkowy::adj',
    'uszczerbek::noun na::prep zdrowie::noun',
    'krzywda::noun',
    'niesprawiedliwość::noun',
    'nieszczęście::noun',
)

highlights = []
for phrase in wordlist:
    try:
        vector = np.sum([wv.get_vector(part) for part in phrase.split()], axis=0)
        highlights.append(vector)
    except KeyError:
        print('{} not in model'.format(phrase))
print('{} highlights found'.format(len(highlights)))
random_vectors = list(map(lambda x: wv.get_vector(x), random.sample(list(wv.vocab.keys()), 1000 - len(highlights))))
processed = TSNE(n_components=2).fit_transform(highlights + random_vectors)

plt.figure(figsize=(10, 10))
plt.title('# 5')
plt.scatter(processed[:len(highlights), 0], processed[:len(highlights), 1])
plt.scatter(processed[len(highlights):, 0], processed[len(highlights):, 1])
plt.savefig('tsne.png')


#IMPORTING REQUIRED HELPER MODULES
import random
import time
import requests
import json
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
#Setting figure size
plt.rcParams["figure.figsize"] = (20,3)

#IMPORTING PYTORCH MODULES
import torch
import torch.nn as nn
import torchvision.models as models
from torchvision import transforms
from torch.utils.data import Dataset , DataLoader

#------------------------------------------------------------------------------------------------------------
#HELPER FUNCTIONS
def load_settings():
    with open('settings.json', 'r') as settings_file:
        settings_data = settings_file.read()

    # parse file
    settings = json.loads(settings_data)
    return settings
def get_children(model):
    """
    INPUT: Model
    OUTPUT : All layers present in the model
    """
    children = list(model.children())
    flatt_children = []
    if children == []:
        return model
    else:
        for child in children:
            try:
                flatt_children.extend(get_children(child))
            except TypeError:
                flatt_children.append(get_children(child))
    return flatt_children

def generate_random_number(num_layers):
    """
    INPUT : Layers of Model
    OUTPUT : Random Layer Number from 0 to len(num_layers) - 2
    """
    return random.randint(0, num_layers-2)

#------------------------------------------------------------------------------------------------------------
#LOADING THE MODEL IN MEMORY
model = models.alexnet(pretrained=True)
model.eval()
layers_of_network = get_children(model)
#------------------------------------------------------------------------------------------------------------
#HEAD NETWORK CLASS
class HeadNet(nn.Module):
    def __init__(self ,layers_of_network , random_layer ):
        super( HeadNet, self ).__init__()
        print("---------------------------------------------------------")
        print("[SPLITTING] the model for head part")
        print("---------------------------------------------------------")
        self.layers_useful = layers_of_network[0:random_layer+1]

    def forward(self , input_tensor):
        print("[COMPUTING]the activation from head part")
        print("---------------------------------------------------------")
        for i in self.layers_useful:
            try:
                input_tensor = i(input_tensor)
            except:
                input_tensor = input_tensor.view(1,-1)
                input_tensor = i(input_tensor)
        return input_tensor

#------------------------------------------------------------------------------------------------------------
# MAIN FUNCTIONS

def single_image_prediction(image_path):
    print("---------------------------------------------------------")
    print(f"[READING] the image {image_path}")
    #PROCESSING THE INPUT IMAGE
    input_image = Image.open(image_path)
    print("---------------------------------------------------------")
    print("[PREPROCESSING] input image")
    preprocess = transforms.Compose([
        transforms.Resize(256) , transforms.CenterCrop(224) ,transforms.ToTensor() , transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    ])
    input_tensor = preprocess(input_image)
    input_batch = input_tensor.unsqueeze(0)
    print("---------------------------------------------------------")
    print("[IMAGE] preprocessed")
    print("---------------------------------------------------------")
    print(f"[TOTAL] layers of network - {len(layers_of_network)}")
    time_inference_client_start = time.time()
    print("---------------------------------------------------------")
    print("[GENERATING] a random number")
    print("---------------------------------------------------------")
    random_layer = generate_random_number(len(layers_of_network))
    print(f"[GENERATED] random number - {random_layer}")
    headnetwork = HeadNet(layers_of_network , random_layer)
    print("[HEAD PREDICTION] ready to be performed")
    print("----------------------------------------------------------")
    with torch.no_grad():
        activation = headnetwork(input_batch)
    print("[SHAPE] of intermediate activations from head")
    print("---------------------------------------------------------")
    print(activation.shape)
    activation = activation.numpy().tolist()
    print("---------------------------------------------------------")
    print("[SENDING] the activations at split to the server")
    print("---------------------------------------------------------")
    time_inference_total_client = time.time() - time_inference_client_start
    data = {'i': random_layer , 'activation' : activation , 'time_client_sends_activation' : time.time()}
    response = requests.post(url+"/tail_prediction", json = data)
    print("[RECEIVED] results from the server")
    print("---------------------------------------------------------")
    result = json.loads(response.text)
    download_time = time.time() - result["time_server_sends_client"]
    print(f"Prediction is {result['category']} with confidence {result['confidence_score']} and inference time on edge {time_inference_total_client} , upload time {result['time_upload']} , inference time on server {result['time_inference_server']} , download time {download_time}")
    print("---------------------------------------------------------")

#------------------------------------------------------------------------------------------------------------
#URL FOR SERVER
url = load_settings()["server_url"]
#------------------------------------------------------------------------------------------------------------
print("Random Split on Single Image ALexnet model")
print("---------------------------------------------------------")
image_path = "test_images/dog.jpg"
single_image_prediction(image_path)


""" Requests to the coinapi.io api """
import os
import requests as r

class CoinApiService():
    """ Class for interactions with IEX cloud API """
    def __init__(self):
        """ Set credentials and URL """
        self.base_url = os.environ.get('COIN_API_BASE_URL')
        self.headers = {'X-CoinApi-Key': os.environ.get('COINAPI_KEY')}

    def list_symbols(self):
        """ Function gets all available symbols from coin API """
        req = r.get(f"{self.base_url}/symbols?filter_asset_id=ETH&filter_exchange_id=KRAKEN", headers=self.headers)
        symbols = req.json()
        symbol_list = [symbol for symbol in symbols]
        return symbol_list

    def symbol_historical(self, symbol_id):
        """ Function gets all available symbols from coin API """
        req = r.get(f"{self.base_url}/ohlcv/{symbol_id}/history?period_id=1DAY&time_start=2017-01-10", headers=self.headers)
        chart = req.json()
        return chart


import sys
import stdio
import math
import random
import stdarray

#NOTE - this program has a bug where the data exceeds the arrays capabilities
#I encountered it rarly and it did get it to happen less often

n = int(sys.argv[1])

m = int(sys.argv[2])

i = 0

People = 0

NumberCheck = 0

PastNumber = 0

CurrentRumorHolder = 0

RumorSpreaders = stdarray.create1D(n, 0)

RumorSpreaders[People] = 0

Yes = 0

TotalPeoplePercentage = 0

AllRunPeople = 0

#we know that if n is 2 or 3 there will be full propagation,
#so we don't need to loop if this is the case

if 3 != n != 2:
    while i < m:
        i += 1
        while People < n:

            Tell = random.randrange(n)
            while Tell == PastNumber or Tell == CurrentRumorHolder:
                Tell = random.randrange(n)
            People += 1
            if Tell in RumorSpreaders:
                break
            RumorSpreaders[People] = Tell

            PastNumber = CurrentRumorHolder
            CurrentRumorHolder = Tell

        TotalPeoplePercentage += People

        AllRunPeople = n * m

        if People == n:
            Yes += 1

#Calculate the percentage of times that there was full propagation

    PercentageOfFullPropagation = ((Yes / m) * 100)

    stdio.write("The Rumor Fully Propagated: ")
    stdio.write(PercentageOfFullPropagation)
    stdio.writeln("% Of The Time")

#calculate the average number of people who heard the rumor

    PercentOfPeopleWhoHeardTheRumor = ((TotalPeoplePercentage / AllRunPeople) * 100)

    stdio.write("Percentage Of People Who Heard The Rumor: ")
    stdio.write(PercentOfPeopleWhoHeardTheRumor)
    stdio.writeln("%")

#here is where we have our premade solutions if n is 2 or 3

if n == 2:
    stdio.writeln("The Rumor Fully Propagated: 100% Of The Time")
    stdio.writeln("Percentage Of People Who Heard The Rumor: 100%")

if n == 3:
    stdio.writeln("The Rumor Fully Propagated: 100% Of The Time")
    stdio.writeln("Percentage Of People Who Heard The Rumor: 100%")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019-10-20 10:53
# @Author  : Frenkie
# @Site    :
# @File    : leetcode_5231.py
# @Software: PyCharm

from typing import List

class Solution:
    def removeSubfolders(self, folder: List[str]) -> List[str]:
        """
        注意：操作数组的方式：
        1、从前往后/从后往前遍历
        2、从前，二次迭代
        3、从前，之前迭代的
        判断是否值得加入
        Python String if "" in ""
        :param folder:
        :return:
        """
        res = set()
        folder.sort()
        def check(f):
            s = f.split('/')[1:]
            tmp = ''
            for i in s:
                tmp += ('/' + i)
                if tmp in res:
                    return False
            return True
        for f in folder:
            if check(f):
                res.add(f)
        return res

if __name__ == '__main__':
    # Python sort排序，
    # 按照期望中的排序方式
    s = ['a', 'abc', 'ab', 'ca', 'cab']
    s.sort()
    print(s)


import os
import sys

import openai
import rich

openai.api_key = os.getenv("KOPYLOT_AUTH_TOKEN", "")

def validate_token() -> None:
    if openai.api_key == "":
        rich.print(
            "[bold red]Error:[/bold red] Please set your OpenAI API key as an environment variable named"
            " KOPYLOT_AUTH_TOKEN"
        )
        sys.exit(1)

def ask_llm(prompt: str, temperature: float = 0.7, max_tokens: int = 2048) -> str:
    validate_token()
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=prompt,
        temperature=temperature,
        max_tokens=max_tokens,
    )

    return str(response.choices[0].text.strip())


from odoo import api, fields, models

class IrAttachment(models.Model):
    _inherit = 'ir.attachment'

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        if args and len(args) == 2:
            model = False
            id = False

            for tup in args:
                if len(tup) == 3:
                    if tup[0] == 'res_model' and tup[2] == 'project.task':
                        model = tup[2]
                    if tup[0] == 'res_id':
                        id = tup[2]

            if model and id:
                if model == 'project.task':
                    task = self.env['project.task'].browse(id)
                    args = ['|', '&', ('res_model', '=', 'sale.order'), ('res_id', '=', task.sale_order_id.id), '&'] + args

        return super(IrAttachment, self).search(args, offset, limit, order, count)


import os

from disnake.ext import commands

from bot import SomeBot
from util.code import execute_code
from util.errors import format_exception

class OwnerCommands(commands.Cog):
    def __init__(self, bot: SomeBot):
        self.bot = bot

    @commands.command(name="reload")
    @commands.is_owner()
    async def reload(self, ctx: commands.Context):
        os.system("git pull")

        for cog in self.bot.cog_list:
            self.bot.reload_extension(f"cogs.{cog}")

        await ctx.message.add_reaction("✔")

    @commands.command(name="eval")
    @commands.is_owner()
    async def eval_code(self, ctx: commands.Context, *, stuff: str):
        stuff = stuff.strip(" `\n")

        if stuff.startswith("py"):
            stuff = stuff[2:]

        try:
            result = await execute_code(stuff, {"bot": self.bot, "ctx": ctx})

            await ctx.reply(f"```\n{str(result).replace('```', '｀｀｀')[:2000-9]}```")
        except Exception as e:
            await ctx.reply(f"```py\n{format_exception(e).replace('```', '｀｀｀')[:2000-9]}```")

def setup(bot: SomeBot):
    bot.add_cog(OwnerCommands(bot))


class Solution:
    def isMatch(self, s: str, p: str) -> bool:

        # to indicate lengths including empty string
        sn = len(s) + 1
        pn = len(p) + 1

        # dp board
        dp = [[False] * (pn) for _ in range(sn)] # i = s, j = p

        dp[0][0] = True # empty <> empty: always True

        # handling * located right after empty string (* includes empty string)
        for j in range(1, pn):
            if p[j-1] != '*':
                break
            dp[0][j] = True

        # fill the rest of the board
        for i in range(1, sn):
            for j in range(1, pn):
                if p[j-1] in {'?', s[i-1]}:
                    dp[i][j] = dp[i-1][j-1]
                elif p[j-1] == '*':
                    dp[i][j] = dp[i-1][j] or dp[i][j-1]

        return dp[-1][-1]


# ---
# jupyter:
#   jupytext:
#     cell_metadata_filter: all
#     notebook_metadata_filter: all,-language_info
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.3.3
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# ## AMP prescribing as recommended by the [NHS Dictionary of medicines and devices](https://ebmdatalab.net/what-is-the-dmd-the-nhs-dictionary-of-medicines-and-devices/)
#
# **THIS IS A WORK IN PROGRESS**
#
# The UK has over the last few decades encouraged generic prescribing for reasons of cost containment and safety. However there are important exceptions where generic prescribing is not ideal e.g. narrow therapeutic index where even slight variations between brands could cause adverse clinical responses. On OpenPrescribing we have some measures of generic prescribing where brand prescribing is recommended
#
# - [ciclosporin and tacrolimus](https://openprescribing.net/measure/ciclosporin/)
# - [diltiazem >60mg](https://openprescribing.net/measure/diltiazem/)
#
# We have found that [12.3% of prescriptions for diltiazem, tacrolimus and ciclosporin breach prescribing guidance](https://openprescribing.net/measure/diltiazem/) on brand prescribing in a paper accted in JMIR.
#
# Various organisations make recommendations about brand prescribing in the NHS including the [NHS dictionary of medicines and devices (dm+d)](https://ebmdatalab.net/what-is-the-dmd-the-nhs-dictionary-of-medicines-and-devices/) which is the mandated drug dictionary for electronic systems in the NHS. In the field `prescribing status` the dm+d can assign a value `caution - AMP level prescribing advised` which means you should prescribe by brand. This is assigned to 229 VMPs.
#
# In this notebook we will set out to investigate brand prescribing across all products.

#import libraries required for analysis
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from ebmdatalab import bq, charts, maps
import os

# +
sql = '''
SELECT
  month,
  pct,
  bnf_name,
  bnf_code,
  SUM(items) AS total_items
FROM
hscic.normalised_prescribing_standard AS rx
INNER JOIN
hscic.practices AS prac
ON
rx.practice = prac.code
JOIN
  hscic.ccgs AS ccgs
ON
rx.pct=ccgs.code
WHERE
  prac.setting = 4
  AND
  ccgs.org_type='CCG'
  AND
  bnf_code IN (
  SELECT
    DISTINCT(bnf_code)
  FROM
    ebmdatalab.brian.amp_recommended
     )
GROUP BY
rx.month,
rx.pct,
rx.bnf_code,
rx.bnf_name
ORDER BY
month
'''

df_amp_recommended = bq.cached_read(sql, csv_path=os.path.join('..','data','df_amp_recommended.zip'))
#df_amp_recommended = bq.cached_read(sql, csv_path=os.path.join('..','data','df_amp_recommended.csv'))
df_amp_recommended['month'] = df_amp_recommended['month'].astype('datetime64[ns]')
df_amp_recommended.head(3)
# -

#lets graph to see the total number of items over time
df_amp_recommended.groupby("month")['total_items'].sum().plot(kind='line', title="Total items where AMP recommended by NHS dm+d")
plt.ylim(0, )

#create dataframe with only generically prescribed items
df_generic = df_amp_recommended.loc[df_amp_recommended["bnf_code"].str.contains('AA\w{4}$')]
df_generic.head()

#output unique BNF codes to inspect for accuracy
df_generic.bnf_code.unique()

#plot breaches
df_generic.groupby("month")['total_items'].sum().plot(kind='line', title="Total items where AMP recommended by NHS dm+d but prescribed generically \n in breach of guidance")
plt.ylim(0, )

#inspect top 25
df_generic.groupby(['bnf_code', 'bnf_name']).sum().reset_index().sort_values(by = 'total_items', ascending = False).head(25)

df_generic_ccg = df_generic.groupby(['month', 'pct']).sum().reset_index()
df_generic_ccg .head(3)

df_amp_recommended_ccg = df_amp_recommended.groupby(['month', 'pct']).sum().reset_index()
df_amp_recommended_ccg.head(3)

df_measure = pd.merge(df_generic_ccg, df_amp_recommended_ccg,  how='left', left_on=['month','pct'], right_on = ['month','pct'], suffixes=("_generic_rx", "_all_rx_rec_amp"))
df_measure["measure_value"] = 100*(df_measure.total_items_generic_rx / df_measure.total_items_all_rx_rec_amp).fillna(0)
df_measure.head()

# +
charts.deciles_chart(
    df_measure,
    period_column='month',
    column='measure_value',
    title=" CCG variation - Generic prescriptions \n in breach of dm+d brand prescribing recommendations",
    ylabel=" % ",
    show_outer_percentiles=True,
    show_legend=True
)

#add in example CCG (Devon)
df_subject = df_measure.loc[df_measure['pct'] == '15N']
plt.plot(df_subject['month'], df_subject['measure_value'], 'r--')

plt.ylim(0, 100)
plt.show()
# -

#create choropeth map
plt.figure(figsize=(12, 7))
last_year_df_measure = df_measure.loc[(df_measure['month'] >= '2020-04-01') & (df_measure['month'] <= '2020-12-01')]
plt = maps.ccg_map(last_year_df_measure, title="Generic prescription in breach of brand prescribing recommendations  \n CCG ", column='measure_value', separate_london=False)
plt.show()


import librosa
import librosa.display
import matplotlib.pyplot as plt
import base64
import argparse
import numpy as np

# constant parameter
bands = 60
frames = 60
hop_length = 512
n_fft = 1024

# Running function parameters
ap = argparse.ArgumentParser()
ap.add_argument('-s','--sound',required=True) #lokasi folder sound file, hingga tanda "/" akhir
ap.add_argument('-n','--node',required=True) #nomor node
args = vars(ap.parse_args())

def create_mel_spectrogram(file_name, node):
  window_size = hop_length * (frames - 1)
  log_specgrams = []
  file_loc = file_name + "suara" + node + ".m4a"
  data,sample_rate = librosa.load(file_loc)
  sound_clip, _ = librosa.load(file_loc, sr=sample_rate)
  # Plotting the short-time Fourier Transformation
  plt.figure(figsize=(20, 5))
  # Using librosa.display.specshow() to create our spectrogram
  melspec = librosa.feature.melspectrogram(sound_clip, n_mels=bands, sr=sample_rate, n_fft=n_fft, hop_length=hop_length)
  logspec = librosa.power_to_db(melspec, ref=np.max)
  librosa.display.specshow(logspec,sr=sample_rate,x_axis='time',y_axis='hz',cmap='magma', hop_length=hop_length)
  plt.colorbar(label='Amplitude')
  plt.title('Spectrogram (amp)', fontdict=dict(size=18))
  plt.xlabel('Time', fontdict=dict(size=15))
  plt.ylabel('Frequency', fontdict=dict(size=15))
  plt.savefig(file_name+"Spec"+node+".png")

create_mel_spectrogram(args["sound"], args["node"])
file_ = args["sound"]+"Spec"+args["node"]+".png"

with open(file_, "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

print(encoded_string)


import torch
import math
from typing import List

def _get_warmup_factor_at_iter(
    method: str, iter: int, warmup_iters: int, warmup_factor: float
) -> float:
    """
    Return the learning rate warmup factor at a specific iteration.
    See :paper:`ImageNet in 1h` for more details.
    Args:
        method (str): warmup method; either "constant" or "linear".
        iter (int): iteration at which to calculate the warmup factor.
        warmup_iters (int): the number of warmup iterations.
        warmup_factor (float): the base warmup factor (the meaning changes according
            to the method used).
    Returns:
        float: the effective warmup factor at the given iteration.
    """
    if iter >= warmup_iters:
        return 1.0

    if method == "constant":
        return warmup_factor
    elif method == "linear":
        alpha = iter / warmup_iters
        return warmup_factor * (1 - alpha) + alpha
    else:
        raise ValueError("Unknown warmup method: {}".format(method))

class WarmupPolyLR(torch.optim.lr_scheduler._LRScheduler):
    """
    Poly learning rate schedule used to train DeepLab.
    Paper: DeepLab: Semantic Image Segmentation with Deep Convolutional Nets,
        Atrous Convolution, and Fully Connected CRFs.
    Reference: https://github.com/tensorflow/models/blob/21b73d22f3ed05b650e85ac50849408dd36de32e/research/deeplab/utils/train_utils.py#L337  # noqa
    """

    def __init__(
        self,
        optimizer: torch.optim.Optimizer,
        max_iters: int,
        warmup_factor: float = 0.001,
        warmup_iters: int = 1000,
        warmup_method: str = "linear",
        last_epoch: int = -1,
        power: float = 0.9,
        constant_ending: float = 0.0,
    ):
        self.max_iters = max_iters
        self.warmup_factor = warmup_factor
        self.warmup_iters = warmup_iters
        self.warmup_method = warmup_method
        self.power = power
        self.constant_ending = constant_ending
        super().__init__(optimizer, last_epoch)

    def get_lr(self) -> List[float]:
        warmup_factor = _get_warmup_factor_at_iter(
            self.warmup_method, self.last_epoch, self.warmup_iters, self.warmup_factor
        )
        if self.constant_ending > 0 and warmup_factor == 1.0:
            # Constant ending lr.
            if (
                math.pow((1.0 - self.last_epoch / self.max_iters), self.power)
                < self.constant_ending
            ):
                return [base_lr * self.constant_ending for base_lr in self.base_lrs]
        return [
            base_lr * warmup_factor * math.pow((1.0 - self.last_epoch / self.max_iters), self.power)
            for base_lr in self.base_lrs
        ]

    def _compute_values(self) -> List[float]:
        # The new interface
        return self.get_lr()


"""Python controller"""

# You may need to import some classes of the controller module. Ex:
#  from controller import Robot, LED, DistanceSensor
import numpy as np
import cmc_pylog as pylog
from controller import Supervisor
from cmc_robot import SalamanderCMC

class RobotResetControl(object):
    """Robot reset control"""

    def __init__(self, world, n_joints):
        super(RobotResetControl, self).__init__()
        self.world = world
        self.n_joints = n_joints
        self.salamander = self.world.getFromDef("SALAMANDER")
        self.initial_position = np.array(
            self.salamander.getField("translation").getSFVec3f()
        )
        self.initial_rotation = np.array(
            self.salamander.getField("rotation").getSFRotation()
        )
        self.solid_links = [
            self.world.getFromDef("SOLID_{}".format(i+1))
            for i in range(10)
        ]
        self.hinge_joints = [
            self.world.getFromDef("JOINT_PARAM_{}".format(i+1))
            for i in range(10)
        ]

    def reset(self):
        """Reset state"""
        self.reset_pose()
        self.reset_internal()

    def reset_pose(self):
        """Reset robot pose"""
        self.salamander.getField("translation").setSFVec3f(
            self.initial_position.tolist()
        )
        self.salamander.getField("rotation").setSFRotation(
            self.initial_rotation.tolist()
        )

    def reset_internal(self):
        """Reset intenal links and joints states"""
        for i in range(self.n_joints):
            self.hinge_joints[i].getField("position").setSFFloat(0)
            # self.hinge_joints[i].setVelocity([0, 0, 0, 0, 0, 0])
            self.solid_links[i].setVelocity([0, 0, 0, 0, 0, 0])

def run_simulation(world, parameters, timestep, n_iterations, logs):
    """Run simulation"""

    # Set parameters
    pylog.info((
        "Running new simulation:"
        "\n  - Amplitude: {}"
        "\n  - Phase lag: {}"
        "\n  - Turn: {}"
    ).format(parameters[0], parameters[1], parameters[2]))

    # Setup salamander control
    salamander = SalamanderCMC(
        world,
        n_iterations,
        logs=logs,
        freqs=parameters[0],
        amplitudes=parameters[1],
        phase_lag=parameters[2],
        turn=parameters[3]
    )

    # Simulation MAIN LOOP
    iteration = 0
    while world.step(timestep) != -1:
        iteration += 1
        if iteration >= n_iterations:
            break
        salamander.step()

    # Log data
    pylog.info("Logging simulation data to {}".format(logs))
    salamander.log.save_data()

def main():
    """Main"""

    # Duration of each simulation
    simulation_duration = 10

    # Get supervisor to take over the world
    world = Supervisor()
    n_joints = 10
    timestep = int(world.getBasicTimeStep())
    #freqs = 1

    # Get and control initial state of salamander
    reset = RobotResetControl(world, n_joints)

    ''' Simulation setup - (choose an question to run)'''

    question = '8d' # 8a, 8b, 8c, 8d

    if question == '8a':
        # Experiment 0
        freqs1 = np.ones(20)        # 20 amplitudes to be specified
        amplitude1 = [1/10,1/10]    # [Rhead,Rtail] (specify head and tail amplitude)
        phase_lag1 = 2*np.pi/10     # Positive = forward, negative = backward
        turn1 = 0                   # Positive = left, negative = right (must not be too large)

        parameter_set = [
            [freqs1, amplitude1, phase_lag1, turn1]
        ]

    elif question == '8b':
        pass

    elif question == '8c':
        # Experiment 0
        freqs0 = np.ones(20)
        amplitude0 = [0,1/5]        # Linear distribution of amplitude
        phase_lag0 = 2*np.pi/10
        turn0 = 0

        parameter_set = [
            [freqs0, amplitude0, phase_lag0, turn0]
        ]

    elif question == '8d':
        # Experiment 0
        freqs0 = np.ones(20)
        amplitude0 = [0,1/5]        # Linear distribution of amplitude
        phase_lag0 = -2*np.pi/10    # Swimming backward
        turn0 = 0

        # Experiment 1
        freqs1 = np.ones(20)
        amplitude1 = [0,1/5]        # Linear distribution of amplitude
        phase_lag1 = 2*np.pi/10
        turn1 = 0.1                 # turning left

        parameter_set = [
            [freqs0, amplitude0, phase_lag0, turn0],
            [freqs1, amplitude1, phase_lag1, turn1]
        ]

    else:
        parameter_set = []
        print('ERROR - Invalid question selected')

    # Store the data of the specified question
    for simulation_i, parameters in enumerate(parameter_set):
        reset.reset()
        run_simulation(
            world,
            parameters,
            timestep,
            int(1000*simulation_duration/timestep),
            logs="./logs/" + question + "/simulation_{}.npz".format(simulation_i) #logs="./logs/example/simulation_{}.npz".format(simulation_i)
        )

    # Pause
    world.simulationSetMode(world.SIMULATION_MODE_PAUSE)
    world.worldReload()
    pylog.info("Simulations complete")
    #world.simulationQuit(0)

if __name__ == '__main__':
    main()


from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models
import time,os
from . import cate_views,user_views
from shop.settings import BASE_DIR
from django.core.paginator import Paginator

# 添加
def addgoods(request):
    # 查询所有的分类  进行返回
    types = cate_views.tab()
    return render(request,'myadmin/goods/addgoods.html',{'types':types})

# 添加数据
def goodsinsert(request):

     # 接受用户的信息
    ginfo = request.POST.dict()
    ginfo.pop('csrfmiddlewaretoken')
    # print(ginfo)

    file = request.FILES.get('g_url')
    # print(file)
    if not file:
        return HttpResponse('<script>alert("请选择图片");history.back(-1)</script>')

    # 调图片上传
    g_url=user_views.upload(file)
    # print(g_url)
    try:
        # 入库
        goods = models.Goods()
        goods.title=ginfo['title']
        goods.ordernum=ginfo['ordernum']
        goods.g_url=g_url
        goods.price=ginfo['price']
        goods.ginfo=ginfo['ginfo']
        goods.cateid=models.Cates.objects.get(id=ginfo['cateid'])
        goods.save()

        # 返回
        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_addgoods')+'"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");history.back(-1)</script>')

def goodslist(request):
    goods = models.Goods.objects.all().exclude(status=3)
    # 接受类型
    types = request.GET.get('type')
    print(types)
    # 接受关键字
    search = request.GET.get('search')
    print(search)
    # 判断用是否搜索内容
    if types:
        from django.db.models import Q
        if types=='all':
            #根据id username phone
            # select * from myadmin_users where id like %search% or username like %search% or phone like %search%
            # from django.db.models import Q
            goods = models.Goods.objects.filter(Q(title__contains=search)|Q(id__contains=search)|Q(price__contains=search))
    # 实例化分页对象
    p = Paginator(goods,3)
    print(p)

    #一共可以分多少页
    sumpage=p.num_pages
    print(sumpage)

    # 取第几页的数据
     # 接受用户的页码
    page = int(request.GET.get('p',1))
    # print(page)
    # 第几页的数据
    page1 = p.page(page)
    # print(page1)

    # 判断 如果用输入的页码<=3 显示前五个页码
    if page<=3:
        # 页码的迭代序列  [1,2,3,4,5,6,7]
        prange = p.page_range[:5]
    elif page+2>=sumpage:
        prange = p.page_range[-5:]
    else:
        prange = p.page_range[page-3:page+2]

    return render(request,'myadmin/goods/list.html',{'goods':page1,'prange':prange,'page':page,'sumpage':sumpage})

#删除用户
def delgoods(request):
    uid = request.GET.get('uid')
    # print(uid)

    gl=models.Goods.objects.get(id=uid)
    # print(gl)
    gl.status=3
    # print(gl)
    gl.save()

    return redirect(reverse('myadmin_goodslist'))

# 修改商品
def editgoods(request):
    # get goods id
    uid = request.GET.get('uid')
    # print(uid)
    # 判断是get还是post
    if request.method=='GET':
        egs=models.Goods.objects.get(id=uid)
        types = cate_views.tab()
        return render(request,'myadmin/goods/edit.html',{'egs':egs,'types':types})
    elif request.method=='POST':
        # 获取用户的提交信息
        userinfo = request.POST.dict()
        # 更新数据
        uinfo = models.Goods.objects.get(id=uid)
        uinfo.title=userinfo['title']
        uinfo.price=userinfo['price']
        uinfo.ordernum=userinfo['ordernum']
        # 判断头像有没有上传
        file = request.FILES.get('g_url')
        if file:
            # 右头像上传，要吧旧投头像删除
            # /dajngo07/py17/shop    ./static/pics/1547686265.6370358.png
            os.remove('.'+uinfo.g_url)
            g_url=user_views.uuload(file)
            uinfo.g_url=g_url
        uinfo.save()
        return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myadmin_goodslist')+'"</script>')