from django.contrib import admin
from django.urls import path, include
from django.urls import re_path as url
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions
from metric import views

schema_view = get_schema_view(
    openapi.Info(
        title="Snippets API",
        default_version='v1',
        description="Test description",
        terms_of_service="https://www.google.com/policies/terms/",
        contact=openapi.Contact(email="contact@snippets.local"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=[permissions.AllowAny],
)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/metric/', views.metric_api, name="metric_api"),
]

# swagger
urlpatterns += [
    url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),  # noqa E501
    url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),  # noqa E501
    url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),  # noqa E501
]


#!/usr/bin/env python3
import sys
import os
import socket
import json
import yaml

host_list = ('drive.google.com', 'mail.google.com', 'google.com')
host_for_tests = {}
host_for_tests2 = {}

for host_site in host_list: # выполним первую проверку и заполним словать с элементами сайт:IP
    ip_site = socket.gethostbyname(host_site)
    host_for_tests [host_site] = ip_site
    host_for_tests2 [host_site] = [ip_site, 'default']

with open ('host_for_tests.json','w') as json_log:
    json_log.write (json.dumps(host_for_tests2, indent=2))

with open ('host_for_tests.yaml','w') as yaml_log:
    yaml_log.write (yaml.dump(host_for_tests2, indent=2, explicit_start=True, explicit_end=True))

print ('Будем мониторить данные сайты и их дефолтные IP полученные в результе первой проверки:' + '\n' + str(host_for_tests))

#print (type(list_ip))
print ('\n'+'\n'+'Погнали, проверяем доступность сайтов в цикле')
while True: # запустим бесконечный цикл проверок внутри которого будем проверять сайты из словаря
    for host_site, ip_site in host_for_tests.items():  # цикл проверки по словарю в котором элементы состоят из сайт:IP
        ip_current = socket.gethostbyname(host_site)
        #ip_current = '192.168.1.1' # ручной "стоп-кран" чтоб не гонять долго цикл
        if ip_current == ip_site:
            print (host_site + ':  текущий IP - ' +ip_current + ', IP из первой проверки - '+ ip_site )
        else:
            print ('Для '+host_site + ' IP не сходятся, было - ' + ip_site + ', стало - '+ ip_current)

            #print (f'[ERROR] {host_site} IP mismatch: {ip_site} {ip_current}')
            print ('\n')
            my_error_to_stdout = sys.stdout
            my_error_to_stdout.write(f'[ERROR] {host_site} IP mismatch: {ip_site} {ip_current}')
            host_for_tests = {host_site: ip_current}
            host_for_tests2 [host_site] = [ip_current, 'new']

            #print ('\n')
            #print (host_for_tests2)

            #перезапишем файлики с обновленным словарем
            # в идеале конечно нужно было:
		#	1. загрузить в словарь данные из json и yaml файлов;
		#	2. обновить по ключу сбойный IP или даже удалить элемент из словаря со сбойным IP и добавить обратно новый
		#	3. записать словать обратно в 2 файла
		#	4. но т.к. мы все равно записываем словарь целиком, то думаю можно и так, заново записав словарь поверх текущих данных.
		#	5. значения в словаре представлены ввиде списка, так что бы наглядно было видно какой именно IP изменился.
            with open ('host_for_tests.json','w') as json_log:
                 json_log.write (json.dumps(host_for_tests2, indent=2))

            with open ('host_for_tests.yaml','w') as yaml_log:
                 yaml_log.write (yaml.dump(host_for_tests2, indent=2, explicit_start=True, explicit_end=True))

            exit ()


from dataclasses import dataclass, field
from typing import Iterable, List, Optional

from dataclasses_json import LetterCase, dataclass_json

from ..core import AttributeDef, Cardinality, EntityDef, ObjectId, TypeCategory, RelationshipEndDef, RelationshipDef
from ..data_dictionary import (BusinessDataset, BusinessDatasetAttributes,
                               BusinessDatasetAttributesBase,
                               BusinessDatasetAttributesDefaultsBase,
                               BusinessDatasetBase,
                               BusinessDatasetDefaultsBase)

dashboard_super_type = ["m4i_dataset"]

dashboard_attributes_def = [
    AttributeDef(
        name="updatedAt",
        type_name="string"
    ),
    AttributeDef(
        name="version",
        type_name="string"
    ),
    AttributeDef(
        name="creator",
        type_name="array<m4i_person>",
        cardinality=Cardinality.SET
    ),
    AttributeDef(
        name="elasticCluster",
        type_name="array<m4i_elastic_cluster>",
        cardinality=Cardinality.SET
    ),
    AttributeDef(
        name="kibanaSpace",
        type_name="array<m4i_kibana_space>",
        cardinality=Cardinality.SET
    ),
]

dashboard_def = EntityDef(
    category=TypeCategory.ENTITY,
    name="m4i_dashboard",
    description="A type definition for a generic Dashboard in the context of models4insight.com",
    type_version="1.0",
    super_types=dashboard_super_type,
    attribute_defs=dashboard_attributes_def
)
end_1_kibana_dashboard = RelationshipEndDef(
    type="m4i_kibana_space",
    name="dashboards",
)
end_2_kibana_dashboard = RelationshipEndDef(
    type="m4i_dashboard",
    name="kibanaSpace",
)

m4i_kibana_dashboard_rel_def = RelationshipDef(
    end_def1=end_1_kibana_dashboard,
    end_def2=end_2_kibana_dashboard,
    name="m4i_kibana_space_dashboard_assignment",
    category=TypeCategory.RELATIONSHIP
)

end_1_person_dashboard = RelationshipEndDef(
    type="m4i_person",
    name="dashboards",
)
end_2_person_dashboard = RelationshipEndDef(
    type="m4i_dashboard",
    name="creator",
)

m4i_person_dashboard_rel_def = RelationshipDef(
    end_def1=end_1_person_dashboard,
    end_def2=end_2_person_dashboard,
    name="m4i_person_dashboard_assignment",
    category=TypeCategory.RELATIONSHIP
)

end_1_elastic_cluster_dashboard = RelationshipEndDef(
    type="m4i_elastic_cluster",
    name="dashboards",
)
end_2_elastic_cluster_dashboard = RelationshipEndDef(
    type="m4i_dashboard",
    name="elasticCluster",
)

m4i_elastic_cluster_dashboard_rel_def = RelationshipDef(
    end_def1=end_1_elastic_cluster_dashboard,
    end_def2=end_2_elastic_cluster_dashboard,
    name="m4i_elasticCluster_dashboard_assignment",
    category=TypeCategory.RELATIONSHIP
)

@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass
class DashboardAttributesBase(BusinessDatasetAttributesBase):
    pass

# END DashboardAttributesBase

@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass
class DashboardAttributesDefaultsBase(BusinessDatasetAttributesDefaultsBase):
    updated_at: Optional[str] = None
    version: Optional[str] = None
    elastic_cluster: List[ObjectId] = field(default_factory=list)
    kibana_space: List[ObjectId] = field(default_factory=list)
    creator: List[ObjectId] = field(default_factory=list)

# END DashboardAttributesBase

@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass
class DashboardAttributes(BusinessDatasetAttributes,
                          DashboardAttributesDefaultsBase, DashboardAttributesBase):
    pass

# END DashboardAttributes

@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass
class DashboardBase(BusinessDatasetBase):
    attributes: DashboardAttributes

# END DashboardBase

@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass
class DashboardDefaultsBase(BusinessDatasetDefaultsBase):
    pass

# END DashboardDefaultsBase

@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass
class Dashboard(
    BusinessDataset,
    DashboardDefaultsBase,
    DashboardBase,
):
    type_name: str = "m4i_dashboard"

    @classmethod
    def get_type_def(cls):
        return dashboard_def

    def get_referred_entities(self) -> Iterable[ObjectId]:
        """
        Returns the following references for this Dashboard:
        * List of Kibana Space
        * List of Elastic Cluster
        * List of Atlas Person
        """

        references = [
            *super().get_referred_entities(),
            *self.attributes.kibana_space,
            *self.attributes.elastic_cluster,

        ]

        if self.attributes.creator is not None:
            references = [*references, *self.attributes.creator]
        # END IF

        return filter(None, references)
    # END get_referred_entities

# END Dashboard


from collections import defaultdict
t = int(input())

for i in range(t):
    n =  int(input())
    d = defaultdict(int)
    line = input().split()
    arr = []
    for i in range(n):
        arr.append(int(line[i]))

    x = abs(arr[0] - arr[1])
    d[x] += 1
    for i in range(2,n):
        x = abs(arr[0]-arr[i])/i
        d[x] += 1

    keys = list(d.keys())
    diff = 0
    if(len(keys)>2):
        diff = arr[2]-arr[1]

    else:
        max = 0
        for i in range(len(keys)):
            if(d[keys[i]]>max):
                max = d[keys[i]]
                diff = int(keys[i])

    ans = []
    for i in range(1,len(arr)-1):
        x = abs(arr[i] - arr[i-1])
        y = abs(arr[i] - arr[i+1])

        if(x!=diff and y!=diff):
            ans.append(i)

    if(ans==[]):
        x = abs(arr[0]-arr[1])
        y = abs(arr[-1]-arr[-2])

        if(x!=diff):
            ans.append(0)

        elif(y!=diff):
            ans.append(-1)

    if(ans==[]):
        print(*arr)
    else:
        pos = ans[0]

        if(pos == 0):
            arr[pos] = arr[pos+1]-diff

        else:
            arr[pos] = arr[pos-1]+diff

        print(*arr)


from discord.ext import commands
import re
import discord
import asyncio
from datetime import datetime
import unicodedata
import aiohttp

class NameChanger:
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name="check")
    @commands.has_permissions(manage_nicknames=True)
    @commands.guild_only()
    async def nickname_checker(self, ctx, output="channel"):
        """This will check if someone has special characters in their nickname and will either give you a list of all
        users who have special characters in their name or will directly change them.
        Example: っ, !, ◔
        """
        def check(reaction, user):
            return user == ctx.message.author and str(reaction.emoji) == '👍'

        server = ctx.message.guild
        membercount = server.member_count
        check_change = False
        # checks if the bot has the ability to change nicknames, if yes asks the user if he/she wants to get the list
        # or wants the nicknames directly changed
        if ctx.message.guild.me.guild_permissions.manage_nicknames:
            msg = await ctx.send("Would you like me to change all nicknames which contain special characters? If yes"
                                 " please add the `👍` emote as reaction.\nIf you don't want me to do it you don't have"
                                 " to do anything")
            await msg.add_reaction("👍")
            try:
                await self.bot.wait_for('reaction_add', timeout=15.0, check=check)
                check_change = True
            except asyncio.TimeoutError:
                pass
        else:
            check_change = False
        if check_change:
            text = f"""Okay. I will now check {membercount} members if their nicknames don't
contain special characters."""
            if membercount > 100:
                text = text + f" This might take a while."
            await ctx.send(text)
            counter = 0
            changed_users = ""
            could_be_changed = ""
            time_before = datetime.utcnow()
            for member in server.members:
                m_nick = member.display_name
                changed_nick = self.nickname_maker(m_nick)
                if m_nick != changed_nick:
                    # checks if a user can change his nickname if he is able to his nick will not be changed
                    try:
                        await member.edit(reason=f"Old name ({m_nick}) contained special characters.",
                                          nick=changed_nick)
                        changed_users = changed_users + f"{member.name}: {m_nick} was changed to {changed_nick}\n"
                    except commands.MissingPermissions:
                        could_be_changed += f"{member.name}: {m_nick} could be changed to {changed_nick}\n"
                    counter += 1

            if counter == 0:
                link = await self.mystbin(stringx="No users with special characters in their nicknames could be found.")
            else:
                link = await self.mystbin(stringx=f"Found {counter} members:\n{changed_users}\n\nThe nicknames of foll"
                                                  f"owing users couldn't be changed:\n{could_be_changed}")
            time_after = datetime.utcnow()
            difference = time_after - time_before
            difference = round(difference.total_seconds() / 60.0, 1)
            embed = discord.Embed(
                color=discord.Color.green(),
                title="Successfully finished!",
                description=f"Changed {counter} nicknames in {difference} minutes. Here is a list with all changes: "
                            f"{link}",
                timestamp=datetime.utcnow()
            )
            embed.set_author(name=f"{ctx.message.author}", icon_url=f"{ctx.message.author.avatar_url}")
            if output == "channel":
                await ctx.send(embed=embed)
            else:
                if output == "channel":
                    await ctx.send(embed=embed)
                else:
                    await ctx.message.author(embed=embed)
        else:
            # only returns the list
            await ctx.send("Okay. I will create a file now with all users who have special characters in their name.")
            changed_users = ""
            counter_ = 0
            time_before = datetime.utcnow()
            for member in server.members:
                m_nick = member.display_name
                changed_nick = self.nickname_maker(m_nick)
                if m_nick != changed_nick:
                    counter_ += 1
                    changed_users += f"{member.name}: {m_nick} could be changed to {changed_nick}\n"
            time_after = datetime.utcnow()
            difference = time_after - time_before
            difference = round(difference.total_seconds() / 60.0, 1)
            if changed_users == "":
                link = await self.mystbin(stringx="No users with special characters in their nicknames could be found.")
            else:
                link = await self.mystbin(stringx=f"Found {counter_} members:\n{changed_users}")
            embed = discord.Embed(
                color=discord.Color.green(),
                timestamp=datetime.utcnow(),
                title="Successfully finished!",
                description=f"Found {counter_} members with special characters in their nickname in "
                            f"{difference} minutes.\nHere is the link to the list: {link}",
            )
            embed.set_author(name=f"{ctx.message.author}", icon_url=f"{ctx.message.author.avatar_url}")

    @staticmethod
    def strip_accents(text):
        try:
            text = unicodedata.normalize('NFD', text)
            text = text.encode('ascii', 'ignore')
            text = text.decode("utf-8")
        except Exception as e:
            print(e)
            pass
        return str(text)

    def nickname_maker(self, old_nick):
        old_nick = self.strip_accents(old_nick)
        changed_nick = re.sub('[^a-zA-Z0-9 \n.]', '', old_nick)
        if len(changed_nick.replace(" ", "")) <= 1:
            changed_nick = "Request a new nickname"
        return changed_nick

    @nickname_checker.error
    async def nickname_error(self, ctx, error):
        # error handler
        if isinstance(error, commands.MissingPermissions):
            return
        elif isinstance(error, commands.NoPrivateMessage):
            return
        elif isinstance(error, commands.CommandError):
            embed = discord.Embed(
                color=discord.Color.red(),
                title="Something didn't go quite right...",
                description="I will report this error."
            )
            embed.set_author(name=f"{ctx.message.author}", icon_url=f"{ctx.message.author.avatar_url}")
            await ctx.send(embed=embed)
            print(error)

    @commands.command(name="setnick")
    @commands.guild_only()
    @commands.has_permissions(manage_nicknames=True)
    @commands.bot_has_permissions(manage_nicknames=True)
    async def setnick_cmd(self, ctx, user: discord.Member=None, *, nickname: str=None):
        """Changes the nickname of a specified user to a specified nickname."""
        if nickname is None or user is None and len(nickname) >= 2:
            embed = discord.Embed(
                color=discord.Color.red(),
                title="An error occurred.",
                description=f"Please follow the format: `{ctx.prefix}setnick {'user'} {'new nickname'}`.\n"
                            f"If you followed the format please make sure that the new nickname is at least two chara"
                            f"cters long."
            )
            return await ctx.send(embed=embed)
        await user.edit(nick=nickname, reason=f"Nickname edit by {ctx.message.author.name} ({ctx.message.author.id})")
        embed = discord.Embed(
            color=discord.Color.green(),
            title=f"Successfully changed {user}'s nickname.",
            description=f"New nickname: {nickname}\nOld nickname: {user.display_name}"
        )
        await ctx.send(embed=embed)

    @setnick_cmd.error
    async def setnick_error(self, ctx, error):
        # error handler
        if isinstance(error, commands.CheckFailure):
            return
        elif isinstance(error, commands.NoPrivateMessage):
            return
        elif isinstance(error, commands.BotMissingPermissions):
            embed = discord.Embed(
                color=discord.Color.red(),
                title="I am missing a necessary permission.",
                description="Please make sure I have the manage nicknames permission."
            )
            await ctx.send(embed=embed)
        elif isinstance(error, commands.CommandError):
            embed = discord.Embed(
                color=discord.Color.red(),
                title="Something didn't go quite right...",
                description="I will report this error."
            )
            embed.set_author(name=f"{ctx.message.author}", icon_url=f"{ctx.message.author.avatar_url}")
            await ctx.send(embed=embed)
            print(error)

    @staticmethod
    async def mystbin(stringx):
        async with aiohttp.ClientSession() as session:
            async with session.post("http://mystb.in/documents", data=stringx.encode('utf-8')) as post:
                post = await post.json()
        return f"http://mystb.in/{post['key']}.txt"

def setup(bot):
    bot.add_cog(NameChanger(bot))


import os
from osrf.app import Application
import osrf.log
import pairtree

class Storage(Application):

    Application.register_method(
        api_name='psu.stewardship.storage.store',
        method='store',
        argc=3,
        stream=False
        )
    def store(self, request, base_location, identifier, source):
        f = pairtree.PairtreeStorageFactory()
        tree_location = os.path.join(base_location, "stewardship")
        pairstore = f.get_store(store_dir=tree_location, uri_base="ark://")
        pairobj = pairstore.create_object(identifier)
        pairobj.add_directory(source)
        request.respond(pairobj.location)

Application.register_app(Storage())


import datetime
import os
import matplotlib
import numpy as np
import pandas as pd
matplotlib.use('agg')
import matplotlib.pyplot as plt

"""
Evolution d'une espèce avec le temps
"""

def one_species_evolution_function(data: pd.DataFrame, species: str, with_cf: bool, location: str, user_id: str) -> None:
    # dossier d'export
    directory = "files/one_species_evolution_" + user_id
    if not os.path.exists(directory):
        os.makedirs(directory)

    year = data.iloc[-1]["Date"].year
    month = data.iloc[-1]["Date"].month
    last_date = datetime.datetime(year=year, month=month, day=28)

    # Filtrer espèce
    data = data.loc[data["Espèce"] == species]

    # Filtrer lieu
    if location != "Tous les lieux":
        data = data.loc[data["Lieu"] == location]

    # Si sans cf
    if not with_cf:
        data = data.loc[data["cf"] != "cf."]

    # Enregistrer le fichier excel
    writer = pd.ExcelWriter(directory + '/one_species_evolution.xlsx', engine='xlsxwriter', datetime_format='dd.mm.yyyyy', date_format='dd.mm.yyyyy')

    # Création du graphique cumulation de l'espèce
    total_obs = cumulative_observations(data, last_date)
    total_obs.to_excel(writer, sheet_name='Toutes les observations')
    plt.figure()
    plt.plot(total_obs.index, total_obs["Observations cumulées"],
             label="Observations totales")

    plt.ylabel("Nombre d'observations")
    plt.title("Evolution du nombre d'observations de " + species)
    plt.ylim(ymin=0)
    plt.legend(loc="upper left")
    plt.savefig(directory + "/observations_cumulees_par_mois.svg", bbox_inches='tight')

    # Observations par troncs
    plt.figure()
    for trunk in data["Tronc"].dropna().unique():
        trunk_obs = data.loc[(data["Tronc"] == trunk)]
        trunk_obs = cumulative_observations(trunk_obs, last_date)
        if len(trunk_obs) > 0:
            plt.plot(trunk_obs.index, trunk_obs["Observations cumulées"],
                     label="Tronc " + str(trunk))
            trunk_obs.to_excel(writer, sheet_name="Observations sur tronc " + trunk)

    plt.ylabel("Nombre d'observations")
    plt.title("Evolution du nombre d'observations de " + species + " sur troncs")
    plt.ylim(ymin=0)
    plt.legend(loc="upper left")
    plt.savefig(directory + "/observations_cumulees_par_mois_troncs.svg", bbox_inches='tight')

    # Observations par groupes troncs
    plt.figure()
    for trunk_group in data["Groupe troncs"].dropna().unique():
        trunk_group_obs = data.loc[(data["Groupe troncs"] == trunk_group)]
        trunk_group_obs = cumulative_observations(trunk_group_obs, last_date)
        if len(trunk_group_obs) > 0:
            plt.plot(trunk_group_obs.index, trunk_group_obs["Observations cumulées"],
                     label="Groupe de troncs " + str(trunk_group))
            trunk_group_obs.to_excel(writer, sheet_name="Observations groupe tronc " + trunk_group)

    plt.ylabel("Nombre d'observations")
    plt.title("Evolution du nombre d'observations de " + species + " sur groupes de troncs")
    plt.ylim(ymin=0)
    plt.legend(loc="upper left")
    plt.savefig(directory + "/observations_cumulees_par_mois_groupe_troncs.svg", bbox_inches='tight')

    # Observations par espèces de troncs
    plt.figure()
    for trunk_species in data["Espèce du tronc"].dropna().unique():
        trunk_species_obs = data.loc[(data["Espèce du tronc"] == trunk_species)]
        trunk_species_obs = cumulative_observations(trunk_species_obs, last_date)
        if len(trunk_species_obs) > 0:
            plt.plot(trunk_species_obs.index, trunk_species_obs["Observations cumulées"],
                     label=str(trunk_species))
            trunk_species_obs.to_excel(writer, sheet_name="Observations sur " + trunk_species)

    plt.ylabel("Nombre d'observations")
    plt.title("Evolution du nombre d'observations de " + species + " sur espèces de troncs")
    plt.ylim(ymin=0)
    plt.legend(loc="upper left")
    plt.savefig(directory + "/observations_cumulees_par_mois_especes_troncs.svg", bbox_inches='tight')

    writer.save()

def cumulative_observations(data: pd.DataFrame, last_date) -> pd.DataFrame:
    count = data[["Date", "Espèce"]].groupby(pd.Grouper(key='Date', freq='1M')).count()
    observations = pd.DataFrame([], )
    observations["Observations"] = count["Espèce"]
    observations["Observations cumulées"] = observations.cumsum()
    observations_last_date = observations.iloc[-1].name

    # Ajouter une ligne de la dernière date du dataframe total si absente
    if len(observations) > 0:
        if observations_last_date < last_date:
            new_row = observations.iloc[-1:]
            new_row = new_row.rename(index={observations_last_date: last_date})
            new_row['Observations'] = 0
            observations = pd.concat([observations, new_row])

    return observations


import os
import json

import numpy as np
import hydra
import torch
from torch.nn import functional as F
from sklearn.metrics import f1_score

from src.classifier.utils import store_preds
from src.classifier.visualizers.plots import plot_conf_matrix

def evaluate(
    model, test_loader, texts_test, classes, name_str, output_path, plot=False
):
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model.eval()
    model = model.to(device)
    num_correct = 0
    n_classes = len(classes)
    confusion_matrix = torch.zeros(n_classes, n_classes)
    preds_all = []
    labels_all = []

    for inputs, labels in test_loader:
        inputs, labels = inputs.float().to(device), labels.long().to(device)
        test_outputs = model(inputs)
        if isinstance(test_outputs, tuple):
            test_outputs = test_outputs[0]
        probs = F.log_softmax(test_outputs, dim=1)
        preds = torch.argmax(probs, dim=1)
        preds_all += preds.float()
        labels_all += labels.float()

    preds_all, labels_all = torch.tensor(preds_all), torch.FloatTensor(labels_all)
    correct_tensor = preds_all.eq(labels_all.view_as(preds_all))
    correct = np.squeeze(correct_tensor.cpu().numpy())
    num_correct += np.sum(correct)
    num_per_class = {c: 0 for c in classes}
    for t, p in zip(labels_all, preds_all):
        num_per_class[int(p.item())] += 1
        confusion_matrix[t.long(), p.long()] += 1

    print(f"Confusion matrix: {confusion_matrix}")
    acc_list = confusion_matrix.diag() / confusion_matrix.sum(1)
    acc_per_class = dict(zip(classes, acc_list))
    mean_acc = np.mean(acc_list.cpu().numpy())
    mean_f1_macro = f1_score(
        labels_all.cpu().numpy(),
        preds_all.cpu().numpy(),
        labels=list(classes),
        average="macro",
    )
    mean_f1_micro = f1_score(
        labels_all.cpu().numpy(),
        preds_all.cpu().numpy(),
        labels=list(classes),
        average="micro",
    )
    print(f"Num per class: {num_per_class}")
    print(f"Test Accuracy per class: {acc_per_class}")
    print(f"Test Accuracy averaged: {mean_acc}")
    print(f"Test F1-score macro-averaged: {mean_f1_macro}")
    print(f"Test F1-score micro-averaged: {mean_f1_micro}")
    conf_matrix_npy = confusion_matrix.cpu().numpy()
    if plot:
        os.makedirs(output_path, exist_ok=True)
        plot_conf_matrix(conf_matrix_npy, output_path, f"conf_matrix_{name_str}")

    store_preds(output_path, name_str, preds_all, labels_all, texts_test)
    results_dict = {
        "acc_per_class": str(acc_per_class),
        "mean_acc": str(mean_acc),
        "mean_f1_macro": str(mean_f1_macro),
        "mean_f1_micro": str(mean_f1_micro),
    }
    with open(os.path.join(output_path, f"results_{name_str}.json"), "w") as outfile:
        json.dump(results_dict, outfile)
    np.save(os.path.join(output_path, f"conf_matrix.npy"), conf_matrix_npy)
    return mean_acc, results_dict, conf_matrix_npy


from django.urls import path
from order.views import (
    OrderView,
    OrderInfoDetailView,
    PayInfoView,
)

urlpatterns = [
    path('', OrderView.as_view(), name = 'order_info'),
    path('<int:id>/', OrderInfoDetailView.as_view(), name = 'order_info_detail'),
    path('pay_info/', PayInfoView.as_view(), name = 'pay_info'),
]


import jsonschema, yaml
from dsh import main, node, evaluators, matchers, api, executors

from flange import cfg, model as flmd

from click.testing import CliRunner

FG = cfg.Cfg(
    data=main.DSH_FLANGE_PLUGIN,
    root_path='prj',
    file_patterns=['example.yml'],
    base_dir='.',
    file_search_depth=1)

import os
PATH_EXAMPLE = os.path.join(os.path.dirname(__file__), 'example.yml')
with open(PATH_EXAMPLE) as f:
    DSH_EXAMPLE = yaml.safe_load(f)

MODULE_NAME = __name__.replace('.', '/')

def test_dsh_schema():

    # First make sure the example conforms to the schema
    jsonschema.validate(DSH_EXAMPLE, main.DSH_SCHEMA)

    # Then, check that flange discovers the example as in instance of the model
    f = cfg.from_file('tests/example.yml', root_path='root',)
    f.register_model('dshnode', flmd.Model('dshnode', flmd.Model.get_schema_validator(main.DSH_SCHEMA), main.node_factory_context))
    assert f.obj('root', model='dshnode')

def test_config_model_registration():
    # The initial data contains the test plugin registation
    cmdroot = FG.obj('prj')

    path = cmdroot.resolve('platform')
    assert path.match_result.completions == ['up', 'stop', 'ps', 'build']

    path = cmdroot.resolve('platform build')
    assert path.match_result.completions == []

def test_context_vars():

    cmdroot = FG.obj('prj')
    prod = [x for x in cmdroot.get_children() if x.name == 'prod'][0]

def test_nested_do():

    cmdroot = FG.obj('prj')
    path = cmdroot.resolve('cmd_do_nested')
    path.execute()
    print(cmdroot)

def test_on_failure():
    cmdroot = FG.obj('prj')
    cmdroot.resolve('platform build', 'MODE_EXECUTE').execute()

# def test_context_cmd_do_after_simple():
#
#     cmdroot = FG.obj('tests', model='dshnode')
#     path = cmdroot.resolve('platform build')
#     path.execute()
#     print cmdroot
#

# def test_main():

#     data = {

#     }
#     f = main.get_flange_cfg(
#         options=None,
#         root_ns=main.DSH_DEFAULT_ROOT,
#         base_dir=['test'],
#         file_patterns=['.dsh*.yml'],
#         file_search_depth=0,
#         initial_data=data)

#     roots = f.objs(main.DSH_DEFAULT_ROOT, model='dshnode')
#     assert roots

# def test_cli():
#   runner = CliRunner()
#   result = runner.invoke(main.cli, ['--exist_on_init', True])
#   assert result.exit_code == 0


from random import choice, randrange
from collections import Counter

class NQueensSearch:
    def __init__(self, N):
        self.N = N

    '''
        return random list of n items , each item indicate queen's index
        in it's column
    '''

    def initial(self):
        return list(randrange(self.N) for i in range(self.N))

    def initial_plus(self, initial=50):
        states = [list(randrange(self.N) for i in range(self.N)) for i in range(initial)]
        best =  max(states, key=lambda state: self.heuristic(state))
        h = self.heuristic(best)
        return best

    '''
        given state , returns true if the state is goal state, else false
    '''
    def goal_test(self, state):
        a = set()
        b = set()
        c = set()
        for row, col in enumerate(state):
            if col in a or row - col in b or row + col in c:
                return False
            a.add(col)
            b.add(row - col)
            c.add(row + col)
        return True

    def heuristic(self, state):
        a, b, c = [Counter() for i in range(3)]
        for row, col in enumerate(state):
            a[col] += 1
            b[row - col] += 1
            c[row + col] += 1
        h = 0
        for count in [a, b, c]:
            for key in count:
                h += count[key] * (count[key] - 1) / 2
        return -h

    def nearStates(self, state):
        near_states = []
        for row in range(self.N):
            for col in range(self.N):
                if col != state[row]:  # not in same column
                    temp = list(state)
                    temp[row] = col
                    near_states.append(list(temp))
        return near_states

    def randomNearState(self, state):
        randomRow = randrange(self.N)
        randomCol = randrange(self.N)
        counter = 0
        while counter < 4000:
            if randomCol != state[randomRow]:  # not in same column
                temp = list(state)
                temp[randomRow] = randomCol
                return list(temp)
            counter += 1
        return choice(self.nearStates(state))


import discord
from discord import member
from discord import message
from discord.ext import commands
from datetime import datetime
import asyncio

class Moderation(commands.Cog):
    def __init__(self, client):
        self.client = client

    # Mute Command
    @commands.command(pass_context = True)
    async def mute(self, ctx, member: discord.Member):
        if ctx.message.author.server_permissions.administrator:
            role = discord.utils.get(member.server.roles, name='Muted')
            await ctx.add_roles(member, role)
            embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
            await ctx.send(embed=embed)
        else:
            embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
            await ctx.send(embed=embed)

    # Unmute Command
    @commands.command(description="Unmutes a specified user.")
    @commands.has_permissions(manage_messages=True)
    async def unmute(self, ctx, member: discord.Member):
        mutedRole = discord.utils.get(ctx.guild.roles, name="Muted")

        await member.remove_roles(mutedRole)
        try:
            await member.send(f" you have unmutedd from: - {ctx.guild.name}")
        except:
            await ctx.send("The member's dms were closed!")

        embed = discord.Embed(title="unmute", description=f" unmuted-{member.mention}",colour=discord.Colour.light_gray())
        await ctx.send(embed=embed)

    # Kick Command
    @commands.command()
    @commands.has_permissions(kick_members=True)
    async def kick(ctx, member: discord.Member, *, reason=None):
        if reason==None:
            reason=" no reason provided"

        await ctx.guild.kick(member)
        await ctx.send(f'User {member.mention} has been kicked for {reason}')

    # Ban Command
    class DurationConverter(commands.Converter):
        async def convert(self, ctx, argument):
            amount = argument[:-1]
            unit = argument[-1]

            if amount.isdigit() and unit in ['s', 'm']:
                return (int(amount), unit)

            raise commands.BadArgument(message="Not a valid duration!")

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: commands.MemberConverter, duration: DurationConverter):

        multiplier = {'s': 1, 'm': 60}
        amount, unit = duration

        await ctx.guild.ban(member)
        await ctx.send(f"{member} has been banned from {ctx.guild.name} for {amount}{unit}")
        await asyncio.sleep(amount * multiplier[unit])
        await ctx.guild.unban(member)

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def tempban(self, ctx, member: commands.MemberConverter, duration: DurationConverter):
        await ctx.guild.ban(member)
        await ctx.send(f"{member} has been banned from {ctx.guild.name}")

    # Unban Command
    @commands.command()
    async def unban(self, ctx, *,member):
        banned_user = await ctx.guild.bans()

        member_name, member_discriminator = member.split('#')
        for ban_entry in banned_user:
            user = ban_entry.user

        if (user.name, user.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f'Unbanned {user.mention}')

    @commands.command()
    # @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, amount: int):
        await ctx.channel.purge(limit=amount)
        await ctx.send("THE MESSAGES ARE DELETED", delete_after=2)

def setup(client):
    client.add_cog(Moderation(client))


#! /usr/bin/env python
import os
import sys
from tempfile import NamedTemporaryFile
import unittest

try:
    import mock
except:
    from unittest import mock

try:
    from cStringIO import StringIO
except:
    from io import StringIO

try:
    from ConfigParser import SafeConfigParser
except:
    from configparser import SafeConfigParser

from contextlib import contextmanager

try:
    from configutil import Config, ConfigError, \
        MissingSection, SectionError, ConfigArgumentError
except:
    from configutil.configutil import Config, ConfigError, \
        MissingSection, SectionError, ConfigArgumentError

@contextmanager
def capture(command, *args, **kwargs):
    out, sys.stdout = sys.stdout, StringIO()
    err, sys.stderr = sys.stderr, StringIO()
    try:
        command(*args, **kwargs)
        sys.stdout.seek(0)
        sys.stderr.seek(0)
        yield (sys.stdout.read().strip(), sys.stderr.read().strip())
    finally:
        sys.stdout = out
        sys.stderr = err

class TestConfigutil(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.config_path = NamedTemporaryFile().name

        parser = SafeConfigParser()
        parser.add_section('section0')
        parser.set('section0', 'arg0a', '1234.123')
        parser.set('section0', 'arg0b', 'True')
        parser.set('section0', 'arg0c', 'False')
        parser.add_section('section1')
        parser.set('section1', 'arg1a', 'configstring1a')
        parser.set('section1', 'arg1b', 'configstring1b')
        parser.set('section1', 'arg1c', '1000')

        with open(cls.config_path, 'w') as file:
            parser.write(file)

        cls.missing_path = NamedTemporaryFile().name

        parser = SafeConfigParser()
        parser.add_section('section0')
        parser.set('section0', 'arg0a', '1234.123')
        parser.add_section('section1')
        parser.set('section1', 'arg1c', '1000')

        with open(cls.missing_path, 'w') as file:
            parser.write(file)

    def setup_config(self, path):
        config = Config()

        if type(path) == list:
            config.add_paths(path)
        else:
            config.add_path(path)

        section = config.add_section('section0')
        section.add_argument('arg0a', 'a float', float)
        section.add_argument('arg0b', 'a boolean', bool)
        section.add_argument('arg0c', 'a boolean', bool)

        section = config.add_section('section1')
        section.add_argument('arg1a', 'a string', str)
        section.add_argument('arg1b', 'a string', str)
        section.add_argument('arg1c', 'an int', int)

        return config

    def test_error_creation(self):
        error = ConfigError('arg_name')
        self.assertEquals(error.arg, 'arg_name')
        self.assertEquals(error.message, 'Missing configuration argument "arg_name".')

        error = MissingSection('section_name')
        self.assertEquals(error.arg, 'section_name')
        self.assertEquals(error.message, 'Missing section "section_name" in configuration.')

        error = SectionError('section_name')
        self.assertEquals(error.arg, 'section_name')
        self.assertEquals(error.message, 'Section "section_name" does not exist in configuration.')

        error = ConfigArgumentError('arg_name')
        self.assertEquals(error.arg, 'arg_name')
        self.assertEquals(error.message, '')

    def test_config_error(self):
        config = Config()
        with self.assertRaises(AttributeError):
            config.parse()

    def test_config_get_section(self):
        config = self.setup_config([self.config_path])
        section = config.add_section('section2')
        self.assertEquals(section, config.get_section('section2'))
        self.assertEquals(section.__repr__(),
            '<ConfigSection(name=section2, required=True, arguments=[])>')
        section.add_argument('arg_name', 'arg_help', float)

        if sys.version_info >= (3, 0):
            self.assertEquals(section.arguments[0].__repr__(),
                '<ConfigArgument(name=arg_name, help=arg_help, type=<class \'float\'>, choices=None)>')
        else:
            self.assertEquals(section.arguments[0].__repr__(),
                '<ConfigArgument(name=arg_name, help=arg_help, type=<type \'float\'>, choices=None)>')

        with self.assertRaises(SectionError):
            config.get_section('section3')
        with self.assertRaises(MissingSection):
            args = config.parse()

    def test_config(self):
        sys.argv = [sys.argv[0]]
        config = self.setup_config([self.config_path])
        args = config.parse()
        self.assertEqual(args, config.arguments)
        self.assertEqual(args.section0.arg0a, 1234.123)
        self.assertEqual(args.section0.arg0b, True)
        self.assertEqual(args.section0.arg0c, False)
        self.assertEqual(args.section1.arg1a, 'configstring1a')
        self.assertEqual(args.section1.arg1b, 'configstring1b')
        self.assertEqual(args.section1.arg1c, 1000)
        self.assertEqual(args.command, None)

    def test_config_with_argv(self):
        sys.argv = [sys.argv[0]]
        sys.argv.extend(['--arg0b', 'false', '--arg1b', 'argstring1b',
            '--arg1c', '2000'])
        config = self.setup_config(self.config_path)
        args = config.parse()
        self.assertEqual(args, config.arguments)
        self.assertEqual(args.section0.arg0a, 1234.123)
        self.assertEqual(args.section0.arg0b, False)
        self.assertEqual(args.section0.arg0c, False)
        self.assertEqual(args.section1.arg1a, 'configstring1a')
        self.assertEqual(args.section1.arg1b, 'argstring1b')
        self.assertEqual(args.section1.arg1c, 2000)
        self.assertEqual(args.command, None)

    def test_config_with_commands(self):
        sys.argv = [sys.argv[0]]
        sys.argv.extend((['command1', '--arg0a', '1.1',
            '--arg1a', 'argstring1a']))
        config = self.setup_config(self.config_path)
        config.add_command('command0', 'command0 help')
        config.add_command('command1', 'command1 help')
        config.add_command('command2', 'command2 help')
        args = config.parse()
        self.assertEqual(args, config.arguments)
        self.assertEqual(args.section0.arg0a, 1.1)
        self.assertEqual(args.section0.arg0b, True)
        self.assertEqual(args.section0.arg0c, False)
        self.assertEqual(args.section1.arg1a, 'argstring1a')
        self.assertEqual(args.section1.arg1b, 'configstring1b')
        self.assertEqual(args.section1.arg1c, 1000)
        self.assertTrue(args.command, 'command1')

    def test_config_with_multiple_commands(self):
        sys.argv = [sys.argv[0]]
        sys.argv.extend((['command1', 'command0', '--arg0a', '1.1',
            '--arg1a', 'argstring1a']))
        config = self.setup_config(self.config_path)
        config.add_command('command0', 'command0 help')
        config.add_command('command1', 'command1 help')
        expected_output = 'usage: {cmd} [-h]  ...\n' \
            '{cmd}: error: unrecognized arguments: command0'.format(cmd=sys.argv[0])
        with self.assertRaises(SystemExit) as cm:
            with capture(config.parse) as out, err:
                self.assertEqual(expected_output, err)
        self.assertEqual(cm.exception.code, 2)

    def test_config_with_unknown_command(self):
        sys.argv = [sys.argv[0]]
        sys.argv.extend((['command2', '--arg0a', '1.1',
            '--arg1a', 'argstring1a']))
        config = self.setup_config(self.config_path)
        config.add_command('command0', 'command0 help')
        config.add_command('command1', 'command1 help')
        expected_output = 'usage: {cmd} [-h]  ...\n' \
            '{cmd}: error: argument : invalid choice: \'command2\'' \
            '(choose from \'command0\', \'command1\')'.format(cmd=sys.argv[0])
        with self.assertRaises(SystemExit) as cm:
            with capture(config.parse) as out, err:
                self.assertEqual(expected_output, err)
        self.assertEqual(cm.exception.code, 2)

    def test_config_with_config_arg(self):
        sys.argv = [sys.argv[0]]
        sys.argv.extend(['--config', self.config_path])
        config = self.setup_config(self.config_path)
        section = config.get_section('section0')
        section.add_argument('arg0d', 'a boolean', bool)
        with self.assertRaises(ConfigError) as cm:
            config.parse()

    @mock.patch('configutil.configutil.getenv')
    def test_config_with_envs(self, mock_env):
        sys.argv = [sys.argv[0]]
        envs = {'arg0b': 'True', 'arg0c': 'False',
            'arg1a': 'argstring1a', 'arg1b': 'argstring1b'}
        mock_env.side_effect = lambda k: envs.get(k, None)

        config = self.setup_config(self.missing_path)
        args = config.parse()

        self.assertEqual(mock_env.call_count, 4)
        self.assertEqual(args, config.arguments)
        self.assertEqual(args.section0.arg0a, 1234.123)
        self.assertEqual(args.section0.arg0b, True)
        self.assertEqual(args.section0.arg0c, False)
        self.assertEqual(args.section1.arg1a, 'argstring1a')
        self.assertEqual(args.section1.arg1b, 'argstring1b')
        self.assertEqual(args.section1.arg1c, 1000)
        self.assertEqual(args.command, None)

    @mock.patch('configutil.configutil.getenv')
    def test_config_with_command_envs(self, mock_env):
        sys.argv = [sys.argv[0]]
        sys.argv.extend((['command0', '--arg0a', '1.1',
            '--arg1a', 'argstring1a']))
        envs = {'arg0b': 'True', 'arg0c': 'False',
            'arg1a': 'envstring1a', 'arg1b': 'envstring1b'}
        mock_env.side_effect = lambda k: envs.get(k, None)

        config = self.setup_config(self.missing_path)
        config.add_command('command0', 'command0 help')
        config.add_command('command1', 'command1 help')
        config.add_command('command2', 'command2 help')

        args = config.parse()

        self.assertEqual(mock_env.call_count, 3)
        self.assertEqual(args, config.arguments)
        self.assertEqual(args.section0.arg0a, 1.1)
        self.assertEqual(args.section0.arg0b, True)
        self.assertEqual(args.section0.arg0c, False)
        self.assertEqual(args.section1.arg1a, 'argstring1a')
        self.assertEqual(args.section1.arg1b, 'envstring1b')
        self.assertEqual(args.section1.arg1c, 1000)
        self.assertEqual(args.command, 'command0')
        self.assertIsNotNone(config.__repr__())

    @mock.patch('configutil.configutil.getenv')
    def test_config_with_command_envs_error(self, mock_env):
        sys.argv = [sys.argv[0]]
        sys.argv.extend((['command0', '--arg0a', '1.1',
            '--arg1a', 'argstring1a']))
        envs = {'arg0b': 'True', 'arg0c': 'False',
            'arg1a': 'envstring1a'}
        mock_env.side_effect = lambda k: envs.get(k, None)

        config = self.setup_config(self.missing_path)
        config.add_command('command0', 'command0 help')
        config.add_command('command1', 'command1 help')
        config.add_command('command2', 'command2 help')

        with self.assertRaises(ConfigError):
            args = config.parse()

    def test_config_help(self):
        sys.argv = [sys.argv[0]]
        sys.argv.extend((['--help']))

        config = self.setup_config(self.config_path)
        config.add_command('command0', 'command0 help')
        config.add_command('command1', 'command1 help')
        config.add_command('command2', 'command2 help')

        expected_output = 'usage: {cmd} [-h]  ...\n' \
        '\n' \
        'optional arguments:\n' \
        '  -h, --help  show this help message and exit\n' \
        '\n' \
        'available commands:\n' \
        '              command help\n' \
        'command0  command0 help\n' \
        'command1  command1 help\n' \
        'command2  command2 help\n'.format(cmd=sys.argv[0])

        with self.assertRaises(SystemExit) as cm:
            with capture(config.parse) as out, err:
                self.assertEqual(expected_output, err)
        self.assertEqual(cm.exception.code, 0)

    def test_command_help(self):
        sys.argv = [sys.argv[0]]
        sys.argv.extend((['command1', '--help']))

        config = self.setup_config(self.config_path)
        config.add_command('command0', 'command0 help')
        config.add_command('command1', 'command1 help')
        config.add_command('command2', 'command2 help')

        expected_output = 'usage: {cmd} command1 [-h] [--config CONFIG] [--arg1a ARG1A]\n' \
        '                            [--arg1b ARG1B] [--arg1c ARG1C] [--arg0a ARG0A]\n' \
        '                            [--arg0b ARG0B] [--arg0c ARG0C]\n' \
        '\n' \
        'optional arguments:\n' \
        '  -h, --help       show this help message and exit\n' \
        '  --config CONFIG  configuration file path\n' \
        '  --arg1a ARG1A    a string\n' \
        '  --arg1b ARG1B    a string\n' \
        '  --arg1c ARG1C    an int\n' \
        '  --arg0a ARG0A    a float\n' \
        '  --arg0b ARG0B    a boolean\n' \
        '  --arg0c ARG0C    a boolean\n'.format(cmd=sys.argv[0])

        with self.assertRaises(SystemExit) as cm:
            with capture(config.parse) as out, err:
                self.assertEqual(expected_output, err)
        self.assertEqual(cm.exception.code, 0)

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


"""ninegag URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url, include
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from users.views import UserRegistrationAPIView, UserLoginAPIView, GetToken, Logout
from rest_framework.authtoken.views import obtain_auth_token  # <-- Here

# Simple JWT TOKEN
# from rest_framework_simplejwt.views import (
#     TokenObtainPairView,
#     TokenRefreshView,
# )

# Django Rest Swagger cua drf-yasg
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="Django API",
        default_version='v1',
        description="Test description",
        terms_of_service="https://www.google.com/policies/terms/",
        contact=openapi.Contact(email="contact@snippets.local"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    path('admin/', admin.site.urls),
    # path('register/', UserRegistrationAPIView.as_view(), name="register"),
    # path('register/', UserRegistrationAPIView.as_view(), name="register"),
    # path('login/', UserLoginAPIView.as_view(), name="login"),
    # path('logout/', Logout.as_view(), name='logout'),
    path('get-token/', GetToken.as_view()),
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
    path('user/', include('users.urls')),
    path('post/', include('post.urls')),
    path('categorys/', include('categorys.urls')),
    # url Simple JWT TOKEN
    # url(r'^api/token/$', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    # url(r'^api/token/refresh/$', TokenRefreshView.as_view(), name='token_refresh'),

    # Django Rest Swagger cua drf-yasg
    url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),

]

# Theo cách này, Django sẽ chịu trách nhiệm phục vụ các tệp phương tiện trong quá trình phát triển (DEBUG = True).
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


from tkinter import *
from PIL import ImageTk,Image
import game
import pygame

def start(root,my_canvas):

    #To create buttons and its functionality
    button1 = Button(root,image = play_button,borderwidth=0,highlightthickness=0,command = lambda : change(root))
    button2 = Button(root,image = exit_button,borderwidth=0,highlightthickness=0,command = lambda : change_exit(root))
    button3 = Button(root,image = help_button,borderwidth=0,highlightthickness=0,command = lambda : instruct( ))
    button4 = Button(root,image = mute_button,borderwidth=0,highlightthickness=0,command = lambda : mute(root))

    #To fix the place of the buttons on the tkinter window
    button1_window = my_canvas.create_window(0,30,anchor="nw",window=button1)
    button2_window = my_canvas.create_window(0,500,anchor="nw",window=button2)
    button3_window = my_canvas.create_window(1190,20,anchor="nw",window=button3)
    button4_window = my_canvas.create_window(1195,500,anchor="nw",window=button4)

def change_exit(root):
    exit(0)
    #root.destroy()

def change(root):
    root.destroy()

def instruct():
    root1 = Toplevel()
    root1.title("Instructions")
    root1.geometry('1004x565')

    bg = ImageTk.PhotoImage(file="instructions.png")

    my_canvas = Canvas(root1,width=1004,height=565,highlightthickness=0)
    my_canvas.pack(fill="both",expand=True)
    my_canvas.create_image(0,0,image=bg,anchor="nw")

    root1.mainloop()

is_muted = False

def mute(root):
    global is_muted
    is_muted = not is_muted
    toggle_sound(is_muted)

def toggle_sound(mute):
    pygame.mixer.init()
    if pygame.mixer.music.get_volume() > 0 and mute:
        pygame.mixer.music.set_volume(0)
    else:
        pygame.mixer.music.set_volume(1)

def call():
    global my_canvas,play_button,exit_button,help_button,mute_button
    root = Tk()
    #root.bind('<Configure>',resizer)
    #To get a tkinter window as my fullscreen
    root.attributes("-fullscreen",True)
    root.title('Game')
    #root.geometry('900x1000')

    #to add background to my tkinter window
    bg = ImageTk.PhotoImage(file="idex2.png")

    my_canvas = Canvas(root,width=540,height=684,highlightthickness=0)
    my_canvas.pack(fill="both",expand=True)
    my_canvas.create_image(0,0,image=bg,anchor="nw")

    play_button = PhotoImage(file ='play.png')
    exit_button = PhotoImage(file = 'exit.png')
    help_button = PhotoImage(file = 'help.png')
    mute_button = PhotoImage(file = 'mute.png')

    img_label = Label(image = play_button)
    img_label1 = Label(image = exit_button)
    img_label2 = Label(image = help_button)
    img_label3 = Label(image = mute_button)
    #img_label.pack(pady=20)

    start(root,my_canvas)

    root.mainloop()

while(True):
    call()
    game.main()


# -*- coding: utf-8 -*-
import numpy as np
import torch

bikes_numpy = np.loadtxt("../data/bike_sharing_data/hour-fixed.csv",
                         dtype=np.float32,
                         delimiter=",",
                         skiprows=1,
                         converters={1: lambda x: float(x[8:10])})

bikes = torch.from_numpy(bikes_numpy)
print("bikes:{}\nshape:{}\nbikes.stride:{}".format(bikes, bikes.shape, bikes.stride()))

# shape:torch.Size([17520, 17])
# bikes.stride:(17, 1)

# 将数据重新排列为三个轴（日期,小时,然后是17列）
daily_bikes = bikes.view(-1, 24, bikes.shape[1])
print("daily_bikes.shape: {}, daily_bikes.stride: {}".format(daily_bikes.shape, daily_bikes.stride()))
# daily_bikes.shape: torch.Size([730, 24, 17]), daily_bikes.stride: (408, 17, 1)

# 最右边的维度是原始数据集中的列数。在中间维度中，你将时间分为24个连续小时的块。
# 换句话说，你现在每天有C个通道的N个L小时的序列。为了获得你所需的 N x C x L 顺序，你需要转置张量：

daily_bikes = daily_bikes.transpose(1, 2)
print("daily_bikes.shape:{}, daily_bikes.stride:{}".format(daily_bikes.shape, daily_bikes.stride()))
# daily_bikes.shape:torch.Size([730, 17, 24]), daily_bikes.stride:(408, 1, 17)

first_day = bikes[:24].long()
print("first_day.shape:{}".format(first_day.shape))
# first_day.shape:torch.Size([24, 17])
weather_onehot = torch.zeros(first_day.shape[0], 4)

# 取第一天天气状况那一列的所有数据
print("取第一天天气状况那一列的所有数据: {}\nunsqueeze:{}".format(first_day[:, 9], first_day[:, 9].unsqueeze(1)))

# unsqueeze:tensor([[1],
#         [1],
#         [1],
#         [1],
#         [1],
#         [2],
#         [1],
#         [1],
#         [1],
#         [1],
#         [1],
#         [1],
#         [1],
#         [2],
#         [2],
#         [2],
#         [2],
#         [2],
#         [3],
#         [3],
#         [2],
#         [2],
#         [2],
#         [2]])

weather_onehot.scatter_(
    dim=1,
    # one-hot是从1开始编码, 因此这里减去1 ？？
    index=first_day[:, 9].unsqueeze(1) - 1,
    value=1.0
)

print("weather_onehot:{}".format(weather_onehot))

# 使用cat函数将矩阵连接到原始数据集。看第一个结果：
first_day_cat = torch.cat((bikes[:24], weather_onehot), dim=1)[:1]
print("first_day_cat:{}".format(first_day_cat))
# first_day_cat:tensor([[ 1.0000,  1.0000,  1.0000,  0.0000,  1.0000,  0.0000,  0.0000,  6.0000,
#           0.0000,  1.0000,  0.2400,  0.2879,  0.8100,  0.0000,  3.0000, 13.0000,
#          16.0000,  1.0000,  0.0000,  0.0000,  0.0000]])

# 你也可以使用重新排列的daily_bikes张量完成相同的操作。请记住，它的形状为（B,C,L），其中L=24

daily_weather_onehot = torch.zeros(daily_bikes.shape[0], 4, daily_bikes.shape[2])
print("daily_weather_onehot.shape:{}".format(daily_weather_onehot.shape))
# daily_weather_onehot.shape:torch.Size([730, 4, 24])
daily_weather_onehot.scatter_(dim=1, index=daily_bikes[:, 9, :].long().unsqueeze(1) - 1, value=1.0)
print("daily_weather_onehot shape:{}".format(daily_weather_onehot.shape))
# daily_weather_onehot shape:torch.Size([730, 4, 24])

# 沿C维度连接
daily_bikes = torch.cat((daily_bikes, daily_weather_onehot), dim=1)
print("daily_bikes: {}\nshape:{}".format(daily_bikes, daily_bikes.shape))
# shape:torch.Size([730, 21, 24])

# 将第10列中的温度调整到[0.0, 1.0]之间
# 方法1：
temp = daily_bikes[:, 10,:]
temp_min = torch.min(temp)
temp_max = torch.max(temp)
daily_bikes[:,10,:] = (daily_bikes[:,10,:] - temp_min)/ (temp_max - temp_min)

# 方法2： 减去平均值并除以标准差
temp = daily_bikes[:, 10,:]
daily_bikes[:, 10,:] = (daily_bikes[:, 10,:] - torch.mean(temp))/ torch.std(temp)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import imagekit.models.fields
import brasilcomvc.portal.models

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='HomeBanner',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
                ('image', imagekit.models.fields.ProcessedImageField(help_text='Imagem de alta resolução; será cortada para 1400x550.', upload_to=brasilcomvc.portal.models.homebanner_video_upload_to)),
                ('content', models.TextField(help_text='Conteúdo (HTML) para sobrepor a imagem no banner.')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


from sqlalchemy.orm import sessionmaker

from setting_db import engine
import models, valid

models.Base.metadata.create_all(bind=engine)

# This method opens a connection with the database then there is a search by user id then it returns the full user
# data namely phone email and login
def get_id(id: int):
    db = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    session = db()
    user = session.query(models.User).filter(models.User.id == id).first()
    return user

# adding a new user after receiving data recording and saving to the database
def add_user(user: valid.User):
    db = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    session = db()
    db_user = models.User(login=user.login, email=user.email, phone=user.phone)
    session.add(db_user)
    session.commit()
    session.refresh(db_user)
    return db_user


import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

path = 'df_train.csv'
data = pd.read_csv(path)

filter_fever = data.loc[data['ONSET_FEVER'] == 1]
filter_cough = data.loc[data['ONSET_COUGH'] == 1]
filter_tired = data.loc[data['ONSET_TIRED'] == 1]
filter_sorethroat = data.loc[data['ONSET_SORETHROAT'] == 1]
filter_respiratory = data.loc[data['ONSET_RESPIRATORY'] == 1]

def get_los(filter_onset):
    los = filter_onset.iloc[:, 17:].values
    return np.reshape(los, len(los)).tolist()

los_fever = get_los(filter_fever)
los_cough = get_los(filter_cough)
los_tired = get_los(filter_tired)
los_sorethroat = get_los(filter_sorethroat)
los_respiratory = get_los(filter_respiratory)

combine_los = [los_fever, los_cough, los_tired, los_sorethroat, los_respiratory]

plt.boxplot(combine_los)
plt.xticks([1, 2, 3, 4, 5], ['FEVER', 'COUGH', 'TIRED', 'SORETHROAT', 'RESPIRATORY'], fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel('Length of stay', fontsize=20)
plt.title('Length of stay with respect to onset symptoms', fontsize=24)
plt.show()


from gettext import find
from importlib.resources import path
from math import atan2, cos, sin, sqrt, pi
from sys import maxsize
from itertools import permutations
from typing import Mapping
import gmplot
#---------------------------------------------------------------------------------------------------------------------------------------

#calculate distance from one store to another store (first store, second store)
def distance(first,second):

    r = 6371
    dlat = degToRad(second[1] - first[1])
    dlong = degToRad(second[0] - first[0])
    x = sin (dlat/2) * sin (dlat/2)
    y = cos (degToRad(first[1]) * cos(degToRad(second[1])))
    z = sin(dlong/2) * sin(dlong/2)
    a = x+y*z
    c = 2 * atan2(sqrt(a),sqrt(1-a))
    d = r*c
    return d

# convert degree to radian
def degToRad(deg):
    return deg * (pi/180)

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

v = 5
# center = 0
def computeShortestPath(listdistance,center):
    vertex = []
    for i in range(v):
        if i!=center:
            vertex.append(i)

    # print("vertex: ", vertex)
    mindistance = maxsize
    # print ("max size: ",maxsize)

    # listPermute = list(permutations(vertex))
    # print("total permutation",len(listPermute))
    # print()
    vertexPermute = permutations(vertex)

    # print("path: \t\t\t  total distance: ")
    for i in vertexPermute:
        currentdistance = 0
        k=center
        for j in i:
            currentdistance += listdistance[k][j]
            k = j
        currentdistance += listdistance[k][center] #add distance from last node to the initial node
        # print(i," \t ", currentdistance)

        if(currentdistance<=mindistance):
            mindistance = min(mindistance, currentdistance)
            path = i

    return {'mindistance':mindistance, 'path':path, 'center':center}

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

def plot(text):

    #read path.txt file
    # with open("path.txt") as textFile:
    #     line_array = textFile.read().splitlines()
    #     # line_array = textFile.read()
    #     location = [line.split(' ,') for line in line_array]
    # location = re.split(',|(|)', line_array)

    path = [[0,4,2,1,3],[3,0,1,2,4],[0,4,1,3,2],[3,4,0,1,2],[0,3,4,2,1]]
    # print(path)
    for i in text:
        country = text[i]
        coordinate = readFile(country)
        # print("original coordinate ",coordinate)
        # print(coordinate)

        location = [[0 for i in range(len(coordinate))] for j in range (len(coordinate))]
        #susun coordinate ikut path[]
        k=0
        for j in path[i]:
            location[k] = coordinate[j] #to sort the stores location (long,lat) according to the sorted path
            k=k+1
        # print("sorted location ",location)

        #transfer long and lat from 2d array to 1d array
        lat=[]
        long=[]
        for m in range(len(location)):
            long.append(location[m][1])
            lat.append(location[m][0])

        # print("latitude ", lat)
        # print("longitude ",long,"\n")

        mapping = gmplot.GoogleMapPlotter(lat[0],long[0],zoom=10,apikey="")
        mapping.plot(lat,long,'red',edge_width = 2.5) # to connect the location from 1 store to another store\

        # to connect the last store to deliver to the starting store
        lastPath = zip(*[
            (lat[len(lat)-1],long[len(long)-1]),
            (lat[0],long[0])
        ])
        mapping.plot(*lastPath,'red',edge_width = 2.5)

        # to mark the stores according to their original number
        j=0
        for m in range(len(coordinate)):
            if (m==path[i][0]):
                mapping.marker(lat[m],long[m], label=path[i][0], color="green")
            else:
                mapping.marker(lat[m],long[m], label=path[i][j], color="green")
                j=j+1

        mapping.draw("Problem 2\\map %d.html" %(i))

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

#read location(lat,long) from text file
def readFile(file):
    with open(file) as textFile:
        line_array = textFile.read().splitlines()
        location = [line.split(",") for line in line_array]

    floatLocation = [[0 for i in range (len(location[0]))] for j in range (len(location))]
    for i in range(len(location)):
        for j in range (len(location[0])):
            floatLocation[i][j] = float(location[i][j])

    return floatLocation

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

#find center of the stores
def findCenter(listdistance):

    temp = maxsize
    # print("temp", temp)
    for i in range(len(stores)):
        average=0
        for j in range(len(stores)):
            average = average + listdistance[i][j]
        average = average/5
        if average<temp:
            # print("average",average)
            temp = average
            center = i
            # print("average ",average, " center ", i)

    return center

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

#to sort rank
def sortDeliveryRank(allShortest,countries):
    pairlist = dict(zip(countries, allShortest))
    sortedDeliveryRank = sorted(pairlist.items(), key=lambda x: x[1])

    return sortedDeliveryRank

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

#driver code
if __name__ == "__main__":

    text = {
        0 : "Problem 2\\canada stores.txt",
        1 : "Problem 2\\uae stores.txt",
        2 : "Problem 2\\china stores.txt",
        3 : "Problem 2\\singapore stores.txt",
        4 : "Problem 2\\philippines stores.txt"
    }

    allShortest = []
    countries = ['Canada','UAE','China','Singapore','Phillipines']

    j=0
    for i in text:
        country = text[i]
        stores = readFile(country)
        # print("text: ", stores)
        # print stores
        print("\n*****************",countries[i],"*****************\n")
        print("Store\tLatitude\tLongitude")
        for i in range(len(stores)):
            print(i,"\t",stores[i][0],"\t",stores[i][1])
        print()

        #calculate distance from one store to another store
        listdistance = [[0 for i in range(len(stores))] for j in range (len(stores))] #matrix representation graph
        # center = stores[0]
        for i in range (len(stores)):
            for j in range (len(stores)):
                listdistance[i][j] = float(distance(stores[i],stores[j]))

        #print all dinstance
        print("Matrix representation distance (km): \n")
        print("Eg:")
        print("[ 03 ] means distance from Store 0 to Store 3\n")
        for i in range(len(stores)):
            for j in range(len(stores)):
                print("[ ",i,j," ]", end=" ")
            print()

        print()
        for i in range (len(stores)):
            print(listdistance[i])
        print("\n")

        #find center of the stores
        # center = 0
        center = findCenter(listdistance)

        print("---------- Computing Shortest Path For Delivery ----------")
        ret = computeShortestPath(listdistance, center)
        print("\nCenter (starting and ending): ",ret['center'])
        print("Shortest Path: ", ret['path'])
        print("Total Distance: %.4f" % (ret['mindistance']),"km\n")
        # plot(ret['path'], stores,ret['center'])
        allShortest.insert(i,ret['mindistance'])
        f = open("path.txt","a")
        # write = ret['center'],ret['path'],"\n"
        f.write(str(ret['center']))
        # for i in range(len(ret['path'])):
        f.write(str(ret['path']))
        f.write("\n")
        f.close()
        plot(text)

    rank = sortDeliveryRank(allShortest,countries)
    print("-----------------------------------------------------------------------")
    print("\n\nRank of countries based on the shortest delivery")
    print("No\tCountry\t\tTotal Delivery")
    for i in range(len(rank)):
        # for i in range(len(rank[0])):
        print(i," \t",rank[i][0],"\t","%.4f" %(rank[i][1]))
    print("\n")


from web3 import Web3, HTTPProvider
import rlp
import json
import math
from ethereum.transactions import Transaction

class Land:
    def run(self):
        # desc
        # -112 <= x <= -68
        # -22 <= y <= 22
        # --
        Land_ADDRESS = "0x1a587212c0e35922ee79e4ff876c5e4e600fc877"
        ETH_RPC = "https://kovan.infura.io/ZWef2NOidUm5XooBYqgl"
        USER_ADDRESS = "0xda7fab79bfd0a27f04367f5b9b9348cb5d1b0023"
        PANGU_ADDRESS = "0xda7fab79bfd0a27f04367f5b9b9348cb5d1b0023"

        CREATE_PRI_KEY = ""

        w3 = Web3(HTTPProvider(ETH_RPC, request_kwargs={'timeout': 120}))
        with open('resource.json', 'r') as resource_definition:
            resource_json = json.load(resource_definition)
        nonce = w3.eth.getTransactionCount(USER_ADDRESS),
        nonce = nonce[0]

        for index, resource in enumerate(resource_json):
            x = -112 + index % 45
            y = 22 - int(index / 45)
            execute_transaction = "0x6bd50a14" + self.u256ToInput(x) + self.u256ToInput(y) + self.pandding(PANGU_ADDRESS)
            tx = Transaction(
                nonce=nonce + index,
                gasprice=2000000000,
                startgas=1000000,
                to=Land_ADDRESS,
                value=0,
                data=w3.toBytes(hexstr=execute_transaction),
            )
            tx.sign(CREATE_PRI_KEY)
            raw_tx = rlp.encode(tx)
            raw_tx_hex = w3.toHex(raw_tx)
            tx = w3.eth.sendRawTransaction(raw_tx_hex)
            print(tx)
            break

    def pandding(self, format):
        if format.startswith('0x'):
            format = format[2:]
        return format.rjust(64, '0')

    def panddingF(self, format):
        if format.startswith('0x'):
            format = format[2:]
        return format.rjust(64, 'f')

    def u256ToInput(self, u):
        if u >= 0:
            hex = "{:x}".format(u)
            return self.pandding(hex)
        else:
            if abs(u) == 1:
                hex = "{:x}".format(16 - abs(u))
            else:
                hex = "{:x}".format(int(pow(16, math.ceil(math.log(abs(u), 16))) + u))
            return self.panddingF(hex)

if __name__ == '__main__':
    ld = Land()
    ld.run()


from flask import Flask, render_template, request, g
from DatabaseUtility import query_db, insert_submission
import sqlite3 as sql
app = Flask(__name__)

DATABASE = 'BallmersPeak.db'

@app.route('/enterscore')
def enter_score():
  return render_template('enter_scores.html')

@app.route('/score_entered', methods=['POST'])
def score_entered():
  msg = ''
  if request.method == 'POST':
    try:
      gameID = request.form['gameid']
      score = request.form['score']
      qid = request.form['qid']
      teamid = request.form['teamid']
      code = request.form['code']

      if code == 'miketim3':
        insert_submission(teamid, score, qid, gameID, 'BallmersPeak.db')
        msg = 'Score entered!'
      else:
        msg = 'Access code invalid'

    except:
      msg = "Failed to retrieve leaderboard"

    finally:
      return render_template("result.html",msg = msg)

@app.route('/registerteam')
def new_team():
   return render_template('register.html')

@app.route('/viewleaderboard')
def view_leaderboard():
  return render_template('view_leaderboard.html')

@app.route('/leaderboard', methods = ['POST'])
def leaderboard():
  msg = ''
  if request.method == 'POST':
    try:
      gameID = request.form['id']
      with sql.connect("BallmersPeak.db") as con:
          cur = con.cursor()
          result = cur.execute("SELECT TeamName, Score FROM (SELECT TeamID, SUM(Score) as Score FROM (SELECT TeamID, questionID, MAX(Score) as Score FROM Submissions GROUP BY teamID, questionID HAVING GameID = (?))) INNER JOIN Teams USING (teamID) ORDER BY Score DESC;", (gameID))
          msg = '
  Team Name | Score
'

          for pair in result:
            msg += pair[0] + ' | ' + str(pair[1]) + '
'

    except:
      con.rollback()
      msg = "Failed to retrieve leaderboard"

    finally:
      con.close()
      return render_template("result.html",msg = msg)

@app.route('/viewsubmissions')
def viewsubmisions():
  return render_template("view_submissions.html")

@app.route('/submissions', methods = ['POST'])
def submissions():
  msg = ''
  if request.method == 'POST':
    try:
      team_id = request.form['id']
      with sql.connect("BallmersPeak.db") as con:
          cur = con.cursor()
          result = cur.execute("SELECT SubmissionID, QuestionTitle, Score, Points FROM (SELECT * FROM Submissions INNER JOIN Questions USING (QuestionID) WHERE TeamID = (?)) ORDER BY QuestionTitle, SubmissionID DESC;", (team_id))
          msg = '
  SubmissionID | Question Title | Your Score | Max Points
'

          for pair in result:
            msg += str(pair[0]) + ' | ' + str(pair[1]) + ' | ' + str(pair[2]) + ' | ' + str(pair[3]) + '
'

    except:
      con.rollback()
      msg = "Failed to retrieve submissions"

    finally:
      con.close()
      return render_template("result.html",msg = msg)

@app.route('/teamregistered', methods = ['POST'])
def teamregistered():
  msg = ''
  if request.method == 'POST':
      try:
        team_name = request.form['name']
        gameID = int(request.form['id'])
        new_game_id = gameID

        ## Need to create a new gameID
        if gameID == -1:
          game_id_query_result = query_db('SELECT MAX(GameID) from Game;', 'BallmersPeak.db')
          if (len(game_id_query_result) == 0 or game_id_query_result[0][0] is None):
            new_game_id = 0
          else:
            new_game_id = game_id_query_result[0][0] + 1

          with sql.connect("BallmersPeak.db") as con:
            cur = con.cursor()
            result = cur.execute("INSERT INTO Game (GameID) VALUES (NULL)")
            con.commit()

        team_id_query_result = query_db('SELECT MAX(TeamID) from Teams;', 'BallmersPeak.db')
        new_team_id = -1
        if (len(team_id_query_result) == 0 or team_id_query_result[0][0] is None):
          new_team_id = 0
        else:
          new_team_id = team_id_query_result[0][0] + 1

        with sql.connect("BallmersPeak.db") as con:
          cur = con.cursor()
          result = cur.execute("INSERT INTO Teams (TeamID, TeamName, GameID) VALUES (?, ?, ?)", (new_team_id, team_name, new_game_id))
          con.commit()

        msg = 'Thank you, ' + str(team_name) + ', your game id is: ' + str(new_game_id) + ', and your team id is: ' + str(new_team_id) + '.'
      except:
        con.rollback()
        msg = "Failed to add team"

      finally:
        con.close()
        return render_template("result.html",msg = msg)

@app.route('/questions')
def questions():
   return render_template('questions.html')

@app.route("/")
def main():
    cur = get_db().cursor()
    return render_template("home.html")

@app.route("/ctf1")
def ctf1():
    cur = get_db().cursor()
    return render_template("ctf1.html")

@app.route("/ctf2")
def ctf2():
    cur = get_db().cursor()
    return render_template("ctf2.html")

@app.route("/ctf3")
def ctf3():
    cur = get_db().cursor()
    return render_template("ctf3.html")

@app.route("/ctf4")
def ctf4():
    cur = get_db().cursor()
    return render_template("ctf4.html")

@app.route("/ctf5")
def ctf5():
    cur = get_db().cursor()
    return render_template("ctf5.html")

@app.route("/ctf6")
def ctf6():
    cur = get_db().cursor()
    return render_template("ctf6.html")

@app.route("/ctf7")
def ctf7():
    cur = get_db().cursor()
    return render_template("ctf7.html")

@app.route("/algo1")
def algo1():
  return render_template("StockPrices.html")

@app.route("/algo2")
def algo2():
  return render_template("Skiing.html")

@app.route("/algo3")
def algo3():
  return render_template("KidsLiningUp.html")

@app.route("/algo4")
def algo4():
  return render_template("RoundingFloats.html")

@app.route("/algo5")
def algo5():
  return render_template("6dMahjong.html")

@app.route("/algo6")
def algo6():
  return render_template("AssigningToBrainCells.html")

@app.route("/algo7")
def algo7():
  return render_template("LogOrders.html")

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sql.connect(DATABASE)
    return db

@app.route('/addrec',methods = ['POST', 'GET'])
def addrec():
   if request.method == 'POST':
      try:
         nm = request.form['nm']
         pin = request.form['pin']

         with sql.connect("Teams.db") as con:
            cur = con.cursor()

            cur.execute("INSERT INTO REGISTERED (NAME,PASSWORD) VALUES (?,?)",(nm,pin) )

            con.commit()
            msg = "Record successfully added"
      except:
         con.rollback()
         msg = "error in insert operation"

      finally:
         return render_template("result.html",msg = msg)
         con.close()

@app.route('/registermember')
def new_mem():
   return render_template('new_member.html')

@app.route('/addmem',methods = ['POST', 'GET'])
def addmem():
   if request.method == 'POST':
      try:
         player_name = request.form['name']
         team = request.form['team']
         pin = request.form['pin']

         with sql.connect("Teams.db") as con:
            cur = con.cursor()

            result = cur.execute("SELECT * FROM REGISTERED WHERE NAME = (?) AND PASSWORD = (?)", (team, pin))
            num = 0

            for res in result:
                num += 1

            if num > 0 and num < 3:
              cur.execute("INSERT INTO TEAM_MEMBERS (NAME,TEAM_NAME) VALUES (?,?)",(player_name,team))
              con.commit()
              msg = "Record successfully added"
            elif num == 0:
              msg = "Invalid team credentials"
            else:
              msg = "Team size is out of bounds"
      except:
         con.rollback()
         msg = "Failed to add team"

      finally:
         return render_template("result.html",msg = msg)
         con.close()

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


import asyncio
import re
import sys
from io import BytesIO

from redbot.core import checks, commands
from tsutils.user_interaction import send_confirmation_message, send_cancellation_message

class DevUtils(commands.Cog):
    """Owner Utilities"""

    def __init__(self, bot, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.bot = bot

    async def red_get_data_for_user(self, *, user_id):
        """Get a user's personal data."""
        data = "No data is stored for user with ID {}.\n".format(user_id)
        return {"user_data.txt": BytesIO(data.encode())}

    async def red_delete_data_for_user(self, *, requester, user_id):
        """Delete a user's personal data.

        No personal data is stored in this cog.
        """
        return

    @commands.command(aliases=['freload', 'creload'])
    @checks.is_owner()
    async def rlthen(self, ctx, command, *, arguments=""):
        """Run a command after reloading its base cog."""
        full_cmd = "{}{} {}".format(ctx.prefix, command, arguments)
        command = self.bot.get_command(command)
        if command is None:
            await ctx.send("Invalid Command: {}".format(full_cmd))
            return
        _send = ctx.send

        async def fakesend(text, *args, **kwargs):
            if "Reloaded " in text:
                return
            await _send(text, *args, **kwargs)

        ctx.send = fakesend
        await self.bot.get_cog("Core").reload(ctx, command.cog.__module__.split('.')[0])

        ctx.send = _send
        ctx.message.content = full_cmd
        await self.bot.process_commands(ctx.message)

    @commands.command(aliases=['delaysend'])
    async def delaycommand(self, ctx, time, *, command):
        """Run a command after waiting a period of time.

        [p]delaycommand 30s which sonia
        [p]delaycommand 5m forceindexreload
        """
        if not re.match(r'\d+[ms]?', time):
            await ctx.send("Invalid time: {}".format(time))
            return

        if time.endswith('s'):
            time = int(time[:-1])
        elif time.endswith('m'):
            time = int(time[:-1]) * 60
        else:
            time = int(time)

        if time > 60 * 15:
            await ctx.send("Time must be less than 15 minutes.")
            return

        if command.startswith(ctx.prefix):
            command = command[len(ctx.prefix):]

        cname_parts = []
        for part in command.split():
            if self.bot.get_command(" ".join(cname_parts) + " " + part) is None:
                break
            cname_parts.append(part)

        resolved_command = " ".join(cname_parts)

        cmd = self.bot.get_command(resolved_command)
        if cmd is None:
            resolved_command_message = f'`{resolved_command}`' if resolved_command else "the empty string"
            await send_cancellation_message(ctx,
                                            f"`{command}` (resolved to {resolved_command_message}) is not a valid command.\n"
                                            f"Aliases aren't valid with this command. Bot prefix is optional. "
                                            f"Time must be given in seconds or minutes as a one-letter abbreviation, e.g. `5m`.")
            return
        if not await cmd.can_run(ctx):
            await send_cancellation_message(ctx, f"You do not have permission to run the command `{resolved_command}`")

        await ctx.tick()
        await asyncio.sleep(time)

        ctx.message.content = ctx.prefix + command
        await self.bot.process_commands(ctx.message)

    @commands.command(aliases=["pipupgrade"])
    @checks.is_owner()
    async def pipupdate(self, ctx, module, updatepip: bool = True):
        async with ctx.typing():
            process = await asyncio.create_subprocess_exec(
                sys.executable, "-m", "pip", "install", "-U", module,

                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )

            stdout, stderr = (bts.decode() if bts else "" for bts in await process.communicate())

        if stderr.startswith("WARNING: You are using pip version"):
            if updatepip:
                await ctx.send(stderr.split('You should consider')[0] + '\n\nUpdating pip...')
                await self.pipupdate(ctx, 'pip', False)
            stderr = ""

        if stderr:
            await send_cancellation_message(ctx, "Error updating:\n" + stderr)
        else:
            lines = stdout.split('\n')
            last_line = lines[-1]
            if 'Successfully installed' in last_line:
                return await send_confirmation_message(ctx, last_line)
            else:
                return await send_cancellation_message(ctx, lines[0])

    @commands.command()
    async def relast(self, ctx):
        async for message in ctx.channel.history(limit=200):
            b = False
            if message.author == ctx.author and "relast" not in message.content:
                for prefix in await self.bot.get_valid_prefixes():
                    if message.content.startswith(prefix) \
                            and self.bot.get_command(message.content[len(prefix):]):
                        b = True
                        break
                if b:
                    break
        else:
            await ctx.send("Your most recent message could not be found.")
            return
        await self.bot.process_commands(message)


# -*- coding: utf-8 -*-
"""
Authors: Rejane Paulino, Felipe Nincao, Thainara Munhoz
National Institute for Space Research (INPE) - Instrumentation Laboratory for Aquatic Systems (LabISA)

Last update: 08 september 2022
"""

# Library:
import numpy as np
from osgeo import gdal
import numpy as np
import pandas as pd
import json
import os
from PIL import Image

#%%
# Excel file containing the central wavelenght, fwhm, name of each band for the specific image
# IMPORTANT -> The number of bands must be equal to the spectral response function
bands_prisma = pd.read_excel(
    'G:/Outros computadores/Meu modelo Laptop (1)/Documents/Mestrado/BEPE/atmospheric_correction/6S/prisma_bands_data.xlsx', header=0, index_col=0)
bands_prisma_acolite = bands_prisma.iloc[:, 1]

# TOA Reflectance -> each band must be saved in a unique folder
path_to_toa_reflectance = 'G:/Outros computadores/Meu modelo Laptop (1)/Documents/Mestrado/BEPE/atmospheric_correction/6S/PRISMA_04-09_rtoa/rhot_'

# Read the JSON file for the VNIR
with open('G:/Outros computadores/Meu modelo Laptop (1)/Documents/Mestrado/BEPE/atmospheric_correction/6S/PRISMA_04-09-21_resultados/6S_parameters_VNIR.json') as f:
    data = f.read()

dicionario_VNIR = json.loads(data)

# Read the JSON file for the SWIR
with open('G:/Outros computadores/Meu modelo Laptop (1)/Documents/Mestrado/BEPE/atmospheric_correction/6S/PRISMA_04-09-21_resultados/6S_parameters_SWIR.json') as f:
    data = f.read()

dicionario_SWIR = json.loads(data)

dicionario_completo = {**dicionario_VNIR, **dicionario_SWIR}

dic_aux = dicionario_completo

a = 0
for k in list(dic_aux.keys()):
    dicionario_completo[str(bands_prisma_acolite[a])] = dicionario_completo.pop(str(k))
    a = a + 1

#%%
# Apply the radiative transfer equation in each RTOA image considering the parameters from the 6S
for a in bands_prisma_acolite.values:

    string_band = path_to_toa_reflectance + str(a) + ".tiff"
    band_prisma = gdal.Open(string_band, gdal.GA_ReadOnly)
    array_prisma = band_prisma.GetRasterBand(1).ReadAsArray()

    # Atmospheric modeling:
    atmospheric_modeling_py6S_Band = dicionario_completo[str(a)]

    # Atmospheric Correction -> Equation Vermote et al. (2016):
    tg_OG_co = float(atmospheric_modeling_py6S_Band['co_transmittance_total'])
    tg_OG_c02 = float(
        atmospheric_modeling_py6S_Band['co2_transmittance_total'])
    tg_OG_o2 = float(
        atmospheric_modeling_py6S_Band['oxyg_transmittance_total'])
    tg_OG_no2 = float(
        atmospheric_modeling_py6S_Band['no2_transmittance_total'])
    tg_OG_ch4 = float(
        atmospheric_modeling_py6S_Band['ch4_transmittance_total'])

    # Total transmission of Other Gases -> Tg_OG:
    Tg_OG = float(tg_OG_co * tg_OG_c02 * tg_OG_o2 * tg_OG_no2 * tg_OG_ch4)

    # Total transmission of the Ozone -> Tg_O3:
    Tg_O3 = float(atmospheric_modeling_py6S_Band['ozone_transmittance_total'])

    # Total transmission of the Water Vapor -> Tg_H2O:
    Tg_H20 = float(atmospheric_modeling_py6S_Band['water_transmittance_total'])

    # Total transmittance upward (Rayleigh + Aerosol) -> T_upward:
    T_upward = float(
        atmospheric_modeling_py6S_Band['total_scattering_transmittance_upward'])

    # Total transmittance downward (Rayleigh + Aerosol) -> T_downward:
    T_downward = float(
        atmospheric_modeling_py6S_Band['total_scattering_transmittance_downward'])

    # Total transmission of the atmosphere -> T_atm:
    T_atm = float(T_upward * T_downward)

    # Atmosphere intrinsic reflectance -> p_atm:
    p_atm = float(
        atmospheric_modeling_py6S_Band['atmospheric_intrinsic_reflectance'])

    # Atmosphere spherical albedo -> s_atm:
    s_atm = float(atmospheric_modeling_py6S_Band['spherical_albedo'])

    # Equation (Ref: Vermonte et al., 1997)
    f1 = Tg_OG * Tg_O3 * Tg_H20 * T_atm
    f2 = p_atm / (Tg_H20 * T_atm)
    parte_1 = np.divide(array_prisma, f1)
    parte_2 = np.subtract(parte_1, f2)
    parte_3 = np.multiply(parte_2, s_atm)
    parte_4 = np.add(parte_3, 1)
    p_s = parte_2 / parte_4

    rrs = np.divide(p_s, np.pi) # Calculate de Rrs

    rrs[rrs == rrs[0][0]] = 0

    img_tiff = Image.fromarray(rrs,mode='F')
    # Save each surface reflectance image in a separate file
    name = 'C:/Users/thain/Documents/6S_run/rhos_' + str(a) + '.tiff'
    img_tiff.save(name,'TIFF')

    band_prisma = None

    print(a)

print('FIM')

# %%
# Join all the bands in a stack file:
file_list = ['C:/Users/thain/Documents/6S_run/rhos_' +
             str(k) + '.tiff' for k in bands_prisma_acolite.iloc[0:63]] #Considering only the VNIR (bands 0-63)

files_string = " ".join(file_list)

command_to_join = "gdalbuildvrt -separate stack_6s.vrt " + files_string

os.system(command_to_join)

os.system('gdal_translate stack_6s.vrt PRISMA_6s_rrs_VNIR.tif')

#%%
#Clean the folder
for k in bands_prisma_acolite.values:
    if os.path.exists('C:/Users/thain/Documents/6S_run/rhos_' + str(k) + '.tiff'):
        os.remove('C:/Users/thain/Documents/6S_run/rhos_' + str(k) + '.tiff')


"""Library to perform various corrections on native 6X imagery."""

import re
import setuptools

VERSIONFILE = "correct6x/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
    verstr = mo.group(1)
else:
    raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))

setuptools.setup(
    name="py6x",
    version=verstr,
    description="Correction library for Sentera 6X imagery.",
    packages=setuptools.find_packages(),
    install_requires=[
        "Pillow",
        "numpy",
        "tifffile",
        "pandas",
        "tqdm",
        "opencv-contrib-python",
        "imgparse @ git+https://github.com/SenteraLLC/py-image-metadata-parser.git@v1.9.2"
    ],
    extras_require={
        "dev": ["pytest", "sphinx_rtd_theme", "pre-commit", "m2r", "sphinx"],
    },
)