import os
import datetime
import numpy as np
import pandas as pd

from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator, FixedLocator
from fig1_plot import plot_data
# ---------------------------
def run(win2_sparse, win2_dense, win4_sparse, win4_dense, win6_sparse, win6_dense, figname):

    plt.rcParams.update({'font.size': 10})
    fig, axes = plt.subplots(1, 3, figsize=[8, 2.5], dpi=300)

    prop_cycle = plt.rcParams['axes.prop_cycle']
    colors = prop_cycle.by_key()['color']
    # ---------------------------
    fnames = [[win2_sparse, win2_dense],
              [win4_sparse, win4_dense],
              [win6_sparse, win6_dense]]

    for i, window_size in enumerate([2, 4, 6]):
        for j, sampling in enumerate(["sparse", "dense"]):
            plot_data(axes[i], None, colors[j], fnames[i][j], linewidth=1, alpha=0.15)
            plot_data(axes[i], None, "k", fnames[i][j], linewidth=0.5, alpha=1, n_trial=1)     ## representative trajectory
            axes[i].plot([np.nan, np.nan], c=colors[j], label=sampling, linewidth=1, alpha=0.7)

        axes[i].legend()#title=f"samples per {window_size}-day window")
        axes[i].xaxis.set_major_locator(FixedLocator(np.arange(20, 168.1, 24)))  # FixedLocator
        axes[i].xaxis.set_minor_locator(FixedLocator(np.arange(20, 168.1, 8)))  # FixedLocator
        axes[i].set_xlim([20, 168])
        axes[i].grid(which = "both")

    # axis label

    axes[0].set_ylabel("Number of\nsegregating sites")
    axes[0].set_xlabel('Days post index case')
    axes[1].set_xlabel('Days post index case')
    axes[2].set_xlabel('Days post index case')

    axes[0].yaxis.set_major_locator(FixedLocator(np.arange(0, 300, 25)))  # FixedLocator
    axes[1].yaxis.set_major_locator(FixedLocator(np.arange(0, 300, 25)))  # FixedLocator
    axes[2].yaxis.set_major_locator(FixedLocator(np.arange(0, 300, 25)))  # FixedLocator

    ## add subplot label
    labels = 'ABC'.lower()
    for i, label in enumerate(labels):
        if i == 0:
            axes[i].text(-0.22, 1.1, label, transform=axes[i].transAxes, fontsize=16, fontweight='bold', va='top',
                         ha='left')
            axes[i].set_ylim([0, 300])
        else:
            axes[i].text(-0.18, 1.1, label, transform=axes[i].transAxes, fontsize=16, fontweight='bold', va='top',
                         ha='left')
            axes[i].set_ylim([0, 300])

    ## save figure
    fig.tight_layout(pad=0.5)
    fig.savefig(f'manuscript figures/pdf/{figname}.pdf')
    fig.savefig(f'manuscript figures/png/{figname}.png')

    fig.clf()
    plt.cla()

    return

if __name__ == "__main__":
    import os
    import argparse

    if os.getcwd().find("manuscript_figure_script") == -1:
        parser = argparse.ArgumentParser()
        parser.add_argument('--figname', type=str, default="figureS1")
        parser.add_argument('--win2_sparse', type=str)
        parser.add_argument('--win2_dense' , type=str)
        parser.add_argument('--win4_sparse', type=str)
        parser.add_argument('--win4_dense' , type=str)
        parser.add_argument('--win6_sparse', type=str)
        parser.add_argument('--win6_dense' , type=str)

        args = parser.parse_args()

    else:
        os.chdir(os.getcwd().replace("manuscript_figure_script", ""))
        parser = argparse.ArgumentParser()
        args = parser.parse_args()
        args.figname = "figureS1"

        args.win2_sparse = "simulated_data/simpleSEIR_R0=16e-1_mu2e-1/!!!!!!!_trial##_segsites.tsv"
        args.win2_dense  = "simulated_data/simpleSEIR_R0=16e-1_mu2e-1/!!!!!!!_trial##_segsites.tsv"
        args.win4_sparse = "simulated_data/simpleSEIR_R0=16e-1_mu2e-1/!!!!!!!_trial##_segsites.tsv"
        args.win4_dense  = "simulated_data/simpleSEIR_R0=16e-1_mu2e-1/!!!!!!!_trial##_segsites.tsv"
        args.win6_sparse = "simulated_data/simpleSEIR_R0=16e-1_mu2e-1/!!!!!!!_trial##_segsites.tsv"
        args.win6_dense  = "simulated_data/simpleSEIR_R0=16e-1_mu2e-1/!!!!!!!_trial##_segsites.tsv"

    print(args)
    run(args.win2_sparse,
        args.win2_dense,
        args.win4_sparse,
        args.win4_dense,
        args.win6_sparse,
        args.win6_dense,
        args.figname)


from random import choice
class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.nums = nums

    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        res = []
        for i in enumerate(self.nums):
            if i[1] == target:
                res.append(i[0])
        return choice(res)

# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)

398. Random Pick Index/398. Random Pick Index (AC).py


import socket

ip_dest = '49.235.72.162'
port_dest = 20201
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((ip_dest,port_dest))

while True:
    str = input("请输入给服务发送的数据：")
    data = str +'\n'
    client.send(data.encode("utf-8"))
    info = client.recv(1024)
    print("服务器说:"+info.decode("utf-8"))

网络编程/TCP编程/2、客户端与服务器的交互/client.py


def ispotenza2(n):
    if(n==0):
        return False
    while(n != 1):
        n = n/2
        if (n%2 != 0 and n != 1):
            return False
    return True

n = int(input())
l = []
i = 0
potenze2 = True

while n != 0:
    l.append(n)
    n = int(input())

while potenze2 and i < len(l):
    if (not ispotenza2(l[i])):
        potenze2 = False
    i += 1

if (potenze2):
    print("SI", end='')
else:
    print("NO", end='')


import torchvision.transforms as T
try:
    from torchvision.transforms import GaussianBlur
except ImportError:
    from .gaussian_blur import GaussianBlur
    T.GaussianBlur = GaussianBlur

imagenet_mean_std = [[0.485, 0.456, 0.406],[0.229, 0.224, 0.225]]

class SimCLRTransform():
    def __init__(self, image_size, mean_std=imagenet_mean_std, s=1.0):
        image_size = 224 if image_size is None else image_size
        self.transform = T.Compose([
            T.RandomResizedCrop(image_size, scale=(0.2, 1.0)),
            T.RandomHorizontalFlip(),
            T.RandomApply([T.ColorJitter(0.8*s,0.8*s,0.8*s,0.2*s)], p=0.8),
            T.RandomGrayscale(p=0.2),
            T.RandomApply([T.GaussianBlur(kernel_size=image_size//20*2+1, sigma=(0.1, 2.0))], p=0.5),
            # We blur the image 50% of the time using a Gaussian kernel. We randomly sample σ ∈ [0.1, 2.0], and the kernel size is set to be 10% of the image height/width.
            T.ToTensor(),
            T.Normalize(*mean_std)
        ])
    def __call__(self, x):
        x1 = self.transform(x)
        x2 = self.transform(x)
        return x1, x2


from sys import stdin
from random import randint

# 초등학교 알고리즘

def elementary_mult(a, b):
    longer_num, shorter_num = max(a, b), min(a, b)
    longer_num, shorter_num = str(longer_num), str(shorter_num)
    longer_num_len, shorter_num_len = len(longer_num), len(shorter_num)
    computing_que = [[0] * longer_num_len for i in range(shorter_num_len)]

    for idx in range(shorter_num_len - 1, -1, -1):
        current_numi = shorter_num[idx]
        for jdx in range(longer_num_len - 1, -1, -1):
            current_numj = longer_num[jdx]
            computing_que[shorter_num_len - 1 - idx][longer_num_len - 1 - jdx] = int(current_numi) * int(current_numj)

    total_sum = 0
    for i in range(len(computing_que)):
        for j in range(len(computing_que[i])):
            temp = (computing_que[i][j] * (pow(10, i))) * pow(10, j)
            total_sum += temp
    return total_sum

def karatsuba_mult(a, b):
    a, b = str(a), str(b)
    if len(b) > len(a):
        a, b = b, a

        diff = len(a) - len(b)
        b = '0' * diff + b
    if a == 0 or b == 0:
        return 0
    if len(a) < 50:
        return elementary_mult(a, b)

    a1, a0 = a[:len(a) // 2], a[len(a) // 2:]
    b1, b0 = b[:len(b) // 2], b[len(b) // 2:]
    z2 = karatsuba_mult(a1 * b1)
    z0 = karatsuba_mult(a0, b0)
    z1 = karatsuba_mult((a0 + a1) * (b0 + b1)) - z0 - z2
    total_sum = int(z2 + '0' * len(a) // 2) + int(z1 + '0' * len(a) // 4) + z0
    return total_sum

a, b = randint(1000, 1000000000), randint(1000, 1000000000)
result = elementary_mult(a, b)
kara_result = karatsuba_mult(a, b)
print(f'ele => {a} * {b} = {result}  check: {result == a * b}\nkara => {a} * {b} = {kara_result}   check: {kara_result == a * b}')

소스 코드/7. 분할 정복/sAp00n/ex7.4) 카라츠바의 빠른 곱셈 알고리즘.py

ex7.4) 카라츠바의 빠른 곱셈 알고리즘.py


import argparse
import sys
from typing import Dict

from kenning.cli.autocompletion import configure_autocomplete
from kenning.cli.config import (
    AVAILABLE_COMMANDS,
    MAP_COMMAND_TO_SCENARIO,
    SUB_DEST_FORM,
    setup_base_parser,
)
from kenning.cli.parser import (
    Parser,
    ParserHelpException,
    print_help_from_parsers,
)
from kenning.utils.excepthook import (
    MissingKenningDependencies,
    find_missing_optional_dependency,
)
from kenning.utils.logger import KLogger

def main():
    """
    The entrypoint of Kenning CLI.

    Creates and manages parsers, runs subcommands, and handle errors.
    """
    verbosity = "WARNING"
    if (
        "--verbosity" in sys.argv
        and len(sys.argv) > sys.argv.index("--verbosity") + 1
    ):
        verbosity = sys.argv[sys.argv.index("--verbosity") + 1]
    KLogger.configure()
    KLogger.set_verbosity(level=verbosity)
    configure_autocomplete()
    parser, parsers = setup_base_parser()

    # Get only subcommands and help
    i = 1
    while i < len(sys.argv) and sys.argv[i] in AVAILABLE_COMMANDS:
        i += 1

    # Parse subcommands and help
    args, rem = parser.parse_known_args(sys.argv[1:i])
    args, rem = parser.parse_known_args(args=rem, namespace=args)
    rem += sys.argv[i:]

    # Retrieve parsed subcommands
    i = 0
    subcommands = []
    while getattr(args, SUB_DEST_FORM.format(i), None) is not None:
        subcommands.append(getattr(args, SUB_DEST_FORM.format(i)))
        i += 1

    if not subcommands:
        parser.print_help()
        if rem:
            parser.exit(
                2,
                f"{parser.prog}: error: '{rem[0]}' doesn't match any subcommand",  # noqa: E501
            )
        return

    # Creating parent-parsers from scenarios and completing description
    groups = {}
    parse_all = True
    used_configs = set()
    parents, description = [], []
    seq_description = len(subcommands) > 1
    if seq_description:
        description.append("Running in sequence:")
    for subcommand in subcommands:
        scenario = MAP_COMMAND_TO_SCENARIO[subcommand]
        if isinstance(scenario.description, Dict):
            desc = scenario.description[subcommand]
        else:
            desc = scenario.description[1:]
        description.append(("- " if seq_description else "") + desc)
        if scenario.configure_parser not in used_configs:
            parents.append(
                scenario.configure_parser(types=subcommands, groups=groups)[0]
            )
            used_configs.add(scenario.configure_parser)
            parse_all = parse_all and scenario.parse_all
    description = "\n".join(description)

    # The main parser without subcommands
    parser = Parser(
        "kenning " + " ".join(subcommands),
        conflict_handler="resolve",
        parents=parents,
        description=description,
        add_help=False,
    )

    def _print_help():
        """
        Prints help message for non sequenced subcommands.
        """
        print_help_from_parsers(
            "kenning " + " ".join(subcommands),
            [parsers[tuple(subcommands)], parser],
            description,
        )

    # Print help, including possible subcommands
    if args.help:
        _print_help()
        return

    errors = []
    # Parse arguments
    if parse_all:
        try:
            args = parser.parse_args(
                args=sys.argv[1 + len(subcommands) :], namespace=args
            )
        except ParserHelpException:
            args.help = True
        if args.help:
            _print_help()
            return
        rem = []
    else:
        # Parse only known args if scenario will add more arguments
        try:
            args, rem = parser.parse_known_args(
                sys.argv[1 + len(subcommands) :], namespace=args
            )
        except ParserHelpException as ex:
            errors.append(ex.error)

    # Run subcommands
    used_functions = set()
    for subcommand in subcommands:
        run = MAP_COMMAND_TO_SCENARIO[subcommand].run
        if run in used_functions:
            continue
        try:
            try:
                result = run(args, not_parsed=rem)
                if result:
                    parser.error(
                        f"`{subcommand}` subcommand did not end successfully",
                        print_usage=False,
                    )
            except ModuleNotFoundError as er:
                extras = find_missing_optional_dependency(er.name)
                if not extras:
                    raise
                er = MissingKenningDependencies(
                    name=er.name, path=er.path, optional_dependencies=extras
                )
                raise

            except argparse.ArgumentError as er:
                parser.error(er.message)
                return 2
        except ParserHelpException as ex:
            # Prepare combined errors
            if ex.error is not None:
                errors.append(ex.error)
            if len(errors) > 1:
                ex.error = "\n"
                for error in errors:
                    ex.error += f"- {error}\n"
            elif errors:
                ex.error = errors[0]
            # Print help with errors
            ex.print(
                parser,
                [parsers[tuple(subcommands)], parser],
                description,
            )
            return

        used_functions.add(run)


from unicodedata import name
from django.test import TestCase

from .models import Destiny

class TesteCreateDestiny(TestCase):

    def setUp(self):
        Destiny.objects.create(
        name = 'Minas',
        state = 'MG',
        city = 'Ibié'
        )

    def test_novo_destino_criado(self):
        destiny = Destiny.objects.get(name='Minas')
        self.assertEquals(destiny.__str__(), 'Minas: Ibié/MG')
        self.assertEquals(destiny.city_state(), 'Ibié/MG')

        print(
            'Nome:', destiny.name,'\n'
            'Estado:', destiny.state,'\n'
            'Cidade:', destiny.city,'\n'
        )


import sys
import heapq
input = sys.stdin.readline
INF = int(1e9)

n = int(input())
graph = [[] for i in range(n+1)]
distance = [INF]*(n+1)
G = []

for i in range(n):
    G.append(list(map(int, input().split())))

for i in range(n):
    for j in range(n):
        if G[i][j] == 1:
            graph[i].append((j, 1))
        else :
            graph[i].append((j, INF))

def dijkstra(start):
    q = []
    heapq.heappush(q, (INF, start))
    distance[start] = INF
    while q:
        dist, now = heapq.heappop(q)
        if distance[now]<dist :
            continue
        for i in graph[now]:
            cost = 1
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                heapq.heappush(q, (cost, i[0]))

for i in range(n):
    distance = [INF]*(n+1)
    dijkstra(i)
    for j in range(n):
        if distance[j]==INF:
            print(0, end=' ')
        else :
            print(1, end=' ')
    print()


Registro_de_bandas = []
opcion = 0

while opcion != 5:

  agrupacion = {}

  print("*_*_*_*_* FESTIVAL DE METAL *_*_*_*_*")
  print("1. Ingresar una banda")
  print("2. Mostrar todas las bandas")
  print("3. Cambiar hora de presentación")
  print("4. Retirar una banda")
  print("5. Salir.")
  opcion = int(input("Digite una opción: "))

  if opcion == 1:
    agrupacion["nombre"] = input("Digite el nombre de la banda: ")
    agrupacion["id"] = int(input("Digite el id de la banda: "))
    agrupacion["genero"] = input("Que genero tocá? R/= ")
    agrupacion["hora_presentacion"] = input("Digite la hora de presentación (HH:mm): ")
    agrupacion["presentado"] = input("¿La banda ya se presento?: ")
    agrupacion["valor_pago"] = input("Valor a pagar: ")

    if agrupacion["presentado"].lower() == "si":
      agrupacion["presentado"] = True
    else:
      agrupacion["presentado"] = False

    Registro_de_bandas.append(agrupacion)

  elif opcion == 2:
    for agrupacion in Registro_de_bandas:
      if not agrupacion["presentado"]:
        print(f"La agrupación {agrupacion['nombre']} no se ha presentado")

  elif opcion == 3:
    for agrupacion in Registro_de_bandas:
      if not agrupacion["presentado"]:
        nombre = agrupacion["nombre"]
        print(f"Se cambiará la hora de la agrupación {nombre}")
        agrupacion["hora_presentacion"] = input(f"Digite la nueva hora de presentación: ")

  elif opcion == 4:
    for agrupacion in Registro_de_bandas:
      if not agrupacion["presentado"]:
        nombre = agrupacion["nombre"]
        Registro_de_bandas.remove(agrupacion)

print("Vuelva pronto")


import io
def add_rating(place, rating):
    """given the name of a place and a rating adds a rating to the rating.txt file for the place"""
    with open('rating.txt', 'r') as file:
        data = file.readlines()
    for i in range(len(data)):
        if place in data[i]:
            data[i] = data[i] + rating
    with open('rating.txt', 'w') as file:
        file.writelines(data)

def get_average_rating(place)->float:
    """given the name of a place returns the average rating from the rating.txt file"""
    with open('rating.txt', 'r') as file:
        data = file.readlines()
    for i in range(len(data)):
        if place in data[i]:
            rating_string = data[i+1]
            break
    sum = 0
    count = 0
    for i in range(len(rating_string)):
        if rating_string[i:i+1].isdigit():
            sum += int(rating_string[i:i+1])
            count += 1
    return sum/count


from dsl.create_lead import CreateLead
from ioffice.clients.client_dashboard import ClientDashboardPage
from ioffice.leads.change_status_dialog import ChangeStatusDialog
from ioffice.leads.lead_details_page import LeadDetailsPage
from utils import get_temp_data, get_common_data

class ConvertLead(CreateLead):

    def using_change_status_dialog(self):
        lead_details_page = LeadDetailsPage(self.config)
        lead_details_page.lead_actions_menu() \
            .hover_over_lead_actions() \
            .change_status()
        return ConvertLead._ChangeStatus(lead_details_page, self)

    def assert_lead_converted_to_client_exists(self):
        lead = get_temp_data(self.config, "lead")
        clientdashboard = ClientDashboardPage(self.config)
        assert clientdashboard.is_title_matches(), "Title does not match the client dashboard"
        assert clientdashboard.get_client_bar_info() == lead["person"]["firstName"] + ' ' + lead["person"]["lastName"]

    class _ChangeStatus:
        def __init__(self, parent_page, journey):
            self.config = journey.config
            self.journey = journey
            self.dialog = ChangeStatusDialog(parent_page)

        def convert_lead_to_client(self):
            data = get_common_data(self.config)["test_data"]["lead_data"]
            self.dialog.select_status(data["STATUS"])
            self.dialog.wait_until_please_wait_spinner_present()
            self.dialog.click_save_button()
            self.dialog.close_io_dialog()
            return self.journey


from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from .models import Project
from .forms import ProjectForm
from .utils import search_projects

def projects(requests):
    page = requests.GET.get("page")
    projects, search_query = search_projects(requests)

    results_per_page = 3
    paginator = Paginator(projects, results_per_page)
    try:
        projects = paginator.page(page)
    except PageNotAnInteger:
        page = 1
        projects = paginator.page(page)
    except EmptyPage:
        page = paginator.num_pages
        projects = paginator.page(page)

    context = {"projects": projects, "search_query": search_query, "paginator": paginator}
    return render(requests, "projects/projects.html", context)

def project(requests, pk):
    project = Project.objects.get(id=pk)
    context = {"project": project}
    return render(requests, "projects/single_project.html", context)

@login_required(login_url="login")
def create_project(request):
    profile = request.user.profile
    form = ProjectForm()

    if request.method == "POST":
        form = ProjectForm(request.POST, request.FILES)
        if form.is_valid():
            project = form.save(commit = False)
            project.owner = profile
            project.save()
            return redirect("account")
    context = {"form": form}
    return render(request, "projects/project_form.html", context)

@login_required(login_url="login")
def update_project(request, pk):
    profile = request.user.profile
    project = profile.project_set.get(id=pk)
    form = ProjectForm(instance=project)

    if request.method == "POST":
        form = ProjectForm(request.POST, request.FILES, instance=project)
        if form.is_valid():
            form.save()
            return redirect("account")
    context = {"form": form}
    return render(request, "projects/project_form.html", context)

@login_required(login_url="login")
def delete_project(request, pk):
    profile = request.user.profile
    project = profile.project_set.get(id=pk)
    if request.method == "POST":
        project.delete()
        return redirect("account")
    context = {"object": project}
    return render(request, 'delete_template.html', context)


import pytest

from advent.calendar.day_19 import part_one, part_two

def _input():
    return """Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian.""".splitlines()

# these take a while to run, marking skip to not tax my githooks on every push
@pytest.mark.skip
def test_part_one():
    expected = 33
    actual = part_one(_input())

    assert expected == actual

@pytest.mark.skip
def test_part_two():
    expected = 56 * 62
    actual = part_two(_input())

    assert expected == actual


import time
from selenium import webdriver
from bs4 import BeautifulSoup, NavigableString, Tag
import requests
import pandas as pd
import logging
import csv
import argparse

logging.basicConfig(level=logging.CRITICAL)

parser = argparse.ArgumentParser(description='fill arguement')

parser.add_argument('--novel_name', type=str, required=False,
                    help='input the novel name')

parser.add_argument('--page', type=int, required=False, default=1000,
                    help='input the novel name')

parser.add_argument('--experiment', type=str, required=True,
                    help = 'input the execution experiment name')

parser.add_argument('--url', type=str, required=False, default="https://www.ptwxz.com/",
                    help= "input novel table of content's url")

args = parser.parse_args()

logging.debug("novel name", args.novel_name)
logging.debug("novel page", args.page)

count_page = args.page

browser = webdriver.Chrome()
url=args.url
browser.get(url)

soup = BeautifulSoup(browser.page_source, 'html.parser')

data = pd.DataFrame()

#count the page
count = 0
for i in soup.find_all('li'):
    for j in i.find_all('a', href=True):

        if(count > count_page):
            break

        newurl = url+'/'+j.get('href')
        response = requests.get(newurl, verify=False, headers={
            "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36"
        })
        print("new url", newurl)
        logging.debug("status code ", response.status_code)
        logging.debug("web encode ",response.encoding)
        logging.debug("apparent encode", response.apparent_encoding)
        response.encoding = response.apparent_encoding

        soup = BeautifulSoup(response.text, 'html.parser')

        title = soup.find("title")

        text = ""

        for i in soup.find_all('br'):
            next_s = i.nextSibling
            if(next_s and type(next_s) == "<class 'bs4.element.NavigableString'>"):
                continue
            if(isinstance(next_s, Tag)):
                continue
            #print(next_s)
            text += str(next_s)
        if(title.string != "404 Not Found"):
            series = pd.DataFrame({
                "title": title.string,
                "desc" : text
            }, index=[str(count)])
            data = data.append(series)
            count += 1
        else:
            print("error 404")

data_csv = data.to_csv(args.experiment+'.csv')
print(data_csv)


## runtime: 86.36%, memory: 69.86%
class Solution:
    def decrypt(self, code: List[int], k: int) -> List[int]:
        if k == 0:
            # return [0] * len(code)
            return [0 for _ in code]

        if len(code) == 0:
            return []

        li_Ret = []
        if k > 0:
            code = code[1:] + [code[0]]
            #print (code)
        else:
            code = code[k:] + code[:k]
            #print (code)
            k = -k

        # k = abs(k)

        curr_sum = 0
        for idx in range(len(code)):
            if idx == 0:
                curr_sum = sum([code[(idx + idy)%len(code)] for idy in range(k)])
            else:
                curr_sum = curr_sum - code[idx-1] + code[(idx + k -1)%len(code)]

            li_Ret.append(curr_sum)

        return li_Ret

data = [[[5,7,1,4], 3], [[1,2,3,4], 0], [[2,4,9,3], -2]]
results = [[12,10,16,13], [0,0,0,0], [12,5,6,13]]
is_success = True

sol = Solution()
for idx, _data in enumerate(data):
    ret = sol.decrypt(_data[0], _data[1])
    if ret != results[idx]:
        is_success = False

        print (f"Failed: idx:{idx}")
        print (f"Outputs: {ret}")
        print (f"Expected: {results[idx]}")

if is_success:
    print ("Success!!")


r"""Plotting helpers."""

__all__ = ['nice_rc', 'corner', 'mark_point', 'coverage_plot']

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

from numpy import ndarray as Array
from typing import *

def nice_rc(latex: bool = False) -> Dict[str, Any]:
    r"""Returns a dictionary of runtime configuration (rc) settings for nicer
    :mod:`matplotlib` plots. The settings include 12pt font size, higher DPI,
    tight layout, transparent background, etc.

    Arguments:
        latex: Whether to use LaTeX typesetting or not.

    Example:
        >>> plt.rcParams.update(nice_rc())
    """

    rc = {
        'axes.axisbelow': True,
        'axes.linewidth': 0.8,
        'figure.dpi': 150,
        'figure.figsize': (6.4, 4.8),
        'font.size': 12.0,
        'legend.fontsize': 'x-small',
        'lines.linewidth': 1.0,
        'lines.markersize': 3.0,
        'savefig.bbox': 'tight',
        'savefig.pad_inches': 0.05,
        'savefig.transparent': True,
        'xtick.labelsize': 'x-small',
        'xtick.major.width': 0.8,
        'ytick.labelsize': 'x-small',
        'ytick.major.width': 0.8,
    }

    if latex:
        rc.update({
            'font.family': ['serif'],
            'font.serif': ['Computer Modern'],
            'text.usetex': True,
        })

    return rc

class LinearAlphaColormap(mpl.colors.LinearSegmentedColormap):
    r"""Linear segmented transparency colormap.

    Arguments:
        color: A color.
        levels: A sequence of levels dividing the domain into segments.
        alpha: The transparency range.
        name: A name for the colormap.
    """

    def __new__(
        self,
        color: Union[str, tuple],
        levels: Array = None,
        alpha: Tuple[float, float] = (0.0, 1.0),
        name: str = None,
    ):
        if name is None:
            if type(color) is str:
                name = f'alpha_{color}'
            else:
                name = f'alpha_{hash(color)}'

        if levels is None:
            levels = [0.0, 1.0]

        levels = np.asarray(levels)
        levels = (levels - levels.min()) / (levels.max() - levels.min())
        alpha = np.linspace(*alpha, len(levels))

        rgb = mpl.colors.to_rgb(color)
        colors = sorted((l, rgb + (a,)) for l, a in zip(levels, alpha))

        return mpl.colors.LinearSegmentedColormap.from_list(
            name=name,
            colors=colors,
        )

def gaussian_blur(img: Array, sigma: float = 1.0) -> Array:
    r"""Applies a Gaussian blur to an image.

    Arguments:
        img: An image array.
        sigma: The standard deviation of the Gaussian kernel.

    Returns:
        The blurred image.

    Example:
        >>> img = np.random.rand(128, 128)
        >>> gaussian_blur(img, sigma=2.0)
        array([...])
    """

    size = 2 * int(3 * sigma) + 1

    k = np.arange(size) - size / 2
    k = np.exp(-(k**2) / (2 * sigma**2))
    k = k / np.sum(k)

    smooth = lambda x: np.convolve(x, k, mode='same')

    for i in range(len(img.shape)):
        img = np.apply_along_axis(smooth, i, img)

    return img

def credible_levels(hist: Array, creds: Array) -> Array:
    r"""Returns the levels of credibility region contours.

    Arguments:
        hist: An histogram.
        creds: The region credibilities.
    """

    x = np.sort(hist, axis=None)[::-1]
    cdf = np.cumsum(x)
    idx = np.searchsorted(cdf, creds * cdf[-1])

    return x[idx]

def corner(
    data: Array,
    weights: Array = None,
    domain: Tuple[Array, Array] = None,
    bins: Union[int, Sequence[int]] = 64,
    creds: Sequence[float] = (0.6827, 0.9545, 0.9973),
    color: Union[str, tuple] = None,
    alpha: Tuple[float, float] = (0.0, 0.5),
    legend: str = None,
    labels: Sequence[str] = None,
    smooth: float = 0,
    figure: plt.Figure = None,
    **kwargs,
) -> plt.Figure:
    r"""Displays each 1 or 2-d projection of multi-dimensional data, as a triangular
    matrix of histograms, known as corner plot. For 2-d histograms, highest density
    credibility regions are delimited.

    Arguments:
        data: Multi-dimensional data, either as a table or as a matrix of histograms.
        weights: The importance weights of the data samples.
        domain: A pair of lower and upper domain bounds. If :py:`None`, inferred from data.
        bins: The number(s) of bins per dimension.
        creds: The region credibilities (in :math:`[0, 1]`) to delimit.
        color: The color of histograms. If :py:`None`, use the color cycler instead.
        alpha: The transparency range.
        legend: A legend.
        labels: The dimension labels.
        smooth: The standard deviation of the smoothing kernels.
        figure: A corner plot over which to draw the new one.
        kwargs: Keyword arguments passed to :func:`matplotlib.pyplot.subplots`.

    Returns:
        The figure instance for the corner plot.

    Example:
        >>> data = np.random.randn(2**16, 3)
        >>> labels = [r'$\alpha$', r'$\beta$', r'$\gamma$']
        >>> figure = corner(data, bins=32, labels=labels, figsize=(4.8, 4.8))

    .. image:: ../images/corner.png
        :align: center
        :width: 600
    """

    # Histograms
    if np.asarray(data[0][0]).ndim == 0:
        data = np.asarray(data)
        D = data.shape[-1]

        if type(bins) is int:
            bins = [bins] * D

        if domain is None:
            lower, upper = data.min(axis=0), data.max(axis=0)
        else:
            lower, upper = map(np.asarray, domain)

        bins = [
            np.histogram_bin_edges(data, bins[i], range=(lower[i], upper[i]))
            for i in range(D)
        ]

        hists = np.ndarray((D, D), dtype=object)

        for i in range(D):
            for j in range(i + 1):
                if i == j:
                    hist, _ = np.histogram(
                        data[..., i],
                        bins=bins[i],
                        density=True,
                        weights=weights,
                    )
                else:
                    hist, _, _ = np.histogram2d(
                        data[..., i],
                        data[..., j],
                        bins=(bins[i], bins[j]),
                        density=True,
                        weights=weights,
                    )

                hists[i, j] = hist
    else:
        data = np.asarray(data, dtype=object)
        D = len(data)

        if domain is None:
            lower, upper = np.zeros(D), np.ones(D)
        else:
            lower, upper = map(np.asarray, domain)

        bins = [None] * D
        for i in range(D):
            if data[i, i] is not None:
                bins[i] = np.linspace(lower[i], upper[i], len(data[i, i]) + 1)

        hists = data

    # Figure
    if figure is None:
        kwargs.setdefault('figsize', (6.4, 6.4))

        figure, axes = plt.subplots(
            D,
            D,
            squeeze=False,
            sharex='col',
            gridspec_kw={'wspace': 0.0, 'hspace': 0.0},
            **kwargs,
        )
        new = True
    else:
        axes = np.asarray(figure.axes).reshape(D, D)
        new = False

    # Legend

    ## Quantiles
    creds = np.sort(np.asarray(creds))[::-1]
    creds = np.append(creds, 0)

    if new:
        cmap = LinearAlphaColormap('black', levels=creds, alpha=alpha)

        levels = (creds - creds.min()) / (creds.max() - creds.min())
        levels = (levels[:-1] + levels[1:]) / 2

        for c, l in zip(creds[:-1], levels):
            axes[0, -1].plot(
                [],
                [],
                color=cmap(l),
                linewidth=6,
                solid_capstyle='butt',
                label=r'${:.1f}\,\%$'.format(c * 100),
            )

    ## Color
    lines = axes[0, -1].plot([], [], color=color, solid_capstyle='butt', label=legend)
    color = lines[-1].get_color()

    axes[0, -1].legend(loc='upper right', frameon=False)

    # Plot
    for i in range(D):
        for j in range(D):
            ax = axes[i, j]
            hist = hists[i, j]

            if j > i:
                ax.axis('off')
                continue

            if hist is None:
                continue

            if smooth > 0:
                hist = gaussian_blur(hist, smooth)

            ## Draw
            x, y = bins[j], bins[i]
            x = (x[1:] + x[:-1]) / 2
            y = (y[1:] + y[:-1]) / 2

            if i == j:
                ax.plot(x, hist, color=color)

                _, top = ax.get_ylim()
                top = max(top, hist.max() * 1.0625)

                ax.set_xlim(left=bins[i][0], right=bins[i][-1])
                ax.set_ylim(bottom=0.0, top=top)
            else:
                levels = np.unique(credible_levels(hist, creds))

                cf = ax.contourf(
                    x,
                    y,
                    hist,
                    levels=levels,
                    cmap=LinearAlphaColormap(color, levels, alpha=alpha),
                )
                ax.contour(cf, colors=color)

                if j > 0:
                    ax.sharey(axes[i, j - 1])
                else:
                    ax.set_ylim(bottom=bins[i][0], top=bins[i][-1])

            ## Ticks
            if i == D - 1:
                ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(3, prune='both'))
                plt.setp(
                    ax.get_xticklabels(),
                    rotation=45.0,
                    horizontalalignment='right',
                    rotation_mode='anchor',
                )
            else:
                ax.xaxis.set_ticks_position('none')

            if i == j:
                ax.set_yticks([])
            elif j == 0:
                ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(3, prune='both'))
            else:
                ax.yaxis.set_ticks_position('none')

            ## Labels
            if labels is not None:
                if i == D - 1:
                    ax.set_xlabel(labels[j])

                if j == 0 and i != j:
                    ax.set_ylabel(labels[i])

            ax.label_outer()

    figure.align_labels()
    figure.set_layout_engine(layout='tight')

    return figure

def mark_point(
    figure: plt.Figure,
    point: Array,
    color: Union[str, tuple] = 'black',
    linestyle: str = 'dashed',
    marker: str = 's',  # square
    legend: str = None,
) -> None:
    r"""Marks a point on the histograms of a corner plot.

    Arguments:
        figure: The corner plot figure (see :func:`corner`).
        point: The point to mark.
        color: The color of the lines and markers.
        linestyle: The style of the lines.
        marker: The shape of the markers.
        legend: A legend.

    Example:
        >>> mark_point(figure, [0.5, 0.3, -0.7], color='black')

    .. image:: ../images/corner_marked.png
        :align: center
        :width: 600
    """

    D = len(point)
    axes = np.asarray(figure.axes).reshape(D, D)

    # Legend
    if legend is not None:
        axes[0, -1].plot(
            [],
            [],
            color=color,
            linestyle=linestyle,
            marker=marker,
            solid_capstyle='butt',
            label=legend,
        )

        axes[0, -1].legend(loc='upper right', frameon=False)

    # Plot
    for i in range(D):
        for j in range(i + 1):
            ax = axes[i, j]
            ax.axvline(point[j], color=color, linestyle=linestyle)

            if i != j:
                ax.axhline(point[i], color=color, linestyle=linestyle)
                ax.plot(point[j], point[i], color=color, marker=marker)

def coverage_plot(
    levels: Array,
    coverages: Array,
    color: Union[str, tuple] = None,
    legend: str = None,
    figure: plt.Figure = None,
    **kwargs,
) -> plt.Figure:
    r"""Plots the expected coverage at various credible levels.

    Arguments:
        levels: A vector of increasing credible levels.
        coverages: A vector of corresponding expected coverages.
        legend: A legend.
        figure: Another coverage plot over which to draw the new one.
        kwargs: Keyword arguments passed to :func:`matplotlib.pyplot.subplots`.

    Returns:
        The figure instance for the coverage plot.

    Example:
        >>> levels = np.linspace(0, 1, 512) ** 2
        >>> coverages = np.linspace(0, 1, 512)
        >>> figure = coverage_plot(levels, coverages)

    .. image:: ../images/coverage.png
        :align: center
        :width: 400
    """

    levels, coverages = np.asarray(levels), np.asarray(coverages)

    # Figure
    if figure is None:
        kwargs.setdefault('figsize', (3.2, 3.2))

        figure, ax = plt.subplots(**kwargs)
        new = True
    else:
        ax = figure.axes[0]
        new = False

    # Plot
    if new:
        ax.plot([0, 1], [0, 1], color='k', linestyle='--')

    ax.plot(levels, coverages, color=color, label=legend)

    ax.grid(visible=True)
    ax.set_xlabel(r'Credible level')
    ax.set_ylabel(r'Expected coverage')

    if legend is not None:
        ax.legend(loc='upper left')

    figure.set_layout_engine(layout='tight')

    return figure


#!/bin/python3

import os
from collections import defaultdict

# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
    subs = defaultdict(int)
    count = 0
    l = len(s)
    for i in range(l - 1, 0, -1):
        for j in range(0, l, 1):
            if i + j > l:
                break
            t = s[j:i+j]
            t = str(sorted(t))
            if t not in subs:
                subs[t] = 1
            else:
                subs[t] += 1

    for k, value in subs.items():
        if value > 1:
            count += int((value - 1) * value / 2)

    return count

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

    q = int(input())

    for q_itr in range(q):
        s = input()

        result = sherlockAndAnagrams(s)

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

    fptr.close()

Tutorials/Interview Preparation Kit/Dictionaries and Hashmaps/Sherlock and Anagrams/code.py3


from flask_ngrok import run_with_ngrok
from flask import Flask, render_template, request
import numpy as np
import sys
import os
sys.path.append(os.path.abspath("./model"))
from load import *
import tensorflow.keras.backend as K
from tensorflow.keras.preprocessing import image
from werkzeug import secure_filename
from werkzeug.routing import Rule

K.clear_session()

global model, food_classes

app = Flask(__name__)

path_trained_model = "model/best_model_58class_all.hdf5"
model = init(path_trained_model)
food_classes = init_food_classes()

# Gère le routing
app.url_map.add(Rule('/', endpoint="predict"))
app.url_map.add(Rule('/predict/', endpoint="predict"))

# IMPORTANT : Décommenter la ligne ci-dessous pour exécuter NGROK et sonner accès à l'application en ligne
# run_with_ngrok(app)

def do_prediction(food_img_path):
    K.clear_session()
    img = image.load_img(food_img_path, target_size=(299, 299))
    img = image.img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img /= 255.

    pred = model.predict(img)

    indexes = np.argsort(pred[0])[::-1][:3]

    food_probas = np.array(pred[0])[indexes]
    food_probas = [round(proba*100, 2) if idx == 0 else round(proba*100, 5) for idx, proba in enumerate(food_probas)]

    food_classes.sort()

    pred_values = [food_classes[index].capitalize().replace("_", " ") for index in indexes]

    print(pred_values)

    return render_template("draw.html", food_image = os.path.join("..", food_img_path), food_pred = pred_values, food_probas = food_probas)

# @app.route("/")
# @app.route("/predict/")
# @app.route('/uploader/', methods=["GET", "POST"])
@app.endpoint('predict')
def predict():
    path_images_validation = os.path.join("static", "images_validation")
    path_list_food_test = os.path.join("/", "home" , "sully" , "code", "practice", "portfolio_data", "food-recognizer", "datasets", "google_images_dataset", "images", "test")

    if request.method == 'POST':
        f = request.files['file']
        f.save(os.path.join(path_images_validation, secure_filename(f.filename)))
        print('file uploaded successfully')

        food_img = secure_filename(f.filename)
        food_img_path = os.path.join(path_images_validation, food_img)
    else:
        food_validation_list = os.listdir(path_images_validation)
        food_img = food_validation_list[np.random.randint(len(food_validation_list))]
        food_img_path = os.path.join(path_images_validation, food_img)

    return do_prediction(food_img_path)

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


# https://www.interviewbit.com/problems/sorted-array-to-balanced-bst/
# Definition for a  binary tree node
class TreeNode:
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None

class Solution:
	# @param A : tuple of integers
	# @return the root node in the tree
	def sortedArrayToBST(self, A):
		return self.array_to_bst(A, 0, len(A) - 1)

	def array_to_bst(self, arr, start_index, end_index):
		if start_index <= end_index:
			mid = (end_index + start_index) / 2
			tree_node = TreeNode(arr[mid])
			tree_node.left = self.array_to_bst(arr, start_index, mid - 1)
			tree_node.right = self.array_to_bst(arr, mid + 1, end_index)

			return tree_node

a = Solution()
A = [1, 2, 3]
a.sortedArrayToBST(A)


from django.shortcuts import render, redirect
from .models import Product
from .form import ProductForm
from django.http import Http404
from merchan.models import Merchandise

def index(request):
    return render(request, 'product/index.html')

def create_product(request):
    data = {}
    if request.method == "GET":
        group_form = ProductForm()
        data['group_form'] = group_form
        return render(request, 'product/create.html', context=data)
    elif request.method == "POST":
        group_form = ProductForm(request.POST, request.FILES)
        group_form.save()
        return redirect('/product/list')

def delete_product(request, slug):
    data = {}
    if not request.user.is_authenticated or not Product.objects.filter(slug=slug).exists():
        raise Http404
    product = Product.objects.get(slug=slug)
    if request.method == "GET":
        data['product'] = product
        return render(request, 'product/delete.html', context=data)
    elif request.method == "POST":
        product.delete()
        return redirect('/product/list')

def product_detail(request, slug):
    data = {}
    if not Product.objects.filter(slug=slug).exists():
        raise Http404
    product = Product.objects.get(slug=slug)

    # Секция со студентами
    data['product'] = product
    merchan = Merchandise.objects.filter(product__id=product.id)
    data['merchan'] = merchan
    return render(request, 'product/details.html', context=data)

def product_list(request):
    data = {}
    all_product = Product.objects.all()
    data['product'] = all_product
    return render(request, 'product/list.html', context=data)

def update_product(request, slug):
    data = {}
    if not request.user.is_authenticated or not Product.objects.filter(slug=slug).exists():
        raise Http404
    product = Product.objects.get(slug=slug)
    data['product'] = product
    if request.method == "GET":
        product_form = ProductForm(instance=product)
        data['product_form'] = product_form
        return render(request, 'product/update.html', context=data)
    elif request.method == "POST":
        product_form = ProductForm(request.POST)
        if product_form.is_valid():
            product.image = product_form.cleaned_data['image']
            product.name = product_form.cleaned_data['name']
            product.about = product_form.cleaned_data['about']
            product.max_presets = product_form.cleaned_data['max_presets']
            product.is_discount_preset = product_form.cleaned_data['is_discount_preset']
            product.save()
        else:
            print('NOT VALID FORM!')

        return redirect('/product/list')


from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep

driver = webdriver.Firefox(executable_path="C://Users//seker//Documents//driver//geckodriver.exe")
driver.get("https://www.rahulshettyacademy.com/AutomationPractice/")
driver.maximize_window()
driver.implicitly_wait(10)

row = len(driver.find_elements(By.XPATH,"//table/tbody/tr"))
col = len(driver.find_elements(By.XPATH,"//table/tbody/tr/th"))

print('Number of the rows:', row)
print('Number of the col :', col)

for r in range(2,row+1):
    for c in range(1,col+1):
        value = driver.find_element(By.XPATH,"//body[1]/div[3]/div[1]/fieldset[1]/table[1]/tbody[1]/tr["+str(r)+"]/td["+str(c)+"]").text
        print(value,end='   ')
    print()

driver.quit()


"""
ZMMemory
=====================
Wrapper to access SHM for Monitor status
"""

import mmap
import struct
from collections import namedtuple
import os
from pyzm.helpers.Base import Base
import pyzm.helpers.globals as g

"""
shared_data => { type=>'SharedData', seq=>$mem_seq++, contents=> {
    size             => { type=>'uint32', seq=>$mem_seq++ }, I
    last_write_index => { type=>'uint32', seq=>$mem_seq++ }, I
    last_read_index  => { type=>'uint32', seq=>$mem_seq++ }, I
    state            => { type=>'uint32', seq=>$mem_seq++ }, I
    last_event       => { type=>'uint64', seq=>$mem_seq++ }, Q
    action           => { type=>'uint32', seq=>$mem_seq++ }, I
    brightness       => { type=>'int32', seq=>$mem_seq++ },  i
    hue              => { type=>'int32', seq=>$mem_seq++ },  i
    colour           => { type=>'int32', seq=>$mem_seq++ },  i
    contrast         => { type=>'int32', seq=>$mem_seq++ },  i
    alarm_x          => { type=>'int32', seq=>$mem_seq++ },  i
    alarm_y          => { type=>'int32', seq=>$mem_seq++ },  i
    valid            => { type=>'uint8', seq=>$mem_seq++ },  ?
    active           => { type=>'uint8', seq=>$mem_seq++ },  ?
    signal           => { type=>'uint8', seq=>$mem_seq++ },  ?
    format           => { type=>'uint8', seq=>$mem_seq++ },  ?
    imagesize        => { type=>'uint32', seq=>$mem_seq++ }, I
    epadding1        => { type=>'uint32', seq=>$mem_seq++ },  I
    startup_time     => { type=>'time_t64', seq=>$mem_seq++ },  Q
    last_write_time  => { type=>'time_t64', seq=>$mem_seq++ },  Q
    last_read_time   => { type=>'time_t64', seq=>$mem_seq++ },  Q
    control_state    => { type=>'uint8[256]', seq=>$mem_seq++ }, s256
    alarm_cause      => { type=>'int8[256]', seq=>$mem_seq++ }, s256
"""

"""
    trigger_data => { type=>'TriggerData', seq=>$mem_seq++, 'contents'=> {
    size             => { type=>'uint32', seq=>$mem_seq++ }, I
    trigger_state    => { type=>'uint32', seq=>$mem_seq++ }, I
    trigger_score    => { type=>'uint32', seq=>$mem_seq++ }, I
    padding          => { type=>'uint32', seq=>$mem_seq++ }, I
    trigger_cause    => { type=>'int8[32]', seq=>$mem_seq++ }, s32
    trigger_text     => { type=>'int8[256]', seq=>$mem_seq++ }, s256
    trigger_showtext => { type=>'int8[256]', seq=>$mem_seq++ }, s256
  }
"""

class ZMMemory(Base):

    def __init__(self,api=None, path='/dev/shm', mid=None):
        self.api = api

        self.alarm_state_stages = {
        'STATE_IDLE':0,
        'STATE_PREALARM':1,
        'STATE_ALARM':2,
        'STATE_ALERT':3,
        'STATE_TAPE':4,
        'ACTION_GET':5,
        'ACTION_SET':6,
        'ACTION_RELOAD':7,
        'ACTION_SUSPEND':8,
        'ACTION_RESUME':9,
        'TRIGGER_CANCEL':10,
        'TRIGGER_ON':11,
        'TRIGGER_OFF':12
        }
        self.fhandle = None
        self.mhandle = None

        if not mid:
            raise ValueError ('No monitor specified')
        self.fname = path+'/zm.mmap.'+str(mid)
        self.reload()

    def reload(self):
        """Reloads monitor information. Call after you get
        an invalid memory report

        Raises:
            ValueError: if no monitor is provided
        """
        self.close()
        self.fhandle = open(self.fname, "r+b")
        sz = os.path.getsize(self.fname)
        if not sz:
            raise ValueError ('Invalid size: {} of {}'.format(sz, self.fname))

        self.mhandle = mmap.mmap(self.fhandle.fileno(), 0, access=mmap.ACCESS_READ)
        self.sd = None
        self.td = None
        self._read()

    def is_valid(self):
        """True if the memory handle is valid

        Returns:
            bool: True if memory handle is valid
        """
        try:
            d = self._read()
            return not d['shared_data']['size']==0
        except Exception as e:
            g.logger.Error('Memory: {}'.format(e))
            return False

    def is_alarmed(self):
        """True if monitor is currently alarmed

        Returns:
            bool: True if monitor is currently alarmed
        """

        d = self._read()
        return int(d['shared_data']['state']) == self.alarm_state_stages['STATE_ALARM']

    def alarm_state(self):
        """Returns alarm state

        Returns:
            dict: as below::

                {
                    'id': int # state id
                    'state': string # name of state
                }

        """

        d = self._read()
        return {
            'id': d['shared_data']['state'],
            'state': list(self.alarm_state_stages.keys())[list(self.alarm_state_stages.values()).index(int( d['shared_data']['state']))]
        }

    def last_event(self):
        """Returns last event ID

        Returns:
            int: last event id
        """
        d = self._read()
        return d['shared_data']['last_event']

    def cause(self):
        """Returns alarm and trigger cause as applicable

        Returns:
            dict: as below::

                {
                    'alarm_cause': string
                    'trigger_cause': string
                }

        """
        d=self._read()
        return {
            'alarm_cause': d['shared_data'].get('alarm_cause'), # May not be there
            'trigger_cause': d['shared_data'].get('trigger_cause'),
        }

    def trigger(self):
        """Returns trigger information

        Returns:
            dict: as below::

                {
                    'trigger_text': string,
                    'trigger_showtext': string,
                    'trigger_cause': string,
                    'trigger:state' {
                        'id': int,
                        'state': string
                    }
                }
        """

        d=self._read()
        return {
            'trigger_text': d['trigger_data'].get('trigger_text'),
            'trigger_showtext': d['trigger_data'].get('trigger_showtext'),
            'trigger_cause': d['trigger_data'].get('trigger_cause'),
            'trigger_state': {
                'id':d['trigger_data'].get('trigger_state'),
                'state': d['trigger_data']['trigger_state']
            }

        }

    def _read(self):
        self.mhandle.seek(0)
        SharedData = namedtuple('SharedData', 'size last_write_index last_read_index state last_event action brightness hue color contrast alarm_x alarm_y valid active signal format imagesize epadding1 startup_time last_write_time last_read_time control_state alarm_cause')
        s = SharedData._make(struct.unpack('IIIIQIiiiiii????IIQQQ256s256s',self.mhandle.read(600)))
        TriggerData = namedtuple('TriggerData', 'size trigger_state trigger_score padding trigger_cause trigger_text trigger_showtext')
        t = TriggerData._make(struct.unpack('IIII32s256s256s', self.mhandle.read(560)))
        self.sd = s._asdict()
        self.td = t._asdict()

        self.sd['alarm_cause'] = self.sd['alarm_cause'].split(b'\0',1)[0].decode()
        self.sd['control_state'] = self.sd['control_state'].split(b'\0',1)[0].decode()
        self.td['trigger_cause'] = self.td['trigger_cause'].split(b'\0',1)[0].decode()
        self.td['trigger_text'] = self.td['trigger_text'].split(b'\0',1)[0].decode()
        self.td['trigger_showtext'] = self.td['trigger_showtext'].split(b'\0',1)[0].decode()
        return { 'shared_data':self.sd, 'trigger_data':self.td}

    def get(self):
        """returns raw shared and trigger data as a dict

        Returns:
            dict: raw shared and trigger data ::

                {
                    'shared_data': dict, # of shared data,
                    'trigger_data': dict # trigger data
                }
        """
        return self._read()

    def get_shared_data(self):
        """Returns just the shared data

        Returns:
            dict: shared data
        """
        return self._read()['shared_data']

    def get_trigger_data(self):
        """Returns just the trigger data

        Returns:
            dict: trigger data
        """
        return self._read()['trigger_data']

    def close(self):
        """Closes the handle
        """
        try:
            if self.mhandle: self.mhandle.close()
            if self.fhandle: self.fhandle.close()
        except Exception as e:
            pass


import typer
from motion_marmot.advanced_motion_filter import AdvancedMotionFilter

app = typer.Typer()

@app.command()
def run():
    amf = AdvancedMotionFilter("model/scene_knn_model", 0, 0)
    print(amf)

def main():
    """Main program"""
    app()

if __name__ == "__main__":
    main()


# importing all required modules
import tkinter as tk
from tkinter import END
from tkinter.filedialog import askopenfilename
from tkcalendar import Calendar
import CSVparsing
import ftp_connect
import displayCSV
import os
import shutil

class App:
    """
    CREATING UI, largely created by Adam D
    """
    def __init__(self):
        """
        CONFIGURING WINDOW
        """

        # defining widgets
        self.calendar = None
        self.btn_upload = None
        self.btn_choose_file = None
        self.scrollbar = None
        self.dropDown = None
        self.entries_to_use = None
        self.frm_scroll_box = None
        self.btn_view = None
        self.btn_today = None
        self.btn_filter = None
        self.ent_filter = None
        self.lbl_filter = None
        self.frm_filter = None

        # creates window
        self.window = tk.Tk()
        self.window.title("Medical Data")

        # configures grid layout
        self.window.rowconfigure(0, minsize=250, weight=1)
        self.window.rowconfigure(1, minsize=100, weight=1)
        self.window.columnconfigure(0, minsize=230, weight=1)
        self.window.columnconfigure(1, minsize=100, weight=1)
        self.window.columnconfigure(2, minsize=100, weight=1)
        self.init_ui()

    def init_ui(self):
        """
        CREATING WIDGETS
        """
        # configuring filter widgets
        self.frm_filter = tk.Frame(master=self.window)
        self.lbl_filter = tk.Label(master=self.frm_filter,
                                   text="Filter by Date")
        """calendar code created by team"""
        self.btn_filter = \
            tk.Button(
                master=self.frm_filter,
                text="Get Date",
                command=self.get_date
            )
        # creating calendar widget
        self.calendar = Calendar(master=self.frm_filter,
                                 selectmode="day")
        """end of calendar code"""

        # other button widgets
        self.btn_view = tk.Button(
            master=self.window,
            text="View Selected File",
            command=self.selectedItemOutput
        )

        # configuring scrollable list
        self.frm_scroll_box = tk.Frame(master=self.window)
        self.dropDown = tk.Listbox(self.frm_scroll_box)
        self.scrollbar = tk.Scrollbar(self.frm_scroll_box)
        self.dropDown.config(yscrollcommand=self.scrollbar.set)

        # configuring file upload widgets
        self.btn_choose_file = tk.Button(
            master=self.window,
            text="Choose File",
            command=self.choose_file
        )
        self.btn_upload = tk.Button(
            master=self.window,
            text="Upload"
            # command=
        )

        """
        CREATING WIDGET LAYOUT
        """
        # laying out widgets on the main window
        self.frm_scroll_box.grid(row=0, column=0)
        self.frm_filter.grid(row=0, column=1, columnspan=2, padx=5, pady=5)
        self.btn_view.grid(row=1, column=0, sticky="nsew", padx=10, pady=10)
        self.btn_choose_file.grid(row=1, column=1, sticky="nsew", padx=5, pady=10)
        self.btn_upload.grid(row=1, column=2, sticky="nsew", padx=10, pady=10)

        # laying out filtering widgets within frm_filter
        self.lbl_filter.grid(row=0)
        self.calendar.grid(row=1)
        self.btn_filter.grid(row=2, padx=5, pady=5, sticky="nsew")

        # laying out scrollable list widgets within frm_scroll_box
        self.scrollbar.pack(side=tk.RIGHT, fill="y")
        self.dropDown.pack(side=tk.LEFT, fill="y")

    """
    FUNCTIONS, largely created by Harry A and Sunil S
    """

    """
    when choose file button is clicked, a dialogue box opens
    which allows the user to select a file, the filepath is returned
    """
    def choose_file(self):
        # user selects filepath from dialogue window
        filepath = askopenfilename(filetypes=(("csv files", "*.csv"),))
        # if no file path is selected, nothing happens
        if not filepath:
            return
        # changes text of button to display the filepath
        self.btn_choose_file["text"] = filepath
        # returns the filepath
        return filepath

    """
    Once the get_Date button is pressed the validated files
    are grabbed from the server and added to the dropdown list
    """
    def get_date(self):

        self.outListItems = []
        date_string = self.calendar.selection_get()
        date_string = str(date_string).replace("-", "")
        try:
            itemList = ftp_connect.ftp_fetch()  # validation to check if there is a connection to FTP
        except:
            print("Couldnt connect to FTP Server, is config up to date? or is server running?")
            exit(0)

        for items in itemList:
            if CSVparsing.validateFilename(items):
                if str(date_string) in str(items):
                    os.makedirs("tempFTPDownload/", exist_ok=True)
                    ftp_connect.ftp_pull(items, "tempFTPDownload/" + str(items))
                    if CSVparsing.masterValidate("tempFTPDownload/",
                                                 items):  # Validates all files before adding them to Show List
                        os.makedirs("FTPDownload/" + str(date_string[:4]) + "/" + str(date_string[4:6]) + "/" + str(date_string[6:8]), exist_ok=True)
                        self.outListItems.append(items)

        if len(self.outListItems) != 0:
            for files in self.outListItems:
                os.rename("tempFTPDownload/" + files,
                          "FTPDownload/" + files[9:13] + "/" + files[13:15] + "/" + files[15:17] + "/" + files)
            shutil.rmtree("tempFTPDownload")
        self.putInDropDown(self.outListItems)

    """
    Adds all the valid files to the drop down list in the UI
    """
    def putInDropDown(self, validFilesList):
        self.dropDown.delete(0, tk.END)
        for val in validFilesList:
            self.dropDown.insert(END, val)

    """
    Method outputs the given selected file into a Tkinter GUI for easy user reading
    """
    def selectedItemOutput(self):
        self.fileToOutput = ""
        for item in self.dropDown.curselection():
            self.fileToOutput = self.dropDown.get(item)
        ftp_connect.ftp_pull(self.fileToOutput, "FTPDownload/" + self.fileToOutput[9:13] + "/"
                             + self.fileToOutput[13:15] + "/" + self.fileToOutput[15:17] + "/" + self.fileToOutput)  # Creates a temp file to store Pulled FTP CSV data
        outputObj = displayCSV.DisplayCSV("FTPDownload/" + self.fileToOutput[9:13] + "/" +
                                          self.fileToOutput[13:15] + "/" + self.fileToOutput[15:17] + "/" + self.fileToOutput)

"""
LAUNCHING UI
"""
def launch_gui():
    app = App()  # Launches the Tkinter UI
    app.window.mainloop()

if __name__ == "__main__":
    launch_gui()


import csv
replace_rule = 'file.csv'
stringfile = 'strings.xml'

with open(replace_rule, mode ='r')as file:
    # reading the CSV file
    csvFile = csv.reader(file)
    reading_file = open(stringfile, "r")
    content = reading_file.read()
    new_file_content = content
    # displaying the contents of the CSV file
    for lines in csvFile:
        new_file_content = new_file_content.replace(lines[0], lines[1])
   # print(new_file_content)
    reading_file.close()
    writing_file = open("replaced-"+stringfile, "w")
    writing_file.write(new_file_content)
    writing_file.close()


# Written by Hayatu Abdullahi

from PIL import ImageTk, Image
import cv2
from os.path import splitext
import numpy as np
import matplotlib.pyplot as plt

# Obtain camera intrinsics for the images
def camera_intrinsic(camera):
    global fx, fy, cx, cy, depth
    depth = 0
    fx = float(((str(camera[0]).lstrip('[').rstrip(']'))))
    fy = float(((str(camera[1]).lstrip('[').rstrip(']'))))
    cx = float(((str(camera[2]).lstrip('[').rstrip(']'))))
    cy = float(((str(camera[3]).lstrip('[').rstrip(']'))))
    print('Camera Intrinsics:', fx,fy,cx,cy)

    return fx, fy, cx, cy

# Convert RGB images to match depth size if necessary
def convert(imgselect, depth_map, depth_map2):
    global img4
    global img7
    global rgb
    global rgb2

    rgb = Image.open(imgselect)
    rgb2 = np.asarray(rgb)
    dp_size = depth_map.shape
    if rgb2.size != depth_map.size:
        img =cv2.resize(rgb2,(dp_size[1],dp_size[0]))
        img4 = Image.fromarray(img)

        if img4.mode != 'RGB':
            img4 = img4.convert('RGB')

    pic2 = Image.open('images/8.jpeg')
    #pic2 = Image.open('images\8.jpeg')
    rgb3 = np.asarray(pic2)
    dp_size2 = depth_map2.shape
    if rgb3.size != depth_map2.size:
        img6 =cv2.resize(rgb3,(dp_size[1],dp_size[0]))
        img7 = Image.fromarray(img6)

        if img7.mode != 'RGB':
            img7 = img7.convert('RGB')

    print('Depth Size', depth_map.shape)
    print('Image Size',img.shape)
    #depth_map2 = depth_map.reshape(2016, 1512, 3)
    #print (depth_map2.shape)

    return img4, rgb, img7


def quicksort(arr, start, end):
    if start >= end:
        return
    else:
        pivotIndex = partition(arr, start, end)
        quicksort(arr, start, pivotIndex - 1)
        quicksort(arr, pivotIndex + 1, end)

def partition(arr, start, end):
    pivot = arr[start]
    k = 0
    # Find all elements less than k
    for i in range(start, end + 1):
        if arr[i] < pivot:
            k += 1

    # pivot is swapped to the kth position element
    arr[start + k], arr[start] = arr[start], arr[start + k]
    si = start
    ei = end
    while si < ei:
        if arr[si] < pivot:
            si += 1
        elif arr[ei] >= pivot:
            ei = ei - 1
        else:
            arr[si], arr[ei] = arr[ei],  arr[si]
            si += 1
            ei -= 1
    print(arr)
    return start+k

src = [2, 6, 8, 5, 4, 3, 2]#[10, 9, 8, 7, 1, 3, 5, 4, 2]
quicksort(src, 0, len(src) - 1)
print(src)


from django.urls import re_path, include
from rest_framework import routers
from .viewsets import (
    FoodViewSet,
    IngredientViewSet,
    RestrictionTagViewSet,
    RecipeViewSet
)

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'food', FoodViewSet)
router.register(r'ingredients', IngredientViewSet)
router.register(r'restriction_tags', RestrictionTagViewSet)
router.register(r'recipes', RecipeViewSet)

# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    re_path(r'^', include(router.urls)),
    re_path(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]


''' Problem description: https://leetcode.com/problems/longest-common-prefix/description/ '''

class Solution:
	def longestCommonPrefix(self, strs: list[str]) -> str:

		if len(strs) == 0:
			return ''

		strs.sort()

		answer = ''
		for i in range(min(len(strs[0]), len(strs[len(strs) - 1]))):
			if strs[0][i] == strs[len(strs) - 1][i]:
				answer += strs[0][i]
			else:
				break

		return answer


from celery import Celery
from django.core.mail import send_mail
from django.conf import settings
from django.template import loader
import os
# import django
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dailyfresh.settings')
# django.setup()
from goods.models import GoodsType, IndexGoodsBanner, IndexPromotioBanner, IndexTypeGoodsBanner

# 创建一个celery的实力对象
app = Celery('celery_tasks.tasks', broker='redis://192.168.72.136:6379/8')

# 定义任务函数
@app.task
def send_register_active_email(to_email, username, token):
    '''发送激活邮件'''
    subject = '天天生鲜欢迎信息'
    message = ''
    html_message = '''
%s,欢迎注册会员

请点击下面链接激活

            http://127.0.0.1:8000/user/active/%s
            ''' % (username, token, token)
    sender = settings.DEFAULT_FROM_EMAIL
    recrice = [to_email]
    send_mail(subject, message, sender, recrice, html_message=html_message)

@app.task
def generate_static_index_html():
    '''生产首页静态页面'''
    # 获取首页商品的分类信息
    types = GoodsType.objects.all()

    # 获取轮播商品信息
    goods_banners = IndexGoodsBanner.objects.all().order_by('index')

    # 获取首页促销活动信息
    promotion_banners = IndexPromotioBanner.objects.all().order_by('index')

    # 获取首页分类商品展示信息
    for type in types:
        # 获取type种类商品的图片展示信息
        image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1)
        # 获取文字展示信息
        title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0)
        # 动态增加属性
        type.image_banners = image_banners
        type.title_banners = title_banners

    # 获取购物车商品数目
    cart_count = 0

    # 组织上下文
    context = {
        'types': types,
        'goods_banners': goods_banners,
        'promotion_banners': promotion_banners,
        'cart_count': cart_count
    }
    # 加载模板
    temp = loader.get_template('static_index.html')
    # 模板渲染
    static_index_html = temp.render(context)
    # 生产静态文件
    save_path = os.path.join(settings.BASE_DIR, 'static/index.html')
    with open(save_path, 'w') as f:
        f.write(static_index_html)


# Library that gives us the functions to create
#   the map
import plotly.io as pio

# Reads csv files and sorts the states by their
#   fips codes
import pandas as pd

# Object that will be used to execute the
#   map creation features
import plotly.express as px

# Reads the map data from a website to help
#   generate the map
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

# To find the proper path to find the html file we want to display
import os

# Used to import and run the C++ program to generate CSV files
import subprocess

# Calculate the elapsed time for each check for a map or csv file
import timeit

class map_test() :
  # Constructor
  def __init__( self, interval, sDate, fDate, rates ) :
    # Stores the number of days the user chooses
    self.interval = interval

    # Stores the start date
    self.sDate = sDate

    # Stores the final date
    self.fDate = fDate

    # Stores the rates of change
    self.rates = rates

    # Make mapHash() a global variable
    self.mapHash = {}

  # Runs entire checks for generating map
  def main( self ) :
    # Reads in user input from the website
    options = [ self.interval, self.sDate,
                self.fDate, self.rates ]

    if int(options[3]) == int(8) :
      options[3] = 'ALL'

    # Stores the name of the temporary key
    tempKey = ''

    # Creates a key using the user input
    for i in range( len(options) ) :
      tempKey = tempKey + str( options[i] )

      # Separates each element in the key by a hyphen
      if i != len(options) - 1 :
        tempKey = tempKey + '-'

    # Reformats the key to be easier to read with the file names
    key = self.createKey( tempKey )

    # Each element is separated into
    keys = key.split( '-' )

    # Concatenates the strings that will be used for filename
    fName = ( keys[0] + '-CommID-Cases-' +
              keys[1] + '-' + keys[2] + '-' +
              keys[3] + 'vs' + keys[4] + '-' +
              keys[5] + '-' + keys[6] +
              '-intDays' + keys[7] )

    # Creates a subdirectory for the data set if it doesn't exist
    subName = ( 'Cases-'+ keys[1] + '-' +
                keys[2] + '-' + keys[3] +
                'vs' + keys[4] + '-' +
                keys[5] + '-' + keys[6] +
                '-intDays' + keys[7] )

    # Calculate to generate map hash table
    start_time = timeit.default_timer()

    # Initialize the hash tables for
    #   the maps files
    self.mapHash = self.initMapHash()

    # End timer
    elapsed = timeit.default_timer() - start_time

    # Calculate to generate map hash table
    start_time = timeit.default_timer()

    # Initialize the hash tables for
    #   the CSV files
    csvHash = self.initCSVHash()

    # End timer
    elapsed = timeit.default_timer() - start_time

    # Check if there is a map for this dataset
    if self.mapHash.get( key ) != None :
      #print( "map key: %s does exist" % key )
      fName = './v2/static/maps/' + subName + '/' + self.mapHash[key]
    else :
      if csvHash.get( key ) == None :
        subprocess.call(["g++", "-o", "hello", "./v2/maptest/hello.cpp"])
        subprocess.call(["./hello"])

        #print( "csv key: %s doesn't exist" % key )

      # Creates a file path for where to store the cases CSV files
      csvPath = os.getcwd() + '/v2/maptest/cases/'+ subName

      # Checks if a directory for the CSV data set exists
      # If not, then we create one
      if not os.path.isdir( csvPath ) :
        try :
          os.mkdir( csvPath )
        except OSError :
          print ("Command mkdir for directory %s has failed." % csvPath)
      else :
        print( 'this csv directory exists' )

      #print( "map key: %s doesn't exist" % key )

      # Creates a file path for where to store the map html files
      mapPath = os.getcwd() + '/v2/static/maps/'+ subName

      # Checks if a directory for the map data set exists
      # If not, then we create one
      if not os.path.isdir( mapPath ) :
        try :
          os.mkdir( mapPath )
        except OSError :
          print ("Command mkdir for directory %s has failed." % mapPath)

      fig = self.generateMap( subName, fName )

      # Add key and value to the HTML hash table
      with open( './v2/maptest/tables/html_table.txt', 'a' ) as fp :
        fp.write( key + ',' + fName + '.html\r\n' )

      fp.close()

      # Update the map hash table
      self.mapHash[key] = ( fName + '.html' )

    return key
#-------------------------------------------------------------

  # Takes a filename and generates the map requested by the user
  def generateMap( self, dirName, fName ) :
    """
    TODO: Create a way to parse a folder from filename

    """
    path = ( './v2/maptest/cases/'+ dirName +
             '/' + fName + '.csv' )

    # Reads in the info from our COVID data set
    df = pd.read_csv(path, dtype={"FIPS": str}, encoding='UTF-8')

    # We manually insert the CommunityID column in the DataFrame
    #   object so it is compatible with the cholopleth parameter
    if fName[:3] != 'ALL' :
      # The color parameter in the choropleth function
      #   only takes in int data types
      df.loc[:,'CommunityID'] = int( fName[0] )

    df['text'] = '' + df['Area_Name'] + ', ' + df['State'] + '' + '
' + \
                 'Pop. Density per Square Mile: ' + str(df['DensityPerSquaremileOfLandarea-Population']) + '
' + \
                 'Median Household Income in 2018: ' + str(df['Median_Household_Income_2018']) + '
' + \
                 '% Adults with High School Diplomas: ' + str(df['Percent_of_adults_with_a_high_school_diploma_only_2014-18'])

    text = df['text'].tolist()

    # Creates the map object and fills it with
    #   information
    fig = px.choropleth(df, geojson=counties, locations='FIPS', color='CommunityID',
                               range_color=[1,7],
                               # color_continuous_scale=px.colors.diverging.RdYlGn[::-1],
                               # color_continuous_scale=px.colors.sequential.OrRd,
                               #color_continuous_scale=([(0.000, 'rgb(175, 45, 36)'), (0.142,'rgb(175, 45, 36)'), # dark red
                               #                          (0.142, 'rgb(193, 78, 79)'), (0.285,'rgb(193, 78, 79)'), # light red
                               #                          (0.285, 'rgb(202, 122, 92)'), (0.428,'rgb(202, 122, 92)'), # nude
                               #                          (0.428, 'rgb(211, 166, 88)'), (0.571,'rgb(211, 166, 88)'), # mustard
                               #                          (0.571, 'rgb(183, 192, 85)'), (0.714,'rgb(183, 192, 85)'), # olive
                               #                          (0.714, 'rgb(143, 174, 98)'), (0.857,'rgb(143, 174, 98)'), # light green
                               #                          (0.857, 'rgb(119, 163, 111)'), (1.000,'rgb(119, 163, 111)')]), # green apple
                               color_continuous_scale=(['rgb(119, 163, 111)', # green apple
                                                        'rgb(143, 174, 98)', # light green
                                                        'rgb(183, 192, 85)', # olive
                                                        'rgb(211, 166, 88)', # mustard
                                                        'rgb(202, 122, 92)', # nude
                                                        'rgb(193, 78, 79)', # light red
                                                        'rgb(175, 45, 36)']), # dark red
                               scope="usa",
                               labels={'State':'State',
                                       'Area_Name':'County',
                                       'DensityPerSquaremileOfLandarea-Population':'Pop. Density per Square Mile of Land Area',
                                       'Median_Household_Income_2018':'Median Household Income in 2018',
                                       'Percent_of_adults_with_a_high_school_diploma_only_2014-18':'% Adults with High School Diplomas',
                                       'FIPS':'',
                                       'CommunityID':''},
                               hover_data=["Area_Name",
                                           "DensityPerSquaremileOfLandarea-Population",
                                           "Median_Household_Income_2018",
                                           "Percent_of_adults_with_a_high_school_diploma_only_2014-18"])
                               #hover_data=["text"])

    # Fixes and displays the legend to the
    #   right of the map
    fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0},
                      coloraxis_colorbar = dict(
                        title = dict(
                          text = "Percentage Change in
the Number of New Cases",
                          font = dict(
                            size = 15)),
                        ticks = 'inside',
                        tickvals = [1, 2, 3, 4, 5, 6, 7],
                        ticktext = ['-100%: BIG DIP', '(-100%, 50%]: DOWNTICK',
                                    '(-50%, 0%): DECREASE', '0%: FLAT',
                                    '(0%, 50%): INCREASE', '[50%, 100%): UPTICK',
                                    'Greater than 100%: SPIKE'],
                        tickfont = dict(
                          size = 10),
                        thickness = 30,
                        xpad = 5,
                        len = 0.75))

    # Displays the figure when program is executed
    #fig.show()

    # Path to the specific directory the file is stored in
    nDir  = ( './v2/static/maps/' + dirName + '/' )

    # Path to where to store the file for the hash table
    nFile = fName + '.html'

    # Creates an html file of the map
    pio.write_html(fig, file= nDir + nFile, auto_open=False)

    return fig
#-------------------------------------------------------------

  # Initializes the CSV Hash Table
  def initCSVHash( self ) :
    # The dictionary that stores all the keys to
    #   the csv file we want to generate maps from
    csvHash = {}

    # Empties out the file before we store new values
    open( './v2/maptest/tables/csv_table.txt', 'w+' ).close()

    # Walks through each subdirectory in /cases/ and
    #   stores the names of the CSVs in csv_table.txt
    for path, subd, files in os.walk( './cases/' ) :
      for names in files:
        keys = names.replace( '.', '-' ).split( '-' )

        # Only the keys and CSV files will be stored
        #   in csv_table.txt
        if keys[-1] == 'csv' :
          # Creates the key for each value in the
          #   CSV hash table
          key = ( keys[0] + '-' + keys[3] +
                  '-' + keys[4] + '-' + keys[5][:2] +
                  '-' + keys[5][-2:] + '-' + keys[6] +
                  '-' + keys[7] + '-' + keys[-2][7:] )

          # Writes the values to csv_table.txt
          with open( './v2/maptest/tables/csv_table.txt', 'a+' ) as fp :
            fp.write( key + ',' + names + '\r\n' )

          fp.close()

    with open( './v2/maptest/tables/csv_table.txt', 'r' ) as fp :
      lines = fp.read().replace( '\r', '' ).split( '\n' )

    # Checks if the file is not empty
    if lines[0] != '' :
      for line in lines :
        line = line.split( ',' )

        key = line[0]

        # Indicates an end of file
        if key == '' :
          val = ''
        else :
          val = line[1]

        csvHash[key] = val

    return csvHash
#-------------------------------------------------------------

  # Initializes the Map Hash Table
  def initMapHash( self ) :
    # The dictionary that stores all the keys to
    #   the html file we want to display to the
    #   home page iframe
    mHash = {}

    with open( './v2/maptest/tables/html_table.txt', 'r' ) as fp :
      lines = fp.read().replace( '\r', '' ).split( '\n' )

    fp.close()

    # Checks if the file is not empty
    if lines[0] != '' :
      for line in lines :
        line = line.split( ',' )

        key = line[0]

        # Indicates an end of file
        if key == '' :
          val = ''
        else :
          val = line[1]

        mHash[key] = val

    return mHash
#-------------------------------------------------------------

  # Formats the key of the hash table to be similar
  #   the names of all the .csv and .html files
  def createKey( self, tempKey ) :
    key = ''
    front = ''
    middle = ''
    end = ''

    if( tempKey.endswith('ALL') ) :
      # Holds the ALL part of the string to be moved
      #   to the front of a key
      front = tempKey[-3:]

      if tempKey[1] == '-' :
        # Rearranges the string for key in order for
        #   it to fit the format of each files that
        #   will need to be read in
        middle = tempKey[1:-3]
        end    = tempKey[:1]
      else :
        middle = tempKey[2:-3]
        end = tempKey[:2]
    else :
      # Otherwise, last element in the key will be
      #   a single digit
      front = tempKey[-1:]

      if tempKey[1] == '-' :
        middle = tempKey[1:-1]
        end = tempKey[:1]
      else :
        middle = tempKey[2:-1]
        end = tempKey[:2]

    key = front + middle + end

    return key
#-------------------------------------------------------------

  def get_maphash( self ) :
    return self.mapHash
#-------------------------------------------------------------

# This is how you'll call the class
# test = map_test( 7, '04-JUL-20', '04-AUG-20', 2 )
# test = map_test( 30, '04-JUL-20', '04-AUG-20', 8 )
# key = test.main()