# encoding=utf-8
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
from datetime import datetime
import time
import socketserver
import logging,sys
from queue import PriorityQueue

from SqlServer import *
from common import TaskInfo
import  common,FBCheckHelper,FBUserHelper,FBLandmarkHelper
import threading

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%Y %b %d %H:%M:%S',
                    #filename='myapp.log',
                    #filemode='w',
                    stream=sys.stdout)

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

mutex = threading.Lock()

class TaskServer:
    def __init__(self):
        self.fbCheckQueue = PriorityQueue()
        self.fbTaskUserQueue = PriorityQueue()
        self.fbTaskLandmarkQueue = PriorityQueue()
        self.serverconfig = common.getDispatchServerConfig()
        self.__serverIP = serverconfig[0]
        self.__serverPort = int(serverconfig[1])
        self.__fbcheckhelper = FBCheckHelper.FBCheckHelper()
        self.__fbuserhelper = FBUserHelper.FBUserHelper()
        self.__fblandmarkhelper = FBLandmarkHelper.FBLandmarkHelper()

    #####################################ExecQuery##################用户信息###################################################################
    def getATaskUser(self,taskType):
        '''
        根据任务类型，从人员任务列表中提取分配一个任务给爬虫
        :param taskType:任务类型
        :return:common.FBTaskUser，FBTaskUser.id=-1，表明没有任务
        '''
        mutex.acquire()
        try:
            #return common.FBTaskUser(-1, 0, '919761698961', '0', '','3')
            if self.fbTaskUserQueue.empty():
                self.fbTaskUserQueue = self.__fbuserhelper.LoadTopNTask(10,taskType)
                logging.debug('reload {0} fbcheck seed!'.format(self.fbTaskUserQueue.qsize()))

            logging.info('count queue has left {0} fbtaskuser seed'.format(self.fbTaskUserQueue.qsize()))

            if not self.fbTaskUserQueue.empty():
                task = self.fbTaskUserQueue.get()[1]
                #XMLRPC传输的long必须改变成string
                task2 = common.FBTask(str(task.id),int(task.priority),str(task.fbid),task.tasktype,task.originalfbid,str(task.deep),task.name)

                logging.info('dispatch fbtaskuser seed:taskid:{0}/priority:{1}/fbid:{2}/name:{3}'.format(task.id,task.priority,task.fbid,task.name))
                #set the running state to 1 running
                self.__fbuserhelper.SetRuningState(task.id,1)
                return task2
            else:
                return common.FBTask(-1,0,'919761698961','0','0','3','name')  #def __init__(self,id,priority,fbid,tasktype,originalfbid,deep,name):
        finally:
            mutex.release()

    def reportFBTaskUserComplete(self,taskid,runningState,completeDescription):
        '''
        报告完成情况
        :param completeDescription:
        :return:
        '''
        mutex.acquire()
        try:
            logging.info('{0},{1},{2}'.format(taskid,runningState,completeDescription))

            self.__fbuserhelper.SetCompleteState(taskid,runningState,completeDescription)
            return 'OK'
        finally:
            mutex.release()

#######################################################账号检测###################################################################
    def getAFBCheckTask(self):
        '''
        根据任务类型，从任务列表中提取分配一个任务给爬虫
        :param taskType:任务类型
        :return:common.FBCheckTodo，如果FBCheckTodo.id=-1，表明没有任务
        '''
        mutex.acquire()
        try:
            if self.fbCheckQueue.empty():
                self.fbCheckQueue = self.__fbcheckhelper.LoadTopNTask(10)
                logging.debug('reload {0} fbcheck seed!'.format(self.fbCheckQueue.qsize()))

            logging.info('count queue has left {0} fbcheck seed'.format(self.fbCheckQueue.qsize()))

            if not self.fbCheckQueue.empty():
                task = self.fbCheckQueue.get()[1]
                logging.debug('dispatch fbcheck seed:{0}/{1}/{2}'.format(task.id,task.mobileoremail,task.origin))
                #set the running state to 1 running
                self.__fbcheckhelper.SetRuningState(task.id,1)
                return task
            else:
                return common.FBCheckTodo(-1,'0','none')
        finally:
            mutex.release()

    def reportFBCheckTaskComplete(self,taskid,runningState,completeDescription):
        '''
        报告完成情况
        :param completeDescription:
        :return:
        '''
        mutex.acquire()
        try:
            self.__fbcheckhelper.SetCompleteState(taskid,runningState,completeDescription)
            return 'OK'
        finally:
            mutex.release()

#####################################ExecQuery##################地标信息###################################################################
    def getATaskLandmark(self, taskType):
        '''
        根据任务类型，从地标任务列表中提取分配一个任务给爬虫
        :param taskType:任务类型
        :return:common.FBTaskUser，FBTaskUser.id=-1，表明没有任务
        '''
        # return common.FBTaskUser(-1, 0, '919761698961', '0', '','3')
        mutex.acquire()
        try:
            logging.debug('reload {0} fblandmark seed!')
            if self.fbTaskLandmarkQueue.empty():
                self.fbTaskLandmarkQueue = self.__fblandmarkhelper.LoadTopNTask(10, taskType)
                logging.debug('reload {0} fblandmark seed!'.format(self.fbTaskLandmarkQueue.qsize()))

            logging.info('count queue has left {0} fblandmark seed'.format(self.fbTaskLandmarkQueue.qsize()))

            if not self.fbTaskLandmarkQueue.empty():
                task = self.fbTaskLandmarkQueue.get()[1]
                # XMLRPC传输的long必须改变成string
                task2 = common.FBTask(str(task.id), int(task.priority), str(task.fbid), task.tasktype,
                                      task.originalfbid, str(task.deep), task.name)

                logging.debug(
                    'dispatch fblandmark seed:taskid:{0}/priority:{1}/fbid:{2}/name:{3}'.format(task.id, task.priority,
                                                                                task.fbid, task.name))
                # set the running state to 1 running
                self.__fblandmarkhelper.SetRuningState(task.id, 1)
                return task2
            else:
                return common.FBTask(-1, 0, '919761698961', '0', '0', '3',
                                     'name')  # def __init__(self,id,priority,fbid,tasktype,originalfbid,deep,name):
        finally:
            mutex.release()

    def reportFBTaskLandmarkComplete(self, taskid, runningState, completeDescription):
        '''
        报告完成情况
        :param completeDescription:
        :return:
        '''
        mutex.acquire()
        try:
            print('{0},{1},{2}'.format(taskid, runningState, completeDescription))

            self.__fblandmarkhelper.SetCompleteState(taskid, runningState, completeDescription)
            return 'OK'
        finally:
            mutex.release()

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

# Create server
#多线程实现
class RPCThreading(socketserver.ThreadingMixIn, SimpleXMLRPCServer):
    pass

serverconfig = common.getDispatchServerConfig()  # 3
serverIP = serverconfig[0]
serverPort = int(serverconfig[1])
with RPCThreading((serverIP,serverPort),requestHandler=RequestHandler) as server:
#with RPCThreading(("localhost", 8089),requestHandler=RequestHandler) as server:
    #Register my function
    # server.register_function(getATask)

    server.register_instance(TaskServer())

    def test():
        return 'Connected!'
    server.register_function(test)

    # Register a function under a different name
    def adder_function(x,y):
        return x + y
    server.register_function(adder_function, 'add')

    # Register an instance; all the methods of the instance are
    # published as XML-RPC methods (in this case, just 'mul').
    class MyFuncs:
        def mul(self, x, y):
            return x * y

    #server.register_instance(MyFuncs())    #只能注册一个对象

    print('listening on ip {0} / port {1}'.format(serverIP, serverPort))
    logging.info('listening on ip {0} / port {1}'.format(serverIP, serverPort))

    # Run the server's main loop
    server.serve_forever()


import streamlit as st
import numpy as np
import cv2
import pandas as pd

# ********************

def main():
    st.title('Recognition App')
    st.sidebar.title('Parameters')
    st.sidebar.markdown('Choose Parameters')
    st.subheader('Choose What You want to Identify')
    a = st.selectbox("Choose Option", ("Face", "Smile", "Eyes"))

    if a == 'Face':
        b = st.sidebar.button(
            'Capture Images For Face Recognition 🧔', key='capface')
        if b:
            face_model = cv2.CascadeClassifier(
                'C:/Users/kevka/Documents/Streamlit/HaarCascadeFace.xml')
            cap = cv2.VideoCapture(0)
            while True:
                status, photo = cap.read()
                face_cor = face_model.detectMultiScale(photo)
                if len(face_cor) == 0:
                    pass
                else:
                    x1 = face_cor[0][0]
                    y1 = face_cor[0][1]
                    x2 = x1+face_cor[0][2]
                    y2 = y1+face_cor[0][3]
                    photo = cv2.rectangle(
                        photo, (x1, y1), (x2, y2), [0, 255, 0])
                    cv2.putText(photo, "Hey Kevin", (250, 450),
                                cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
                    cv2.imshow('Look At You', photo)
                    if cv2.waitKey(10) == 13:
                        break
            cv2.destroyAllWindows()
            cap.release()
        st.sidebar.markdown('To Stop, Press Enter')

    if a == 'Smile':
        c = st.sidebar.button(
            'Capture Images For Smile Recognition 😁', key='capnose')
        if c:
            smile_model = cv2.CascadeClassifier(
                'C:/Users/kevka/Documents/Streamlit/HaarCascadeSmile.xml')
            cap = cv2.VideoCapture(0)
            while True:
                status, photos = cap.read()
                smile_cor = smile_model.detectMultiScale(photos)
                if len(smile_cor) == 0:
                    pass
                else:
                    x1 = smile_cor[0][0]
                    y1 = smile_cor[0][1]
                    x2 = x1+smile_cor[0][2]
                    y2 = y1+smile_cor[0][3]
                    photos = cv2.rectangle(
                        photos, (x1, y1), (x2, y2), [0, 255, 0])
                    cv2.putText(photos, "Hey Kevin's Smile", (250, 450),
                                cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
                    cv2.imshow('Look At Your Smile', photos)
                    if cv2.waitKey(10) == 13:
                        break
            cv2.destroyAllWindows()
            cap.release()
        st.sidebar.markdown('To Stop, Press Enter')

    if a == 'Eyes':
        d = st.sidebar.button(
            'Capture Images For Eyes Recognition 👀', key='capeyes')
        if d:
            eyes_model = cv2.CascadeClassifier(
                'C:/Users/kevka/Documents/Streamlit/HaarCascadeEyes.xml')
            cap = cv2.VideoCapture(0)
            while True:
                status, photoe = cap.read()
                eyes_cor = eyes_model.detectMultiScale(photoe)
                if len(eyes_cor) == 0:
                    pass
                else:
                    x1 = eyes_cor[0][0]
                    y1 = eyes_cor[0][1]
                    x2 = x1+eyes_cor[0][2]
                    y2 = y1+eyes_cor[0][3]
                    photoe = cv2.rectangle(
                        photoe, (x1, y1), (x2, y2), [0, 255, 0])
                    cv2.putText(photoe, "Hey Kevin's Eyes", (250, 450),
                                cv2.FONT_HERSHEY_TRIPLEX, 1, (0, 255, 0), 2)
                    cv2.imshow('Look At Your Eyes', photoe)
                    if cv2.waitKey(10) == 13:
                        break
            cv2.destroyAllWindows()
            cap.release()
        st.sidebar.markdown('To Stop, Press Enter')

if __name__ == '__main__':
    main()


from pathlib import Path

from click.testing import CliRunner

from zenml.cli.base import clean, init
from zenml.constants import CONFIG_FILE_NAME, REPOSITORY_DIRECTORY_NAME
from zenml.utils import yaml_utils
from zenml.utils.io_utils import get_global_config_directory

def test_init_creates_zen_folder(tmp_path: Path) -> None:
    """Check that init command creates a .zen folder."""
    runner = CliRunner()
    runner.invoke(init, ["--path", str(tmp_path)])
    assert (tmp_path / REPOSITORY_DIRECTORY_NAME).exists()

def test_clean_user_config(clean_workspace) -> None:
    global_zen_config_yaml = (
        Path(get_global_config_directory()) / CONFIG_FILE_NAME
    )
    assert global_zen_config_yaml.exists()
    yaml_contents = yaml_utils.read_yaml(str(global_zen_config_yaml))
    user_id = yaml_contents["user_id"]
    analytics_opt_in = yaml_contents["analytics_opt_in"]
    version = yaml_contents["version"]
    runner = CliRunner()
    runner.invoke(clean, ["--yes", True])
    new_yaml_contents = yaml_utils.read_yaml(str(global_zen_config_yaml))
    assert user_id == new_yaml_contents["user_id"]
    assert analytics_opt_in == new_yaml_contents["analytics_opt_in"]
    assert version == new_yaml_contents["version"]


import re
from django.contrib.sites import requests

__author__ = 'Travis'

def analysis(tweet_list):

    #links to NLP sentiment analysis at http://text-processing.com/demo/sentiment/
    url = 'http://text-processing.com/api/sentiment/'
    payload = {'text':tweet_list}
    response = requests.post(url, data=payload)
    return_string = response.content
    numbers = re.findall('\d+(\.\d{1,5})', return_string)
    neg_int = float(numbers[0])

    # "neutral int" is another number returned by the API
    # but is unused for this app
    # neutral_int = float(numbers[1])
    pos_int = float(numbers[2])

    if pos_int > neg_int:
        label = "POSITIVE"
    else:
        label = "NEGATIVE"

    neg_int = str(int(neg_int*100)) + "%"
    # neutral_int = str(int(neutral_int*100)) + "%"
    pos_int = str(int(pos_int*100)) + "%"
    analysis_results = {'neg_int':neg_int,'label':label, 'pos_int':pos_int}

    return analysis_results

# def dictionary():
#
#     apiUrl = 'http://api.wordnik.com/v4'
#     apiKey = 'YOUR API KEY HERE'
#     client = swagger.ApiClient(apiKey, apiUrl)
#
#     wordApi = WordApi.WordApi(client)
#     example = wordApi.getTopExample('irony')
#     dict_data = {'example_text':example.text}
#
#     return dict_data

    # https://github.com/wordnik/wordnik-python


from pathlib import Path
from typing import Tuple
import yaml
import tempfile
import uuid
import shutil
from dataclasses import dataclass, asdict

import numpy as np
import audiotools as at
import argbind
import torch

import gradio as gr
from vampnet.interface import Interface
from vampnet import mask as pmask

# Interface = argbind.bind(Interface)
# AudioLoader = argbind.bind(at.data.datasets.AudioLoader)

interface = Interface(
    coarse_ckpt="./models/vampnet/coarse.pth",
    coarse2fine_ckpt="./models/vampnet/c2f.pth",
    codec_ckpt="./models/vampnet/codec.pth",
    wavebeat_ckpt="./models/wavebeat.pth",
    device="cuda" if torch.cuda.is_available() else "cpu",
)

# loader = AudioLoader()
print(f"interface device is {interface.device}")

# dataset = at.data.datasets.AudioDataset(
#     loader,
#     sample_rate=interface.codec.sample_rate,
#     duration=interface.coarse.chunk_size_s,
#     n_examples=5000,
#     without_replacement=True,
# )

OUT_DIR = Path("gradio-outputs")
OUT_DIR.mkdir(exist_ok=True, parents=True)

def load_audio(file):
    print(file)
    filepath = file.name
    sig = at.AudioSignal.salient_excerpt(
        filepath,
        duration=interface.coarse.chunk_size_s
    )
    sig = interface.preprocess(sig)

    out_dir = OUT_DIR / str(uuid.uuid4())
    out_dir.mkdir(parents=True, exist_ok=True)
    sig.write(out_dir / "input.wav")
    return sig.path_to_file

def load_example_audio():
    return "./assets/example.wav"

def _vamp(data, return_mask=False):
    # remove any old files in the output directory (from previous runs)
    shutil.rmtree(OUT_DIR)
    OUT_DIR.mkdir()

    out_dir = OUT_DIR / str(uuid.uuid4())
    out_dir.mkdir()
    sig = at.AudioSignal(data[input_audio])

    z = interface.encode(sig)

    ncc = data[n_conditioning_codebooks]

    # build the mask
    mask = pmask.linear_random(z, data[rand_mask_intensity])
    mask = pmask.mask_and(
        mask, pmask.inpaint(
            z,
            interface.s2t(data[prefix_s]),
            interface.s2t(data[suffix_s])
        )
    )
    mask = pmask.mask_and(
        mask, pmask.periodic_mask(
            z,
            data[periodic_p],
            data[periodic_w],
            random_roll=True
        )
    )
    if data[onset_mask_width] > 0:
        mask = pmask.mask_or(
            mask, pmask.onset_mask(sig, z, interface, width=data[onset_mask_width])
        )
    if data[beat_mask_width] > 0:
        beat_mask = interface.make_beat_mask(
            sig,
            after_beat_s=(data[beat_mask_width]/1000),
            mask_upbeats=not data[beat_mask_downbeats],
        )
        mask = pmask.mask_and(mask, beat_mask)

    # these should be the last two mask ops
    mask = pmask.dropout(mask, data[dropout])
    mask = pmask.codebook_unmask(mask, ncc)

    print(f"created mask with: linear random {data[rand_mask_intensity]}, inpaint {data[prefix_s]}:{data[suffix_s]}, periodic {data[periodic_p]}:{data[periodic_w]}, dropout {data[dropout]}, codebook unmask {ncc}, onset mask {data[onset_mask_width]}, num steps {data[num_steps]}, init temp {data[temp]},  use coarse2fine {data[use_coarse2fine]}")
    # save the mask as a txt file
    np.savetxt(out_dir / "mask.txt", mask[:,0,:].long().cpu().numpy())

    zv, mask_z = interface.coarse_vamp(
        z,
        mask=mask,
        sampling_steps=data[num_steps],
        temperature=float(data[temp]*10),
        return_mask=True,
        typical_filtering=data[typical_filtering],
        typical_mass=data[typical_mass],
        typical_min_tokens=data[typical_min_tokens],
        gen_fn=interface.coarse.generate,
    )

    if use_coarse2fine:
        zv = interface.coarse_to_fine(zv, temperature=data[temp])

    sig = interface.to_signal(zv).cpu()
    print("done")

    sig.write(out_dir / "output.wav")

    if return_mask:
        mask = interface.to_signal(mask_z).cpu()
        mask.write(out_dir / "mask.wav")
        return sig.path_to_file, mask.path_to_file
    else:
        return sig.path_to_file

def vamp(data):
    return _vamp(data, return_mask=True)

def api_vamp(data):
    return _vamp(data, return_mask=False)

def save_vamp(data):
    out_dir = OUT_DIR / "saved" / str(uuid.uuid4())
    out_dir.mkdir(parents=True, exist_ok=True)

    sig_in = at.AudioSignal(data[input_audio])
    sig_out = at.AudioSignal(data[output_audio])

    sig_in.write(out_dir / "input.wav")
    sig_out.write(out_dir / "output.wav")

    _data = {
        "temp": data[temp],
        "prefix_s": data[prefix_s],
        "suffix_s": data[suffix_s],
        "rand_mask_intensity": data[rand_mask_intensity],
        "num_steps": data[num_steps],
        "notes": data[notes_text],
        "periodic_period": data[periodic_p],
        "periodic_width": data[periodic_w],
        "n_conditioning_codebooks": data[n_conditioning_codebooks],
        "use_coarse2fine": data[use_coarse2fine],
        "stretch_factor": data[stretch_factor],
    }

    # save with yaml
    with open(out_dir / "data.yaml", "w") as f:
        yaml.dump(_data, f)

    import zipfile
    zip_path = out_dir.with_suffix(".zip")
    with zipfile.ZipFile(zip_path, "w") as zf:
        for file in out_dir.iterdir():
            zf.write(file, file.name)

    return f"saved! your save code is {out_dir.stem}", zip_path

with gr.Blocks() as demo:

    with gr.Row():
        with gr.Column():
            gr.Markdown("# VampNet")
            gr.Markdown("""## Description:
            This is a demo of VampNet, a masked generative music model capable of doing music variations.
            You can control the extent and nature of variation with a set of manual controls and presets.
            Use this interface to experiment with different mask settings and explore the audio outputs.
            """)

            gr.Markdown("""
            ## Instructions:
            1. You can start by uploading some audio, or by loading the example audio.
            2. Choose a preset for the vamp operation, or manually adjust the controls to customize the mask settings. Click the load preset button.
            3. Click the "generate (vamp)!!!" button to generate audio. Listen to the output audio, and the masked audio to hear the mask hints.
            4. Optionally, you can add some notes and save the result.
            5. You can also use the output as the new input and continue experimenting!
            """)
    with gr.Row():
        with gr.Column():

            manual_audio_upload = gr.File(
                label=f"upload some audio (will be randomly trimmed to max of {interface.coarse.chunk_size_s:.2f}s)",
                file_types=["audio"]
            )
            load_example_audio_button = gr.Button("or load example audio")

            input_audio = gr.Audio(
                label="input audio",
                interactive=False,
                type="filepath",
            )

            audio_mask = gr.Audio(
                label="audio mask (listen to this to hear the mask hints)",
                interactive=False,
                type="filepath",
            )

            # connect widgets
            load_example_audio_button.click(
                fn=load_example_audio,
                inputs=[],
                outputs=[ input_audio]
            )

            manual_audio_upload.change(
                fn=load_audio,
                inputs=[manual_audio_upload],
                outputs=[ input_audio]
            )

        # mask settings
        with gr.Column():

            presets = {
                    "unconditional": {
                        "periodic_p": 0,
                        "onset_mask_width": 0,
                        "beat_mask_width": 0,
                        "beat_mask_downbeats": False,
                    },
                    "slight periodic variation": {
                        "periodic_p": 7,
                        "onset_mask_width": 0,
                        "beat_mask_width": 0,
                        "beat_mask_downbeats": False,
                    },
                    "strong periodic variation": {
                        "periodic_p": 13,
                        "onset_mask_width": 5,
                        "beat_mask_width": 0,
                        "beat_mask_downbeats": False,
                    },
                    "very strong periodic variation": {
                        "periodic_p": 17,
                        "onset_mask_width": 5,
                        "beat_mask_width": 0,
                        "beat_mask_downbeats": False,
                    },
                    "beat-driven variation": {
                        "periodic_p": 0,
                        "onset_mask_width": 0,
                        "beat_mask_width": 20,
                        "beat_mask_downbeats": False,
                    },
                    "beat-driven variation (downbeats only, strong)": {
                        "periodic_p": 0,
                        "onset_mask_width": 0,
                        "beat_mask_width": 20,
                        "beat_mask_downbeats": True,
                    },
                }

            preset = gr.Dropdown(
                label="preset",
                choices=list(presets.keys()),
                value="strong periodic variation",
            )
            load_preset_button = gr.Button("load_preset")

            with gr.Accordion("manual controls", open=True):
                periodic_p = gr.Slider(
                    label="periodic prompt  (0 - unconditional, 2 - lots of hints, 8 - a couple of hints, 16 - occasional hint, 32 - very occasional hint, etc)",
                    minimum=0,
                    maximum=128,
                    step=1,
                    value=13,
                )

                onset_mask_width = gr.Slider(
                    label="onset mask width (multiplies with the periodic mask, 1 step ~= 10milliseconds) ",
                    minimum=0,
                    maximum=20,
                    step=1,
                    value=5,
                )

                beat_mask_width = gr.Slider(
                    label="beat mask width (in milliseconds)",
                    minimum=0,
                    maximum=200,
                    value=0,
                )
                beat_mask_downbeats = gr.Checkbox(
                    label="beat mask downbeats only?",
                    value=False
                )

                with gr.Accordion("extras ", open=False):
                    rand_mask_intensity = gr.Slider(
                        label="random mask intensity. (If this is less than 1, scatters prompts throughout the audio, should be between 0.9 and 1.0)",
                        minimum=0.0,
                        maximum=1.0,
                        value=1.0
                    )

                    periodic_w = gr.Slider(
                        label="periodic prompt width (steps, 1 step ~= 10milliseconds)",
                        minimum=1,
                        maximum=20,
                        step=1,
                        value=1,
                    )
                    n_conditioning_codebooks = gr.Number(
                        label="number of conditioning codebooks. probably 0",
                        value=0,
                        precision=0,
                    )

                    stretch_factor = gr.Slider(
                        label="time stretch factor",
                        minimum=0,
                        maximum=64,
                        step=1,
                        value=1,
                    )

            preset_outputs = {
                periodic_p,
                onset_mask_width,
                beat_mask_width,
                beat_mask_downbeats,
            }

            def load_preset(_preset):
                return tuple(presets[_preset].values())

            load_preset_button.click(
                fn=load_preset,
                inputs=[preset],
                outputs=preset_outputs
            )

            with gr.Accordion("prefix/suffix prompts", open=False):
                prefix_s = gr.Slider(
                    label="prefix hint length (seconds)",
                    minimum=0.0,
                    maximum=10.0,
                    value=0.0
                )
                suffix_s = gr.Slider(
                    label="suffix hint length (seconds)",
                    minimum=0.0,
                    maximum=10.0,
                    value=0.0
                )

            temp = gr.Slider(
                label="temperature",
                minimum=0.0,
                maximum=10.0,
                value=1.8
            )

            with gr.Accordion("sampling settings", open=False):
                typical_filtering = gr.Checkbox(
                    label="typical filtering ",
                    value=False
                )
                typical_mass = gr.Slider(
                    label="typical mass (should probably stay between 0.1 and 0.5)",
                    minimum=0.01,
                    maximum=0.99,
                    value=0.15
                )
                typical_min_tokens = gr.Slider(
                    label="typical min tokens (should probably stay between 1 and 256)",
                    minimum=1,
                    maximum=256,
                    step=1,
                    value=64
                )

            use_coarse2fine = gr.Checkbox(
                label="use coarse2fine",
                value=True
            )

            num_steps = gr.Slider(
                label="number of steps (should normally be between 12 and 36)",
                minimum=1,
                maximum=128,
                step=1,
                value=36
            )

            dropout = gr.Slider(
                label="mask dropout",
                minimum=0.0,
                maximum=1.0,
                step=0.01,
                value=0.0
            )

        # mask settings
        with gr.Column():
            vamp_button = gr.Button("generate (vamp)!!!")
            output_audio = gr.Audio(
                label="output audio",
                interactive=False,
                type="filepath"
            )

            notes_text = gr.Textbox(
                label="type any notes about the generated audio here",
                value="",
                interactive=True
            )
            save_button = gr.Button("save vamp")
            download_file = gr.File(
                label="vamp to download will appear here",
                interactive=False
            )
            use_as_input_button = gr.Button("use output as input")

            thank_you = gr.Markdown("")

    _inputs = {
            input_audio,
            num_steps,
            temp,
            prefix_s, suffix_s,
            rand_mask_intensity,
            periodic_p, periodic_w,
            n_conditioning_codebooks,
            dropout,
            use_coarse2fine,
            stretch_factor,
            onset_mask_width,
            typical_filtering,
            typical_mass,
            typical_min_tokens,
            beat_mask_width,
            beat_mask_downbeats
        }

    # connect widgets
    vamp_button.click(
        fn=vamp,
        inputs=_inputs,
        outputs=[output_audio, audio_mask],
    )

    api_vamp_button = gr.Button("api vamp", visible=False)
    api_vamp_button.click(
        fn=api_vamp,
        inputs=_inputs,
        outputs=[output_audio],
        api_name="vamp"
    )

    use_as_input_button.click(
        fn=lambda x: x,
        inputs=[output_audio],
        outputs=[input_audio]
    )

    save_button.click(
        fn=save_vamp,
        inputs=_inputs | {notes_text, output_audio},
        outputs=[thank_you, download_file]
    )

demo.queue().launch()


import numpy as np
import numpy.linalg as nplg
import scipy.linalg as sclg
from functional import cost_function,gradient,hessian
from modCholDec import modDec
from utilities import unvec

"""
Implemetation of the modified newton method for cost function minimization

"""

def rec(P0, D,W, conv):
    """
    Use the modified newton method to reconstruct the point configuration that
    generate D
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    Parameters:
        P0: initial guess, is an (d,n) matrix, where d is the embedding
            dimension and n is the nuber of points
        D: measured (n,n) EDM
        W: (n,n) Mask matrix corresponding to D
        conv: convergence rate
    Returns:
        (d,n) matrix containing the estimated configuration that generates D
    """

    first = 1.#first term of convergence condition
    second = 0.#second term of convergence condition
    P = P0#initial guess
    iter = 0#iter counter

    #starting the cycle
    while first> second:
        #store the old configuration
        POld = P

        #compute hessian and gradient
        G = gradient(P,D,W)
        H = hessian(P,D,W)

        #compute LS via modified cholewsky decomposition
        S,L = modDec(H)

        #find the upgrade term by solving the systems
        epsII = sclg.solve_triangular(L,-G)
        epsI  = nplg.solve(S,epsII)
        eps   = sclg.solve_triangular(L,epsI)
        term = unvec(eps, np.shape(P0))

        #update the guess
        P = P + (2**-iter)*term
        iter +=1

        #update convergence terms
        first = abs(cost_function(P,D,W)-cost_function(POld,D,W))
        second = conv*nplg.norm(P-POld, ord = 2)

    return P


import numpy as np
import torch

@torch.no_grad()
def mixup(x, y, alpha=0.2):
	if alpha > 0:
		lam = np.random.beta(alpha, alpha)
	else:
		lam = 1

	mixed_x = lam * x + (1 - lam) * x.flip(dims=(0,))
	y_a, y_b = y, y.flip(dims=(0,))
	return mixed_x, y_a, y_b, lam

def mixup_criterion(criterion, pred, y_a, y_b, lam):
	return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)


import os
import pyautogui
import pyperclip
from PIL import ImageGrab
import random
import urllib.parse
from time import sleep
from datetime import datetime

from common.services.common_service import CommonService

class PyAutoGuiService(CommonService):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        os.makedirs('./common/services/pyautogui/temporary/', exist_ok=True)
        self.screenshot = ImageGrab.grab()

    def click_icon(self, image_path, x=None, y=None, diff_x=0, diff_y=0, type='left'):
        try:
            if x is None and y is None:
                x, y = pyautogui.locateCenterOnScreen(image_path)
                x = x + diff_x
                y = y + diff_y
            pyautogui.moveTo(x, y, duration=0.25)
            if type == 'right':
                pyautogui.click()
                sleep(0.1)
                pyautogui.rightClick()
            else:
                pyautogui.click(x, y)
        except Exception as ex:
            print("[click_icon] 対象が見つかりませんでした。")
            print(ex)

    def read_chrome_position(self, browser='chrome'):
        try:
            # image_path = './common/services/pyautogui/image/chrome_left_up.png'
            chrome_left_up_path = './common/services/pyautogui/image/' + browser + '_left_up.png'
            chrome_left_up = pyautogui.locateOnScreen(chrome_left_up_path)
            print('1_______', chrome_left_up, chrome_left_up_path)

            chrome_right_bottom_path = './common/services/pyautogui/image/' + browser + '_right_bottom.png'
            chrome_right_bottom = pyautogui.locateOnScreen(chrome_right_bottom_path)
            print('2_______', chrome_right_bottom)

            chrome_search_path = './common/services/pyautogui/image/' + browser + '_search.png'
            x, y = pyautogui.locateCenterOnScreen(chrome_search_path)
            print('3_______', x, y)

            return {
                'top': chrome_left_up.top,
                'left': chrome_left_up.left,
                'right': chrome_right_bottom.left + chrome_right_bottom.width,
                'bottom': chrome_right_bottom.top + chrome_right_bottom.height,
                'search': {
                    'x': x + 50,
                    'y': y
                }
            }

        except Exception as ex:
            print("[read_chrome] 対象が見つかりませんでした。")
            print(ex)

    def start_chrome(self, image_path=None, browser='chrome'):
        today = datetime.now().strftime('%Y%m%d_%H%M%S')
        if image_path is None:
            image_path = './common/services/pyautogui/temporary/screenshot_start_chrome_' + today + '.jpg'
        # self.screenshot.save(image_path)
        # pyautogui.screenshot(image_path)
        # sleep(2)

        # image_path = './common/services/pyautogui/image/icon_chrome_taskbar.png'
        self.click_icon(image_path, x=163, y=752)
        self.click_icon(image_path)
        sleep(3)

        # chrome_position = self.read_chrome_position(browser=browser)
        # print(chrome_position)
        chrome_position = {
            'top': 6,
            'left': 52,
            'right': 1211,
            'bottom': 728,
            'search': {'x': 196, 'y': 60}  # {'x': 287, 'y': 155}
        }
        return chrome_position

    def open_chrome(self, x, y, url):
        pyautogui.moveTo(x, y)
        pyautogui.click()
        pyperclip.copy(url)
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.press('delete')
        pyautogui.hotkey('ctrl', 'v')
        pyautogui.press('enter')

    def open_develop_mode(self, x=None, y=None, type='pc'):
        pyautogui.press('f12')
        sleep(3)

        if type == 'pc':
            image_path = './common/services/pyautogui/image/edge_dom_pc.png'
            self.click_icon(image_path, x=x, y=y, diff_x=-15)

    def click2(self, x, y):
        pyautogui.moveTo(x, y)
        pyautogui.click()

    def click_image_curve(self, image_path=None, x=227, y=499, count=1):
        try:
            if image_path is not None:
                x, y = pyautogui.locateCenterOnScreen(image_path)
                print(x, y)
        except Exception as e:
            print(e)

        x0, y0 = pyautogui.position()
        diff_x1 = 20 * random.random()
        diff_y1 = 20 * random.random()
        diff_x2 = 5 * random.random()
        diff_y2 = 5 * random.random()
        pyautogui.moveTo((x + x0)/2 + diff_x1, (y + y0)/2 + diff_y1, duration=0.25)
        pyautogui.moveTo(x + diff_x2, y + diff_y2, duration=0.25)

        for i in range(count):
            print('skip count ', count)
            pyautogui.click()
            sleep(0.5 + 0.5 * random.random())

    def click_image(self, image_path=None, x=None, y=None, random_x=10, random_y=10):
        if x is None and y is None:
            try:
                x, y = pyautogui.locateCenterOnScreen(image_path)
                print(x, y)
            except Exception as e:
                print(e)

        self.dummy_move(x, y, random_x=20, random_y=20)
        self.click(x, y, random_x=random_x, random_y=random_y)
        return x, y

    def click(self, x, y, random_x=10, random_y=10):
        # final_x = x + random.uniform(random_x, random_x * -1)
        # final_y = y + random.uniform(random_y, random_y * -1)
        # move1_x = final_x + random.uniform(100, 100 * -1)
        # move1_y = final_y + random.uniform(100, 100 * -1)
        # move2_x = final_x + random.uniform(50, 50 * -1)
        # move2_y = final_y + random.uniform(50, 50 * -1)
        # pyautogui.moveTo(move1_x, move1_y, duration=0.25)
        # pyautogui.moveTo(move2_x, move2_y, duration=0.25)
        # pyautogui.moveTo(final_x, final_y, duration=0.25)
        # sleep(0.2)
        self.dummy_move(x, y, random_x=random_x, random_y=random_y)
        sleep(0.2)
        pyautogui.click()
        # pyautogui.click()
        # pyautogui.mouseDown()
        # sleep(0.2)
        # pyautogui.mouseUp()

    def copy_text(self, x, y):
        pyautogui.moveTo(x, y)
        pyautogui.click()
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.hotkey('ctrl', 'c')
        pyautogui.click()
        return pyperclip.paste()

    def copy_dom(self, x, y):
        image_path = './common/services/pyautogui/image/edge_dom.png'

        if x is None and y is None:
            x, y = pyautogui.locateCenterOnScreen(image_path)
            x = x
            y = y - 40
        pyautogui.moveTo(x, y, duration=0.25)
        pyautogui.click()
        pyautogui.scroll(3500, x=x, y=y)
        sleep(0.5)
        self.click_icon(image_path, x=x, y=y, diff_y=30, type='right')
        sleep(0.2)

        pyautogui.moveTo(x + 50, y + 150)
        pyautogui.click()
        sleep(0.2)

        pyautogui.moveTo(x + 260, y + 150)
        pyautogui.click()

        return pyperclip.paste()

    def dummy_move(self, x, y, random_x=10, random_y=10):
        final_x = int(x + random.uniform(random_x, random_x * -1))
        final_y = int(y + random.uniform(random_y, random_y * -1))
        move1_x = int(final_x + random.uniform(100, 100 * -1))
        move1_y = int(final_y + random.uniform(100, 100 * -1))
        move2_x = int(final_x + random.uniform(50, 50 * -1))
        move2_y = int(final_y + random.uniform(50, 50 * -1))
        pyautogui.moveTo(move1_x, move1_y, duration=0.25)
        pyautogui.moveTo(move2_x, move2_y, duration=0.25)
        pyautogui.moveTo(final_x, final_y, duration=0.25)
        sleep(0.2)
        return final_x, final_y

    def dummy_scroll(self, x, y, random_x=10, random_y=10, scroll_to=300):
        final_x, final_y = self.dummy_move(x, y, random_x=random_x, random_y=random_y)
        pyautogui.click()
        sleep(0.3 * random.random())
        scroll1 = int((scroll_to * 0.3 + random.uniform(scroll_to * 0.3, 0)) * -1)
        scroll2 = int((scroll_to * 0.3 + random.uniform(scroll_to * 0.3, 0)) * -1)
        scroll3 = int((scroll_to * 0.3 + random.uniform(scroll_to * 0.3, 0)) * -1)
        random_x1 = x + random.uniform(random_x, random_x * -1)
        random_x2 = x + random.uniform(random_x, random_x * -1)

        pyautogui.scroll(scroll1, x=(final_x + random_x1), y=final_y)
        sleep(0.3 * random.random())
        pyautogui.scroll(scroll2, x=(final_x + random_x2), y=final_y)
        sleep(0.2 * random.random())
        pyautogui.scroll(scroll3, x=final_x, y=final_y)
        sleep(0.2 * random.random())
        return pyautogui.position()

    def test(self, x, y, random_x=10, random_y=10):
        pyautogui.moveTo(x, y)
        pyautogui.click()
        pyautogui.hotkey('ctrl', 'a')


import itertools
n=int(input())
arr=[]
for i in range(n):
    p=int(input())
    arr.append(p)

ans=10**10
for i in list(itertools.product((0,1),repeat=n)):
    p0=0
    p1=0

    for j in range(n):
        if i[j]==0:
            p0+=arr[j]
        else:
            p1+=arr[j]

    ans = min(ans,max(p0,p1))

print(ans)


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
from django.conf import settings
from django.core.files.storage import FileSystemStorage
import time
import os.path
from . import steg as lsbsteg
from . import filesteg as lsbfilesteg

UPLOAD_ROOT = os.path.dirname(os.path.realpath(__name__))

# Create your views here.

def index(request):
    return render(request, 'index.html', {})

def encode(request):
    return render(request, 'encode.html', {})

def process_encoding_data(request):
    if request.method == 'POST' and request.FILES['coverimage']:
        coverimage = upload_file(request.FILES['coverimage'])
        if request.POST.get('istextsteg'):
            message = request.POST.get('message')
            stegImage = encode_image_text_steg(message, coverimage)
            return JsonResponse(status=200, data={'status': 'true', 'location': '../' + stegImage})

        else:
            textstegfile = upload_file(request.FILES['textfile'])
            stegImage = encode_image_text_file_steg(textstegfile, coverimage)
            return JsonResponse(status=200, data={'status': 'true', 'location': '../' + stegImage})
    if request.method == 'GET':
        return HttpResponseNotFound('
Not Allowed
')

def encode_image_text_steg(message, coverimg):
    if message == '':
        message = 'no text found'
    if coverimg is not None:
        newImg = lsbsteg.encodeLSB(message, UPLOAD_ROOT + coverimg)
        if not newImg is None:
            return newImg
        else:
            return

def encode_image_text_file_steg(textfile, coverimg):
    if coverimg is not None and textfile is not None:
        newImg = lsbfilesteg.encodeLSB(UPLOAD_ROOT + textfile, UPLOAD_ROOT + coverimg)
        if not newImg is None:
            return newImg
        else:
            return

def decode(request):
    return render(request, 'decode.html', {})

def process_decoding_data(request):
    if request.method == 'POST' and request.FILES['stegimage']:
        steg_image = upload_file(request.FILES['stegimage'])
        if request.POST.get('istextsteg'):
            messageDecoded = decode_text_from_image(steg_image)
            return JsonResponse(status=200, data={'status': 'true', 'message': messageDecoded})

        else:
            textfile = decode_textfile_from_image(steg_image)
            return JsonResponse(status=200, data={'status': 'true', 'location': '../' + textfile})
    if request.method == 'GET':
        return HttpResponseNotFound('
Not Allowed
')

def decode_text_from_image(steg_image):
    if steg_image is not None:
        message_decoded = lsbsteg.decodeLSB(UPLOAD_ROOT + steg_image)
        if not message_decoded is None:
            return message_decoded
        else:
            return

def decode_textfile_from_image(steg_image):
    textFile = lsbfilesteg.decodeLSB(UPLOAD_ROOT + steg_image)
    if not textFile is None:
        return textFile
    else:
        return

def upload_file(my_file):
    if my_file is not None:
        fs = FileSystemStorage()
        extension = os.path.splitext(my_file.name)[1]
        filename = fs.save(time_in_millisecond() + extension, my_file)
        uploaded_file_url = fs.url(filename)
        return uploaded_file_url
    else:
        return None

def time_in_millisecond():
    millis = int(round(time.time() * 1000))
    return str(millis)


import numpy as np
from collections import deque
from itertools import count
from matplotlib.patches import Circle
import matplotlib
import matplotlib.pyplot as plt
from .math import length_squared, angle_between
from .area import Area
import time
from scipy.ndimage.interpolation import rotate
from .pedestriannumba import calculate_pedestrian_repulsive_force

class Pedestrian(object):
    """ Generate a pedestrian object.

    Generates a pedestrian and links it to the group. If start and/or
    target_path are not defined, it generates them from the spawn,
    target_path and target_area defined in the group.

    Args:
        pedestrian_id: unique id for this pedestrian
        group: the group to which this pedestrian is assigned
        desired_velocity: the desired velocity for this pedestrian
        relaxation_time: how quickly a pedestrian moves to their desired
            velocity
        start: a np.array([x,  y]) with the spawn point
        target_path: a list of np.array([x,  y]) objects that represents
            the path that this pedestrian should follow. If the pedestrian
            can see the next target in the list (meaning it is not
            obstructed from view by a wall) it will remove the previous
            target. Once the final target has been reached, the pedestrian
            will either be removed from the world or be given a new target
            within the target area.
    """
    _ids = count(0)

    def __init__(self, group, **kwargs):

        self.radius = 0.2
        self.mass = 60
        self.desired_velocity = 1.3
        self.maximum_velocity = 2.6
        self.relaxation_time = 0.5
        self.start = None
        self.target_path = []

        default_values = group.get_pedestrian_defaults()

        # Override default values
        for key, default_value in default_values.items():
            if key in kwargs:
                setattr(self, key, kwargs[key])
            else:
                setattr(self, key, default_value)

        if 'start' in kwargs:
            self.position = kwargs['start']
        else:
            self.position = group.generate_spawn()

        self.id = next(self._ids)
        self.group = group
        self.diameter = 2 * self.radius

        self.target_is_point = True
        self.angle_ou_process = False
        self.velocity_ou_process = False
        self.desired_offset_angle = 0.0
        self.desired_velocity_offset = 0.0
        self.closest_obstacle_points = []
        self.is_braking = False
        self.original_desired_velocity = self.desired_velocity

        self.target_index = 0
        self.target = self.target_path[self.target_index]
        self.quad = None

        self.initialize()

        self.current_max_repulsion = 160.0

        # Make sure this pedestrian is in the group.
        group.add_pedestrian(self)
        self.max_repulsive_force = group.world.turbulence_max_repulsion

        # Create a measurement history object to be filled on 'update'.
        self.measurements = []

    def initialize(self):
        # Start with a velocity equal to the desired velocity.
        self.desired_direction = self.get_desired_direction()
        velocity = self.desired_direction * self.desired_velocity
        self.velocity = np.array([velocity[0],  velocity[1]])

        self.next_velocity = self.velocity
        self.next_position = self.position
        self.speed = np.sqrt(self.velocity[0]**2 + self.velocity[1]**2)
        self.next_speed = self.speed

    def add_measurement(self, category, name, value):
        """ Add a measurement for this time step to this pedestrian.

        Args:
            category: category of measurement
            name: name of measurement
            value: value of measurement
        """
        # if category != 'self':
        #     return

        if category not in self.measurements[-1]:
            self.measurements[-1][category] = dict()
        self.measurements[-1][category][name] = value

    def get_measurement(self, category, name, time=-1):
        """ Get a measurement for a time step of this pedestrian.

        Args:
            category: category of measurement
            name: name of measurement
            time: array offset to get measurement from (default last)
        """
        if time is not -1 and time not in self.measurements:
            return False
        return self.measurements[time][category][name]

    def set_ornstein_uhlenbeck_process(self, mean, theta, sigma, process):
        """ Enable the Ornstein-Uhlenbeck process for deviating desired
        direction.

        The desired direction of the pedestrian will emulate brownian motion,
        but will gravitate towards the target.

        Args:
            mean: mean angle offset, usually zero
            theta: scaling factor of difference with mean
            sigma: scaling factor of random variation
        """
        if process == 'angle':
            self.angle_ou_process = (mean, theta, sigma)
        elif process == 'velocity':
            self.velocity_ou_process = (mean, theta, sigma)

    def step(self, step_size, obstacles):
        """ Calculate the position and velocity at next timestep.

        The new values are stored in the next_position and next_velocity
        attributes of the pedestrian. These are not immediately updated to
        avoid an order in which pedestrians are considered. Call the update
        function after step to update the position and velocity.

        Args:
            step_size: size of step, or time (dt) over which is propagated.
            pedestrians: list of pedestrians in system
            obstacles: list of obstacles in system
        """

        if len(self.target_path) == 0:
            self.next_velocity = np.array([0.0, 0.0])
            self.next_speed = 0.0
            return

        braking_chance = self.group.world.braking_chance
        if braking_chance > 0 and np.random.random() < braking_chance:
            # print("{}: Braking {}".format(self.group.world.time, self.id))
            self.desired_velocity = 0.0
            self.is_braking = True

        self.measurements.append({})
        self.add_measurement('self', 'time', self.group.world.time)

        # Calculate the new velocity and position using Social Force
        # Propagation.
        position, velocity = self.calculate_position_and_velocity(
            step_size, obstacles)

        # In case of a continuous domain, check if the pedestrian has
        # passed the boundaries. If so, move it.
        if self.group.world.continuous_domain:
            # Make a copy for future reference
            copy = np.array(position)
            position[0] = position[0] % self.group.world.width
            position[1] = position[1] % self.group.world.height

        # Update own position and velocity.
        self.next_position = position
        self.next_velocity = velocity

        # Update barrier counts.
        for barrier in self.group.world.barriers:
            barrier.check_if_passed(self)

        self.next_speed = np.sqrt(length_squared(self.next_velocity))

        # Add position, velocity and speed to history.
        self.add_measurement('self', 'position', self.next_position)
        self.add_measurement('self', 'velocity', self.next_velocity)
        self.add_measurement('self', 'speed', self.next_speed)

    def calculate_position_and_velocity(self, step_size, obstacles):
        """ Calculate the next position and velocity if this pedestrian.

        Args:
            step_size: size of step, or time (dt) over which is propagated.
            obstacles: list of obstacles in system

        Returns:
            np.array of size 2 containing new position
            np.array of size 2 containing new velocity
        """
        force = self.calculate_force(obstacles)

        # Calculate the new velocity
        velocity_new = self.velocity + step_size * force

        # Adjust new velocity if it is above maximum_velocity
        maximum_velocity = self.maximum_velocity
        if length_squared(velocity_new) > maximum_velocity**2:
            factor = np.sqrt((velocity_new[0]**2 + velocity_new[1]**2) /
                             maximum_velocity**2)
            velocity_new = velocity_new / factor

        self_position = np.array(self.position)

        position_new = self_position + step_size * velocity_new

        return position_new, velocity_new

    def goal_obstructed(self, goal, factor=1.0):
        """ Check whether the path to a goal is obstructed by obstacles. It does so by taking
        three points at consistent angles and checking if their line of sight is obstructed."""
        pos = np.array(self.position)
        if isinstance(goal, Area):
            goal = goal.get_closest_point(pos)

        goal_vec = goal - pos
        if length_squared(goal_vec) < 0.001:
            return False

        positions_checked = [pos + factor * self.radius * np.array([np.cos(angle), np.sin(angle)])
                             for angle in [0, 2.0 * np.pi / 3, 4.0 * np.pi / 3]]

        for obstacle in self.group.world.obstacles:
            for position in positions_checked:
                if obstacle.intersects(position, goal) is not None:
                    return True

        return False

    def update(self):
        """ Update the target_path and characteristics of this pedestrian. """
        if not self.quad.inside(self.next_position):
            self.group.world.quadtree.remove(self)
            try:
                self.group.world.quadtree.remove(self)
            except KeyError:
                print(self.position)
                print(self.next_position)
                print(self.quad.length)
                print(self.quad.xmin)
                print(self.quad.ymin)
                print(self.group.world.quadtree.length)
                raise

        # Determine whether braking should stop.
        if self.is_braking and (self.speed != self.next_speed and self.speed / self.next_speed < 1.5):
            self.is_braking = False
            self.desired_velocity = self.original_desired_velocity

        # Update position, velocity and speed.
        self.position = self.next_position
        self.velocity = self.next_velocity
        self.speed = self.next_speed

        # Updated desired velocity if Ornstein Uhlenbeck processes are enabled.
        if self.angle_ou_process is not False:
            # mean, theta, sigma = self.ornstein_uhlenbeck

            mean, theta, sigma = self.angle_ou_process

            angle = (theta * (mean - self.desired_offset_angle) *
                     self.group.world.step_size + sigma *
                     np.random.normal())
            self.desired_offset_angle += angle

        if self.velocity_ou_process is not False:
            # mean, theta, sigma = self.ornstein_uhlenbeck

            mean, theta, sigma = self.velocity_ou_process

            diff = (theta * (mean - self.desired_velocity_offset) *
                     self.group.world.step_size + sigma *
                     np.random.normal())
            self.desired_velocity_offset += diff

        # Make sure the pedestrian is inside the quadtree.
        if not self.quad:
            self.group.world.quadtree.add(self)

        # If the target index is out of range, we have reached our destination.
        if len(self.target_path) == self.target_index:
            return

        # First check if the current target is not obstructed. If it is, work
        # back through the target path to find the closest previous target that
        # is unobstructed.
        while True:
            obstructed = self.goal_obstructed(self.target)

            if obstructed:
                if self.target_index == 0:
                    # print "Error ({}): path obstructed.".format(self.id)
                    break
                else:
                    self.target_index -= 1
                    self.target = self.target_path[self.target_index]
            else:
                break

        # Find the next target that is not obstructed.
        if len(self.target_path) - self.target_index > 1:
            # Look for another target that is not obstructed from view.
            obstructed = False
            while not obstructed and len(self.target_path) - self.target_index > 1:
                next_target = self.target_path[self.target_index + 1]
                obstructed = self.goal_obstructed(next_target, factor=1.1)

                if not obstructed:
                    self.target_index += 1
                    self.target = self.target_path[self.target_index]

        self.desired_direction = self.get_desired_direction()

        # If there is only one target and it is within the threshold range,
        # remove it from this passenger.
        threshold = self.group.world.target_distance_threshold
        if len(self.target_path) - self.target_index == 1:
            if self.distance_to_target() < threshold:
                self.target_index += 1
                self.target = None

        # if len(self.target_path) > self.target_index:
        #     target = self.target_path[self.target_index]
        #     self.target = target

    def get_desired_direction(self):
        """ Finds and returns the desired direction of this pedestrian. """
        target = self.target

        # If the target is an area, find the closest point.
        if isinstance(target, Area):
            target = target.get_closest_point(self.position)

        # Calculate the desired direction
        desired_dir = target - self.position

        # If the target equals position, return a zero vector
        if length_squared(desired_dir) < 0.001:
            # print "Warning: target equals position"
            return desired_dir

        # Add a small angle to the desired direction.
        if self.desired_offset_angle != 0.0:
            # print self.desired_offset_angle
            c = np.cos(self.desired_offset_angle)
            s = np.sin(self.desired_offset_angle)
            R = np.matrix([[c, -s],  [s, c]])
            res = R.dot(desired_dir)
            desired_dir = np.array([res[0, 0], res[0, 1]])

        return desired_dir / np.linalg.norm(desired_dir)

    def arrived(self):
        """ Returns whether the pedestrian has arrived at its target. """
        if self.target_index == len(self.target_path):
            return True

        if self.target_index + 1 < len(self.target_path):
            return False

        if isinstance(self.target, Area):
            return self.group.target_area.in_area(self.position)

        if self.distance_to_target() < self.group.world.target_distance_threshold:
            return True

        return False

    def distance_to_target(self):
        """ Returns the distance to the current target. """
        if self.target_index == len(self.target_path):
            return 0.0

        target = self.target

        if isinstance(target, Area):
            target = target.get_closest_point(self.position)

        return np.sqrt(length_squared(self.position - target))

    def set_desired_velocity(self, velocity):
        """ Set the desired velocity of this pedestrian. """
        self.desired_velocity = velocity

    def calculate_force(self, obstacles):
        """ Calculates the sum of attractive and repulsive forces.

        Args:
            pedestrians: list of pedestrians in system
            obstacles: list of obstacles in system

        Returns:
            np.array: sum of forces
        """

        # Get the pedestrians in the current neighbourhood.
        world = self.group.world
        tree = world.quadtree
        threshold = world.interactive_distance_threshold
        pedestrians = tree.get_pedestrians_in_range(self.position, threshold)

        # If we are currently in a continuous domain, we may need to find
        # neighbours on the other side of the domain.
        if world.continuous_domain:

            # For an x near the threshold
            if self.position[0] - threshold < 0:
                new_position = np.array(self.position)
                new_position[0] = world.width
                new_threshold = np.sqrt(threshold**2 - self.position[0]**2)
                pedestrians = pedestrians.union(
                    tree.get_pedestrians_in_range(new_position, new_threshold)
                )

            if self.position[0] + threshold > world.width:
                new_position = np.array(self.position)
                new_position[0] = 0
                new_threshold = np.sqrt(threshold**2 - (
                    world.width - self.position[0])**2)
                pedestrians = pedestrians.union(
                    tree.get_pedestrians_in_range(new_position, new_threshold)
                )

            # For a y near the threshold
            if self.position[1] - threshold < 0:
                new_position = np.array(self.position)
                new_position[1] = world.height
                new_threshold = np.sqrt(threshold**2 - self.position[1]**2)
                pedestrians = pedestrians.union(
                    tree.get_pedestrians_in_range(new_position, new_threshold)
                )

            if self.position[1] + threshold > world.height:
                new_position = np.array(self.position)
                new_position[1] = 0
                new_threshold = np.sqrt(threshold**2 - (
                    world.height - self.position[1])**2)
                pedestrians = pedestrians.union(
                    tree.get_pedestrians_in_range(new_position, new_threshold)
                )

        # Calculate the forces and return the sum of forces.
        attractive = self.calculate_attractive_force(pedestrians)
        ped_repulsive, ped_physical = self.calculate_pedestrian_repulsive_force(pedestrians)
        ob_repulsive = self.calculate_obstacle_repulsive_force(obstacles)

        # Ignore other pedestrians if braking.
        if self.is_braking:
            print(attractive, ped_repulsive, ob_repulsive)
            ped_repulsive = np.array([0.0, 0.0])

        total_force = attractive + self.group.repulsion_weight * (
            ped_repulsive + ob_repulsive + ped_physical)

        random_force = np.zeros(2)
        if world.velocity_variance_factor > 0.0:
            stdev = world.velocity_variance_factor * world.step_size
            random_force = np.random.normal(0.0, stdev, size=2)

        # Check whether the unit is going backwards
        target = self.target
        if isinstance(target, Area):
            target = target.get_closest_point(self.position)
        angle_between_force_and_target = angle_between(total_force, target - self.position)
        angle_between_velocity_and_target = angle_between(self.velocity, target - self.position)

        self.add_measurement('forces', 'force_angle', angle_between_force_and_target)
        self.add_measurement('forces', 'velocity_angle', angle_between_velocity_and_target)
        self.add_measurement('forces', 'attractive', attractive)
        self.add_measurement('forces', 'pedestrian_repulsive', ped_repulsive)
        self.add_measurement('forces', 'obstacle_repulsive', ob_repulsive)

        return total_force + random_force

    def calculate_attractive_force(self, pedestrians):
        """ Calculates the attractive force towards the next target.

        Returns:
            np.array: attractive force towards target.
        """

        desired_dir = self.desired_direction
        velocity_factor = self.group.world.desired_velocity_importance
        # braking_chance = self.group.world.braking_chance
        preferred_velocity = np.array([0.0, 0.0])

        # Calculate average velocity in neighbourhood.
        average_velocity = np.array([0.0, 0.0])
        if velocity_factor < 1.0 and len(pedestrians):
            for p in pedestrians:
                average_velocity += p.velocity
            average_velocity /= len(pedestrians)
        else:
            velocity_factor = 1.0

        # print(self.relaxation_time)

        # There might be a chance the pedestrian randomly brakes.
        # In that case, set preferred_velocity to (0, 0).
        # if braking_chance > 0 and random.random() < braking_chance:
        #     pass
        # else:

        # Calculate the preferred velocity, which consists of a weighted
        # sum of the desired velocity towards target and the average
        # velocity.
        actual_desired_velocity = max(0.0, self.desired_velocity + self.desired_velocity_offset)
        preferred_velocity = ((velocity_factor * actual_desired_velocity * desired_dir) +
                              (1 - velocity_factor) * average_velocity)

        attractive_force = (- self.mass * (self.velocity -
                            preferred_velocity) / self.relaxation_time)

        return attractive_force

    def calculate_pedestrian_repulsive_force(self, pedestrians):
        """ Calculates the repulsive force with all others pedestrians.

        Args:
            pedestrians: list of pedestrians in system.

        Returns:
            np.array: sum of repulsive forces from all other pedestrians.
        """

        world = self.group.world
        p_position = []
        p_velocity = []
        p_radius = []

        for p in pedestrians:
            if p == self:
                continue

            p_position.append(p.position)
            p_velocity.append(p.radius)
            p_radius.append(p.radius)

        if len(p_position) == 0:
            self.add_measurement('forces', 'local_density', 0.0)
            self.add_measurement('forces', 'local_velocity_variance', 0.0)
            self.add_measurement('forces', 'repulsive_force', 0.0)
            self.add_measurement('forces', 'pushing_force', 0.0)
            return np.array([0.0, 0.0]), np.array([0.0, 0.0])

        force_args = []
        # force_args.append(world.turbulence_max_repulsion)
        force_args.append(self.max_repulsive_force)
        force_args.append(world.turbulence_lambda)
        force_args.append(world.turbulence_d0)
        force_args.append(world.turbulence_d1)
        force_args.append(float(world.body_force_constant))
        force_args.append(float(world.friction_force_constant))

        smoothing_squared = world.smoothing_parameter**2
        smoothing_factor = 1.0 / (np.pi * smoothing_squared)
        force_args.append(smoothing_squared)
        force_args.append(smoothing_factor)

        labda_factor = 1.0
        if self.group.world.scale_lambda:
            velocity_x_component = np.dot(
                np.dot(self.velocity, self.desired_direction) / np.dot(self.desired_direction, self.desired_direction),
                self.desired_direction
            )[0]

            labda_factor = min(1.0, max(0.0, velocity_x_component / self.desired_velocity))

        force = calculate_pedestrian_repulsive_force(
            world.interactive_distance_threshold, self.position, self.velocity,
            self.radius, self.speed, labda_factor, p_position, p_velocity, p_radius,
            world.height, world.width, world.continuous_domain,
            world.ignore_pedestrians_behind, self.desired_direction,
            force_args, world.turbulence_exponent)

        # print(force)
        self.add_measurement('forces', 'local_density', force[4])
        self.add_measurement('forces', 'local_velocity_variance',
                             force[5])
        self.add_measurement('forces', 'repulsive_force', force[6])
        self.add_measurement('forces', 'pushing_force', force[7])

        return np.array([force[0], force[1]]), np.array([force[2], force[3]])

    def calculate_pedestrian_repulsive_force_old(self, pedestrians):
        """ Calculates the repulsive force with all others pedestrians.
        This function is deprecated.

        Args:
            pedestrians: list of pedestrians in system.

        Returns:
            np.array: sum of repulsive forces from all other pedestrians.
        """
        world = self.group.world

        # The following parameters were inspired by the Java SFM implementation
        repulsion_coefficient = world.repulsion_coefficient
        falloff_length = world.falloff_length
        body_force_constant = world.body_force_constant
        friction_force_constant = world.friction_force_constant

        distance_threshold = self.group.world.interactive_distance_threshold
        neighbourhood_distances = []
        pushing_forces = []
        friction_forces = []

        force = np.zeros(2)
        local_density = 0.0
        local_velocity_variance = 0.0

        # Loop through all pedestrians.
        for p in pedestrians:
            # Skip if self.
            if p == self:
                continue

            p_position = np.array(p.position)

            # Calculate the distance.
            position = self.position
            difference = p_position - position

            # In case of a continuous domain, we should check if the 'wrapped'
            # distance is closer.
            if self.group.world.continuous_domain:
                if difference[0] > 0.5 * self.group.world.width:
                    difference[0] = difference[0] - self.group.world.width
                    p_position[0] -= self.group.world.width
                elif difference[0] < - 0.5 * self.group.world.width:
                    difference[0] = difference[0] + self.group.world.width
                    p_position[0] += self.group.world.width

                if difference[1] > 0.5 * self.group.world.height:
                    difference[1] = difference[1] - self.group.world.height
                    p_position[1] -= self.group.world.height
                elif difference[1] < - 0.5 * self.group.world.height:
                    difference[1] = difference[1] + self.group.world.height
                    p_position[1] += self.group.world.height

            distance_squared = difference[0]**2 + difference[1]**2

            # Skip if the pedestrian is too far away. This saves a significant
            # amount of time in large groups.
            if distance_squared > distance_threshold:
                continue

            # In some cases, we want to ignore pedestrians that are 'behind' us
            if self.group.world.ignore_pedestrians_behind:
                # Calculate how far 'behind' the person is.
                desired_dir = self.desired_direction
                front_factor = (desired_dir[0] * difference[0] +
                                desired_dir[1] * difference[1])
                # print "{} -- {}: {}".format(self.id, p.id, front_factor)
                # Check if the distance exceeds the sum of radi.
                if front_factor < - self.radius - p.radius:
                    continue

            distance = np.sqrt(distance_squared)
            neighbourhood_distances.append(distance)

            # Agent overlap is positive if two agents 'overlap' in space.
            agent_overlap = self.radius + p.radius - distance

            # Unit vector of the difference
            difference_direction = difference / distance

            # Find normal and tangential of difference
            normal = (position - p_position) / distance
            # normal[1] = -normal[1]
            tangential = np.array([-normal[1], normal[0]])

            # Method 1: Original
            #####################
            if not world.turbulence:
                social_repulsion_force = repulsion_coefficient * np.exp(
                    agent_overlap / falloff_length)

            # Method 2: Turbulent force
            ############################
            else:
                max_repulsive_force = world.turbulence_max_repulsion
                labda = world.turbulence_lambda
                k = world.turbulence_exponent
                D_zero = world.turbulence_d0
                D_one = world.turbulence_d1

                try:
                    factor = max(distance, 0.15)
                    cos_angle = self.desired_direction * difference_direction
                    omega = labda + (1 - labda) * (1 + cos_angle) / 2
                    social_repulsion_force = (max_repulsive_force * omega *
                                              np.exp(- factor / D_zero +
                                                     (D_one / factor)**k))
                except:
                    print(distance, cos_angle, omega)
                    raise

            pushing_force = 0
            friction_force = np.array([0, 0])

            if agent_overlap > 0:
                # Find delta, which is a factor for friction force.
                delta = (p.velocity - self.velocity) * tangential

                pushing_force = body_force_constant * agent_overlap
                friction_force = (friction_force_constant * agent_overlap *
                                  delta * tangential)

            # Sum the forces and add to total force.
            pedestrian_force = ((social_repulsion_force + pushing_force) *
                                normal + friction_force)

            pushing_forces.append(pushing_force)
            friction_forces.append(np.sqrt(friction_force[0]**2 +
                                   friction_force[1]**2))

            force += pedestrian_force
            pressure = smoothing_factor * np.exp(-distance_squared /
                                                 smoothing_squared)

            local_density += pressure
            local_velocity_variance += self.speed * pressure

        if local_density != 0:
            local_velocity_variance /= local_density

        # self.add_measurement('neighbourhood', 'distances',
        #                      neighbourhood_distances)
        # self.add_measurement('neighbourhood', 'num_neighbours',
        #                      len(neighbourhood_distances))
        # self.add_measurement('forces', 'pushing', pushing_forces)
        # self.add_measurement('forces', 'friction', friction_forces)
        self.add_measurement('forces', 'local_density', local_density)
        self.add_measurement('forces', 'local_velocity_variance',
                             local_velocity_variance)

        return force

    def calculate_obstacle_repulsive_force(self, obstacles):
        """ Calculates the repulsive force with the closest obstacle.

        Args:
            obstacles: list of obstacles in the system.

        Returns:
            np.array: repulsive force from closest obstacle.
        """

        # The following parameters were inspired by the Java SFM implementation
        world = self.group.world
        repulsion_coefficient = world.repulsion_coefficient
        falloff_length = world.falloff_length
        body_force_constant = world.body_force_constant
        friction_force_constant = world.friction_force_constant
        desired_dir = self.get_desired_direction()

        self.closest_obstacle_points = []

        distance_threshold = 2.0

        force = np.zeros(2)

        # Loop through all obstacles.
        for o in obstacles:

            # Calculate the distance.
            position = self.position
            obstacle_position, normal = o.closest_point(self.position,
                                                        distance_threshold)
            if obstacle_position is None:
                continue

            self.closest_obstacle_points.append(obstacle_position)

            difference = obstacle_position - position

            distance = np.sqrt(difference[0]**2 + difference[1]**2)

            # Agent overlap is positive if two agents 'overlap' in space.
            agent_overlap = self.radius - distance

            # Unit vector of the difference
            difference_direction = difference / distance

            # Find tangential
            tangential = np.array([-normal[1], normal[0]])

            # Get angle
            # cos_angle = desired_dir * difference_direction
            # omega = world.turbulence_lambda + (1 - world.turbulence_lambda) * (1 + cos_angle) / 2
            # obstacle_repulsion_force = repulsion_coefficient * omega * np.exp(
            #     agent_overlap / falloff_length)
            obstacle_repulsion_force = repulsion_coefficient * np.exp(
                agent_overlap / falloff_length)

            pushing_force = 0
            friction_force = 0

            if agent_overlap > 0:
                # Find delta, which is a factor for friction force.
                delta = self.velocity * tangential

                pushing_force = body_force_constant * agent_overlap
                friction_force = (friction_force_constant * agent_overlap *
                                  delta * tangential)

            # Sum the forces and add to total force.
            obstacle_force = ((obstacle_repulsion_force + pushing_force) *
                              normal + friction_force)

            force += obstacle_force

        return force

    def plot(self, ax, color, add_quiver=False, plot_target=False):
        """ Plot this pedestrian on a figure.

        Args:
            ax: the pyplot axis on which to draw the pedestrian
            add_quiver: whether to add a quiver or not
            kwargs: pyplot keyword arguments
        """

        # red_blue = cm = plt.get_cmap('RdBu')
        # c_norm = matplotlib.colors.SymLogNorm(linthresh=0.03, linscale=0.03,
        #                                       vmin=-1.0, vmax=1.0)
        # scalarmap = matplotlib.cm.ScalarMappable(norm=c_norm, cmap=red_blue)
        # core_color = scalarmap.to_rgba(self.speed - self.desired_velocity)

        c = 'white'
        # if self.speed < 0.2:
        #     c = 'red'

        ax.add_artist(Circle(xy=(self.position), radius=0.5 * self.diameter,
                             facecolor=c, edgecolor=color, fill=True))

        mirrorred_positions = []

        if self.position[0] < self.radius:
            mirrorred_positions.append(self.position + np.array([self.group.world.width, 0]))
        if self.position[0] > self.group.world.width - self.radius:
            mirrorred_positions.append(self.position - np.array([self.group.world.width, 0]))

        for position in mirrorred_positions:
            ax.add_artist(Circle(xy=position, radius=0.5 * self.diameter,
                                 facecolor=c, edgecolor=color, fill=True))

        if add_quiver:
            ax.quiver(self.position[0], self.position[1],
                      self.velocity[0], self.velocity[1], angles='xy',
                      scale_units='xy', color=color)
        if plot_target:
            target = self.target
            if isinstance(target, Area):
                target = target.get_closest_point(self.position)
            ax.scatter(target[0], target[1])
            ax.plot([self.position[0], target[0]], [self.position[1], target[1]], alpha=0.3)
            for o in self.closest_obstacle_points:
                ax.plot([self.position[0], o[0]], [self.position[1], o[1]])


from django.urls import path
from direct_messages import views

url_patterns = [
    path('messages/<str:username>/',
         views.MessagesView.as_view(), name="direct_messages"),
    path('messages/', views.AllMessages.as_view(), name="all_messages")

]


import os
import sys

import setuptools

NAME = 'pyoslog'

about = {}
working_directory = os.path.join(os.path.abspath(os.path.dirname(__file__)), NAME)
with open(os.path.join(working_directory, '__version__.py')) as version_file:
    exec(version_file.read(), about)

with open('README.md') as readme_file:
    readme = readme_file.read()

# see compatibility.py - allow installation on older versions (or other OSs) but provide is_supported() at runtime
compatibility_module_name = 'compatibility'
compatibility_module_path = os.path.join(working_directory, '%s.py' % compatibility_module_name)
is_old_python_version = sys.version_info < (3, 5,)
try:
    # noinspection PyUnresolvedReferences
    import importlib.util

    if is_old_python_version:  # importlib.util.module_from_spec wasn't always present
        raise ImportError('importlib.util.module_from_spec is not available')
    spec = importlib.util.spec_from_file_location(compatibility_module_name, compatibility_module_path)
    compatibility = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(compatibility)
except ImportError:
    import imp

    compatibility = imp.load_source(compatibility_module_name, compatibility_module_path)

ext_modules = []
# noinspection PyUnresolvedReferences
if compatibility.is_supported():
    ext_modules.append(setuptools.Extension('_' + NAME, ['%s/_%s.c' % (NAME, NAME)]))

# https://setuptools.pypa.io/en/latest/references/keywords.html or https://docs.python.org/3/distutils/apiref.html
setuptools.setup(
    name=NAME,
    version=about['__version__'],
    description=about['__description__'],
    long_description=readme,
    long_description_content_type='text/markdown',
    author=about['__author__'],
    author_email=about['__author_email__'],
    url=about['__url__'],
    project_urls={
        'Documentation': 'https://pyoslog.readthedocs.io/',
        'Bug Tracker': '%s/issues' % about['__url__'],
        'Source Code': about['__url__'],
    },

    platforms=['darwin'],
    packages=[NAME],
    ext_modules=ext_modules,

    # could do, e.g., 'typing;python_version<"3.5"' but some old versions don't support that syntax...
    install_requires=['typing'] if is_old_python_version else [],

    package_data={'': ['LICENSE']},
    include_package_data=True,

    license=about['__license__'],
    classifiers=[
        'Operating System :: MacOS',
        'Programming Language :: Python',
        'Programming Language :: C',
        'Topic :: Software Development',
        'Topic :: System :: Logging',
        'Typing :: Typed',
        'Intended Audience :: Developers',
        'Development Status :: 5 - Production/Stable',
        'License :: OSI Approved :: Apache Software License'
    ]
)


from datetime import datetime
from django import template

register = template.Library()

@register.filter
def ts_to_date(value):
    try:
        ttd = datetime.fromtimestamp(int(value))
    except:
        ttd = value
    return ttd

@register.filter
def wei_to_eth(value):
    try:
        wei_to_eth = int(value) / 1000000000000000000
    except:
        wei_to_eth = value
    return wei_to_eth


from flask import Flask, render_template,request,jsonify
from pymongo import MongoClient
import os
import json
from flask_restplus import reqparse

app = Flask (__name__)
client = MongoClient('localhost', 27017)
db = client['F22Labs']
app = Flask(__name__)

datas=[]
filters=['Season','Episode','Gender','Investor']
dic={}
parser = reqparse.RequestParser()
@app.route("/")
def index():
    data=db.data.find()
    for x in data:
        j=list(x.items())
        datas.append([j[1][1],j[2][1],j[3][1],j[4][1],j[5][1],j[6][1]])
    return render_template('index.html', data=datas)
@app.route("/company/",methods=['GET'])
def company():
    x=request.args.get('compname')
    print(type(x))
    DIR = './static/Data'
    dispdata=[]
    scount=(len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))]))
    for s in range(1,scount+1):
        season="season"+str(s)
        seasonfile=season+".json"
        with open(DIR+'/'+seasonfile,encoding="utf-8") as data:
            jsondata=data.read()
            datas=json.loads(jsondata)
            episodes=len(datas)
            for i in range(1,episodes+1):
                epname="Episode "+str(i)
                companies=len(datas[epname])
                for j in range(companies):
                    company=datas[epname][j]
                    companyname=company['company']['title']
                    try:
                        links=company['company']['link']
                    except:
                        links=""
                    status=company['status']
                    investment=company['kitna']
                    socialmedia=company['social']
                    product=company['product']

                    if(x==companyname):
                        dispdata.append([season,epname,companyname,links,socialmedia,product,company['investors'],investment,status])
                        print(x)
                        print("this works")
    print(dispdata)
    return render_template('Company.html', data=dispdata)

@app.route("/filter/",methods=['GET'])
def filter():
    command=None
    for i in filters:
        x=parser.add_argument(i, action='append')
        x=dict(parser.parse_args())
    for i in x:
        c=x.get(i)
        if(c!=None):
            dic[i]=c
    print(dic)
    datas=[]
    if(dic!={}):
        length=len(dic)
        print(length)
        if(length<2):
            command="{'$or':["
            for i in dic:
                sublength=len(dic.get(i))
                for j in range(sublength):
                    command=command+"{"+(dic.get(i)[j])+"},"
            command=command+"]}"
            print(command)
            data=db.data.find(eval(command))
            for x in data:
                j=list(x.items())
                datas.append([j[1][1],j[2][1],j[3][1],j[4][1],j[5][1],j[6][1]])
        else:
            sub=[]
            command="{'$and':["

            for i in dic:
                subcommand="{'$or':["
                sublength=len(dic.get(i))
                for j in range(sublength):
                    subcommand=subcommand+"{"+(dic.get(i)[j])+"},"
                subcommand=subcommand+"]}"
                sub.append(subcommand)

            for i in range(len(sub)):
                command=command+sub[i]+','
            command=command+"]}"
            print(command)
            data=db.data.find(eval(command))
            for x in data:
                j=list(x.items())
                datas.append([j[1][1],j[2][1],j[3][1],j[4][1],j[5][1],j[6][1]])

    return render_template('index.html', data=datas)
if __name__ == "__main__":
    app.run(debug=True)


"""Media Player platform for eversolo."""
from __future__ import annotations

import datetime as dt

from homeassistant.components.media_player import (
    MediaPlayerDeviceClass,
    MediaPlayerEntity,
    MediaPlayerEntityFeature,
    MediaPlayerState,
)

from .const import DOMAIN, LOGGER
from .coordinator import EversoloDataUpdateCoordinator
from .entity import EversoloEntity

SUPPORT_FEATURES = (
    MediaPlayerEntityFeature.TURN_OFF
    | MediaPlayerEntityFeature.SELECT_SOURCE
    | MediaPlayerEntityFeature.PLAY
    | MediaPlayerEntityFeature.PAUSE
    | MediaPlayerEntityFeature.VOLUME_SET
    | MediaPlayerEntityFeature.VOLUME_MUTE
    | MediaPlayerEntityFeature.VOLUME_STEP
    | MediaPlayerEntityFeature.PREVIOUS_TRACK
    | MediaPlayerEntityFeature.NEXT_TRACK
    | MediaPlayerEntityFeature.SEEK
)

async def async_setup_entry(hass, entry, async_add_devices):
    """Set up the Media Player platform."""
    coordinator = hass.data[DOMAIN][entry.entry_id]

    async_add_devices([EversoloMediaPlayer(coordinator, entry)])

class EversoloMediaPlayer(EversoloEntity, MediaPlayerEntity):
    """Eversolo Media Player."""

    def __init__(self, coordinator: EversoloDataUpdateCoordinator, config_entry):
        """Initialize the Media Player."""
        super().__init__(coordinator)
        self._attr_device_class = MediaPlayerDeviceClass.RECEIVER
        self._attr_supported_features = SUPPORT_FEATURES
        self._attr_unique_id = f"{coordinator.config_entry.entry_id}_media_player"
        self._config_entry = config_entry
        self._name = "Eversolo"
        self._state = None

    @property
    def name(self):
        """Return name."""
        return self._name

    @property
    def state(self):
        """Return Media Player state."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            self._state = None
            return self._state

        state = int(music_control_state.get("state", -1))

        if state == 0:
            self._state = MediaPlayerState.IDLE
        elif state == 3:
            self._state = MediaPlayerState.PLAYING
            self._attr_media_position_updated_at = dt.datetime.now()
        elif state == 4:
            self._state = MediaPlayerState.PAUSED
        else:
            LOGGER.debug("Unknown state: %s", state)
            self._state = None

        return self._state

    @property
    def device_info(self):
        """Return Media Player device info."""
        return {}

    @property
    def volume_level(self):
        """Volume level of the Media Player in range 0..1."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        current_volume = music_control_state.get("volumeData", {}).get(
            "currenttVolume", None
        )
        max_volume = music_control_state.get("volumeData", {}).get("maxVolume", None)

        if current_volume is None or max_volume is None:
            LOGGER.debug(
                "Current volume or max volume invalid in music control state: %s",
                music_control_state,
            )
            return None

        return float(current_volume) / float(max_volume)

    @property
    def is_volume_muted(self):
        """Return muted state."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        return music_control_state.get("volumeData", {}).get("isMute", None)

    @property
    def source(self):
        """Return the current input source."""
        input_output_state = self.coordinator.data.get("input_output_state", None)

        if input_output_state is None:
            return None

        sources = self.coordinator.data.get("input_output_state", {}).get(
            "transformed_sources", None
        )

        if sources is None:
            return None

        input_index = input_output_state.get("inputIndex", -1)
        if input_index < 0 or input_index >= len(sources):
            LOGGER.debug("Input index %s is out of range", input_index)
            return None

        return list(sources.values())[input_index]

    @property
    def source_list(self):
        """List of available input sources."""
        # NoneType object has no values
        sources = self.coordinator.data.get("input_output_state", {}).get(
            "transformed_sources", None
        )

        if sources is None:
            return None

        return list(sources.values())

    @property
    def media_title(self):
        """Title of current playing media."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        play_type = music_control_state.get("playType", None)

        # Bluetooth or Spotify Connect
        if play_type == 4 or play_type == 6:
            return (
                music_control_state.get("everSoloPlayInfo", {})
                .get("everSoloPlayAudioInfo", {})
                .get("songName", None)
            )

        # Internal Player
        if play_type == 5:
            return music_control_state.get("playingMusic", {}).get("title", None)

        return None

    @property
    def media_artist(self):
        """Artist of current playing media."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        play_type = music_control_state.get("playType", None)

        # Bluetooth or Spotify Connect
        if play_type == 4 or play_type == 6:
            return (
                music_control_state.get("everSoloPlayInfo", {})
                .get("everSoloPlayAudioInfo", {})
                .get("artistName", None)
            )

        # Internal Player
        if play_type == 5:
            return music_control_state.get("playingMusic", {}).get("artist", None)

        return None

    @property
    def media_album_name(self):
        """Album of current playing media."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        play_type = music_control_state.get("playType", None)

        # Bluetooth or Spotify Connect
        if play_type == 4 or play_type == 6:
            return (
                music_control_state.get("everSoloPlayInfo", {})
                .get("everSoloPlayAudioInfo", {})
                .get("albumName", None)
            )

        # Internal Player
        if play_type == 5:
            return music_control_state.get("playingMusic", {}).get("album", None)

        return None

    @property
    def media_image_url(self):
        """Image url of current playing media."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        play_type = music_control_state.get("playType", None)

        # Bluetooth or Spotify Connect
        if play_type == 6:
            album_url = music_control_state.get("everSoloPlayInfo", {}).get(
                "icon", None
            )

            if album_url is None or album_url == "":
                return None

            if not album_url.startswith("http"):
                album_url = self.coordinator.client.create_image_url_by_path(album_url)

            return album_url

        # Internal Player
        if play_type == 5:
            song_id = music_control_state.get("playingMusic", {}).get("id", None)
            if song_id is not None:
                return self.coordinator.client.create_image_url_by_song_id(song_id)

        return None

    @property
    def media_duration(self):
        """Duration of current playing media in seconds."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        duration = music_control_state.get("duration", None)

        if duration is None or duration == 0:
            return None

        return duration / 1000

    @property
    def media_position(self):
        """Position of current playing media in seconds."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return None

        position = music_control_state.get("position", None)

        if position is None or position == 0:
            return None

        return position / 1000

    async def async_media_seek(self, position: float):
        """Seek the media to a specific location."""
        await self.coordinator.client.async_seek_time(round(position * 1000))
        await self.coordinator.async_request_refresh()

    async def async_turn_off(self):
        """Turn off Media Player."""
        await self.coordinator.client.async_trigger_power_off()
        await self.coordinator.async_request_refresh()

    async def async_set_volume_level(self, volume: float) -> None:
        """Set volume level, range 0..1."""
        music_control_state = self.coordinator.data.get("music_control_state", None)

        if music_control_state is None:
            return

        converted_volume = round(
            volume * int(music_control_state.get("volumeData", {}).get("maxVolume", 0))
        )
        await self.coordinator.client.async_set_volume(converted_volume)
        await self.coordinator.async_request_refresh()

    async def async_volume_up(self):
        """Volume up the Media Player."""
        await self.coordinator.client.async_volume_up()
        await self.coordinator.async_request_refresh()

    async def async_volume_down(self):
        """Volume down Media Player."""
        await self.coordinator.client.async_volume_down()
        await self.coordinator.async_request_refresh()

    async def async_mute_volume(self, mute):
        """Send mute command."""
        await self.coordinator.client.async_mute()
        await self.coordinator.async_request_refresh()

    async def async_select_source(self, source):
        """Set the input source."""
        sources = self.coordinator.data.get("input_output_state", {}).get(
            "transformed_sources", None
        )

        if sources is None:
            return

        try:
            index, tag = next(
                (index, key)
                for index, key in enumerate(sources)
                if sources[key] == source or key == source
            )
        except StopIteration:
            raise ValueError(f"Source {source} not found")

        await self.coordinator.client.async_set_input(index, tag)

    async def async_media_play_pause(self):
        """Simulate play pause Media Player."""
        await self.coordinator.client.async_toggle_play_pause()
        await self.coordinator.async_request_refresh()

    async def async_media_play(self):
        """Send play command."""
        if self._state is not MediaPlayerState.PLAYING:
            await self.coordinator.client.async_toggle_play_pause()
            await self.coordinator.async_request_refresh()

    async def async_media_pause(self):
        """Send pause command."""
        if self._state is MediaPlayerState.PLAYING:
            await self.coordinator.client.async_toggle_play_pause()
            await self.coordinator.async_request_refresh()

    async def async_media_next_track(self):
        """Send next track command."""
        await self.coordinator.client.async_next_title()
        await self.coordinator.async_request_refresh()

    async def async_media_previous_track(self):
        """Send the previous track command."""
        await self.coordinator.client.async_previous_title()
        await self.coordinator.async_request_refresh()