# Load the libraries

import pandas as pd
import calendar

def data_prep(df):

    df = df.fillna("NA")

    df["province"] = df["province"].str.upper().str.title()
    df["devicetype_en"] = df["devicetype_en"].str.upper().str.title()

    df_INC = df.copy()

    # Deriving new variable

    df_INC['discovery'] = pd.to_datetime(df_INC['discovery'], unit='s')
    df_INC['day'] = df_INC['discovery'].dt.day_name()
    df_INC['month'] = df_INC['discovery'].apply(lambda x: calendar.month_abbr[x.month])
    df_INC['BH'] = df_INC['discovery'].dt.time
    df_INC['date'] = df_INC['discovery'].dt.date

    # Binning device type_en

    list_1 = ['Router', 'Switch', 'Others']

    def binning_1(x):
        if x not in list_1:
            x = "Other 2"
        return x

    # Binning province

    df_INC['devicetype_en'] = df_INC['devicetype_en'].apply(binning_1)

    list_2 = ['Northwest Territories', 'Prince Edward Island', 'Yukon Territory', 'Nunavut']

    list_3 = ['New York', 'Florida', 'Virginia', 'California', 'Texas', 'Illinois', 'Pennsylvania',
            'Indiana', 'Massachusetts', 'Ohio', 'Wisconsin', 'Washington', 'New Jersey', 'North Carolina',
            'Colorado', 'Georgia', 'Nebraska', 'New Hampshire', 'Michigan', 'District of Columbia', 'Maryland',
            'Tennessee', 'Arizona', 'Delaware', 'Missouri', 'Oklahoma', 'South Carolina', 'Minnesota',
            'Arkansas', 'Hawaii', 'Connecticut', 'Alabama', 'Kansas', 'Maine', 'Rhode Island', 'Kentucky', 'Nevada',
            'Oregon', 'Alaska', 'Utah', 'South Dakota', 'Louisiana', 'Iowa', 'Idaho', 'West Virginia', 'Mississippi',
            'Wyoming','Na','State/Province not required','State/Province Not Required']

    def binning_2(x):
        if x in list_2:
            x = 'OtherCanada'
        if x in list_3:
            x = 'OtherUSA'
        if (x not in list_2) & (x not in list_3):
            x = 'OtherUSA'
        return x

    df_INC['province'] = df_INC['province'].apply(binning_2)

    df_INC['province'].fillna("OtherUSA", inplace=True)

    # Generating business hour and non BH variable

    def bh(x):
        y = str(x)
        y = y.split(':')
        y = float(".".join(y[:2]))
        z = 'NBH'
        if ((y > 8.30) & (y < 16.59)):
            z = 'BH'
        return z

    df_INC['BH'] = df_INC['BH'].apply(bh)

    # creating No of incidents in each group

    df_final = pd.DataFrame(
        {'No_of_incidents': df_INC.groupby(['date', 'month', 'day', 'BH', 'province', 'discovery source',
                                              'customerseverity', 'devicetype_en',
                                              'service name_en']).size()}).reset_index()
    return df_final


import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider, Button
from tqdm.auto import tqdm

from utils.algorithm_x import remove_intersections, algorithm_x_first_solution
from utils.sudoku_transcription import sudoku_matrix_representation

def binary_list_to_ids(binary_list):
    output = []
    for i, j in enumerate(binary_list):
        if j:
            output.append(i)
    return np.array(output)

def ids_to_binary_list(ids, length):
    output = np.zeros(length)
    for id in ids:
        output[id] = 1
    return output

def observe_number_of_possible_rows(numbers_of_rows, transcription_matrix):
    queue = numbers_of_rows.copy()
    np.random.shuffle(queue)

    t_matrix = transcription_matrix.copy()

    number_of_possibilities = []

    while queue.size > 0:
        size = t_matrix.shape[0]
        number_of_possibilities.append(size)
        chromosome = ids_to_binary_list(queue, size)

        t_matrix, chromosome = remove_intersections(t_matrix, chromosome, t_matrix, queue[0])

        queue = binary_list_to_ids(chromosome)

    return np.array(number_of_possibilities)

def cumulate_data(size_of_sample, size_of_sudoku, tqdm_mode=False):
    coordinates, transcription_matrix = sudoku_matrix_representation(np.zeros([size_of_sudoku, size_of_sudoku]))
    solution = np.array(algorithm_x_first_solution(transcription_matrix))
    temp = observe_number_of_possible_rows(solution, transcription_matrix)
    initial = temp[0]
    current_stage = np.empty(temp.shape[0])
    for k, value in enumerate(temp):
        current_stage[k] = value / (initial - k)
    number_of_possibilities = current_stage

    if tqdm_mode:
        this_range = tqdm(range(size_of_sample))
    else:
        this_range = range(size_of_sample)

    for i in this_range:
        solution = np.array(algorithm_x_first_solution(transcription_matrix))
        temp = observe_number_of_possible_rows(solution, transcription_matrix)
        initial = temp[0]
        data = np.empty(temp.shape[0])
        for k, value in enumerate(temp):
            data[k] = value / (initial - k)

        current_stage += data

        number_of_possibilities = np.vstack([number_of_possibilities, current_stage / (i + 2)])

    return number_of_possibilities

def distribution_of_final_fails(size):
    sol = []
    for k in range(size ** 2):
        sol.append((size ** 2 - k) / (5 / 8 * (size ** 3) - k))
    sol = np.array(sol)
    print(np.prod(1 / sol))
    plt.plot(np.linspace(0, 1, size ** 2), sol)
    plt.title("Probability of choosing a correct number")
    plt.xlabel('Percent of filling a sudoku')
    plt.ylabel('Probability')
    plt.show()

def slider_demo(size_of_sample, size_of_sudoku=9):
    number_of_possibilities = cumulate_data(size_of_sample, size_of_sudoku)
    f = lambda i: number_of_possibilities[int(i)]
    x = np.linspace(0, 1, number_of_possibilities.shape[1])
    t = np.arange(number_of_possibilities.shape[1])

    # Define initial parameters
    init = 1

    # Create the figure and the line that we will manipulate
    fig, ax = plt.subplots()
    line, = plt.plot(x, f(1), lw=2)
    ax.set_xlabel('Percent of filling a sudoku')
    ax.set_ylabel('Probability')

    axcolor = 'lightgoldenrodyellow'
    ax.margins(x=0)

    # adjust the main plot to make room for the sliders
    plt.subplots_adjust(left=0.25, bottom=0.25)

    # Make a horizontal slider to control the frequency.
    axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
    freq_slider = Slider(
        ax=axfreq,
        label='Size of sample',
        valmin=1,
        valmax=number_of_possibilities.shape[0] - 1,
        valinit=init,
        valfmt="%1i"
    )

    # The function to be called anytime a slider's value changes
    def update(val):
        line.set_ydata(f(freq_slider.val))
        fig.canvas.draw_idle()

    # register the update function with each slider
    freq_slider.on_changed(update)

    # Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
    resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')

    def reset(event):
        freq_slider.reset()

    button.on_clicked(reset)

    plt.show()


import pandas as pd
from typing import Dict, List, Set

from .core import (
    DownloadableFiles,
    get_clinical_downloadable_files,
    get_misc_data_files,
    get_trial_if_exists,
    get_shipments,
    Session,
    TrialMetadata,
    UploadJobs,
)

# copied from cidc_schemas.prism.constants
# Windows doesn't handle current jsonschemas RefResolver configuration
SUPPORTED_ANALYSES: List[str] = [
    "atacseq_analysis",
    "cytof_analysis",
    "rna_level1_analysis",
    "tcr_analysis",
    "wes_analysis",
    "wes_tumor_only_analysis",
]
SUPPORTED_ASSAYS: List[str] = [
    "atacseq_fastq",
    "wes_fastq",
    "wes_bam",
    "olink",
    "cytof",
    "ihc",
    "elisa",
    "rna_fastq",
    "rna_bam",
    "mif",
    "tcr_adaptive",
    "tcr_fastq",
    "hande",
    "nanostring",
    "clinical_data",
    "misc_data",
    "ctdna",
    "microbiome",
    "mibi",
]

SUPPORTED_ASSAYS_AND_ANALYSES: Set[str] = {
    # everything once, without file type specifiers
    a.split("_fastq")[0].split("_bam")[0].split("_adaptive")[0]
    for a in SUPPORTED_ASSAYS + SUPPORTED_ANALYSES
} | {"wes_analysis_old", "wes_tumor_only_analysis_old"}

pd.set_option("display.max_columns", None)
pd.set_option("display.max_colwidth", None)
pd.set_option("display.max_rows", None)

def _describe_olink(metadata_json: dict) -> pd.DataFrame:
    ret = pd.DataFrame(columns=["batch_id", "file", "cimac_id"])
    for batch in metadata_json.get("assays", {}).get("olink", {"batches": []})[
        "batches"
    ]:
        if "combined" not in batch:
            for record in batch["records"]:
                ret = ret.append(
                    pd.DataFrame(
                        [
                            {
                                "batch_id": batch["batch_id"],
                                "file": record["files"]["assay_npx"]["object_url"],
                                "cimac_id": sample,
                            }
                            for sample in record["files"]["assay_npx"]["samples"]
                        ]
                    )
                )
        else:
            ret = ret.append(
                pd.DataFrame(
                    [
                        {
                            "batch_id": batch["batch_id"],
                            "file": "combined",
                            "cimac_id": sample,
                        }
                        for sample in batch["combined"]["npx_file"]["samples"]
                    ]
                )
            )

    return ret.reset_index(drop=True)

def _describe_elisa(metadata_json: dict) -> pd.DataFrame:
    # elisa is special case
    ret = pd.DataFrame(columns=["assay_run_id", "cimac_id"])
    for batch in metadata_json.get("assays", {}).get("elisa", []):
        ret = ret.append(
            pd.DataFrame(
                [
                    {"cimac_id": sample, "assay_run_id": batch["assay_run_id"]}
                    for sample in batch["assay_xlsx"]["samples"]
                ]
            )
        )
    return ret.reset_index(drop=True)

def _describe_nanostring(metadata_json: dict) -> pd.DataFrame:
    # nanostring is special case
    ret = pd.DataFrame(columns=["batch_id", "run_id", "cimac_id"])
    for batch in metadata_json.get("assays", {}).get("nanostring", []):
        for run in batch["runs"]:
            ret = ret.append(
                pd.DataFrame(
                    [
                        {
                            "batch_id": batch["batch_id"],
                            "run_id": run["run_id"],
                            "cimac_id": sample["cimac_id"],
                        }
                        for sample in run["samples"]
                    ]
                )
            )
    return ret.reset_index(drop=True)

def _describe_rna_analysis(metadata_json: dict) -> pd.DataFrame:
    return pd.DataFrame(
        [
            {"cimac_id": record["cimac_id"]}
            for record in metadata_json.get("analysis", {}).get(
                "rna_analysis", {"level_1": []}
            )["level_1"]
        ]
    )

def _describe_cytof_analysis(
    metadata_json: dict,
) -> pd.DataFrame:
    ret = pd.DataFrame(columns=["batch_id", "cimac_id"])
    for batch in metadata_json.get("assays", {}).get("cytof", []):
        if "astrolabe_analysis" in batch:
            ret = ret.append(
                pd.DataFrame(
                    [
                        {
                            "batch_id": batch["batch_id"],
                            "cimac_id": record["cimac_id"],
                        }
                        for record in batch["records"]
                        if "output_files" in record
                    ]
                )
            )
    return ret.reset_index(drop=True)

def _describe_wes_analysis(metadata_json: dict, just_old: bool = False) -> pd.DataFrame:
    ret = pd.DataFrame(columns=["run_id", "tumor_cimac_id", "normal_cimac_id"])

    for subkey in ["wes_analysis", "wes_analysis_old"]:
        if just_old and "old" not in subkey:
            continue

        ret = ret.append(
            pd.DataFrame(
                [
                    {
                        "run_id": run["run_id"],
                        "tumor_cimac_id": run["tumor"]["cimac_id"],
                        "normal_cimac_id": run["normal"]["cimac_id"],
                    }
                    for run in metadata_json.get("analysis", {}).get(
                        subkey, {"pair_runs": []}
                    )["pair_runs"]
                ]
            )
        )
    return ret.reset_index(drop=True)

def _describe_wes_tumor_only_analysis(
    metadata_json: dict, just_old: bool = False
) -> pd.DataFrame:
    ret = pd.DataFrame(columns=["cimac_id"])

    for subkey in ["wes_tumor_only_analysis", "wes_tumor_only_analysis_old"]:
        if just_old and "old" not in subkey:
            continue

        ret = ret.append(
            pd.DataFrame(
                [
                    {"cimac_id": run["tumor"]["cimac_id"]}
                    for run in metadata_json.get("analysis", {}).get(
                        subkey, {"runs": []}
                    )["runs"]
                ]
            )
        )
    return ret.reset_index(drop=True)

def _describe_batched(metadata_json: dict, assay_or_analysis: str) -> pd.DataFrame:
    ret = pd.DataFrame(columns=["batch_id", "cimac_id"])
    for batch in metadata_json.get(
        "analysis" if "analysis" in assay_or_analysis else "assays", {}
    ).get(assay_or_analysis, {"batches": []})["batches"]:
        ret = ret.append(
            pd.DataFrame(
                [
                    {
                        "batch_id": batch["batch_id"],
                        "cimac_id": record["cimac_id"],
                    }
                    for record in batch["records"]
                ]
            )
        )
    return ret.reset_index(drop=True)

def _describe_generic(metadata_json: dict, assay_or_analysis: str) -> pd.DataFrame:
    ret = pd.DataFrame(columns=["batch_id", "cimac_id"])
    for batch_num, batch in enumerate(
        metadata_json.get(
            "analysis" if "analysis" in assay_or_analysis else "assays", {}
        ).get(assay_or_analysis, [])
    ):
        ret = ret.append(
            pd.DataFrame(
                [
                    {
                        "batch_id": batch.get("batch_id", str(batch_num)),
                        "cimac_id": record["cimac_id"],
                    }
                    for record in batch["records"]
                ]
            )
        )
    return ret.reset_index(drop=True)

def list_data_cimac_ids(trial_id: str, assay_or_analysis: str) -> None:
    """
    Prints a table listing all samples for the given assay/analysis and trial

    Parameters
    ----------
    trial_id: str
        the id of the trial to investigate
    assay_or_analysis: str
        the name of the assay / analysis to investigate
        must be in SUPPORTED_ASSAYS_AND_ANALYSES
    """
    if assay_or_analysis not in SUPPORTED_ASSAYS_AND_ANALYSES:
        print("Assay / analysis not supported:", assay_or_analysis)
        return

    elif assay_or_analysis == "clinical_data":
        list_clinical(trial_id)
        return
    elif assay_or_analysis == "misc_data":
        list_misc_data(trial_id)
        return

    with Session.begin() as session:
        trial: TrialMetadata = get_trial_if_exists(trial_id, session=session)
        cimac_ids: pd.DataFrame

        if assay_or_analysis == "olink":
            cimac_ids: pd.DataFrame = _describe_olink(metadata_json=trial.metadata_json)
        elif assay_or_analysis == "elisa":
            cimac_ids: pd.DataFrame = _describe_elisa(metadata_json=trial.metadata_json)
        elif assay_or_analysis == "nanostring":
            cimac_ids: pd.DataFrame = _describe_nanostring(
                metadata_json=trial.metadata_json
            )

        elif assay_or_analysis == "rna_level1_analysis":
            cimac_ids: pd.DataFrame = _describe_rna_analysis(
                metadata_json=trial.metadata_json
            )

        elif assay_or_analysis == "cytof_analysis":
            cimac_ids: pd.DataFrame = _describe_cytof_analysis(
                metadata_json=trial.metadata_json
            )

        elif assay_or_analysis in ["wes_analysis", "wes_analysis_old"]:
            cimac_ids: pd.DataFrame = _describe_wes_analysis(
                metadata_json=trial.metadata_json,
                just_old="old" in assay_or_analysis,
            )

        elif assay_or_analysis in [
            "wes_tumor_only_analysis",
            "wes_tumor_only_analysis_old",
        ]:
            cimac_ids: pd.DataFrame = _describe_wes_tumor_only_analysis(
                metadata_json=trial.metadata_json,
                just_old="old" in assay_or_analysis,
            )

        elif assay_or_analysis in [
            "mibi",
            "tcr_analysis",
        ]:
            cimac_ids: pd.DataFrame = _describe_batched(
                metadata_json=trial.metadata_json, assay_or_analysis=assay_or_analysis
            )

        else:
            cimac_ids: pd.DataFrame = _describe_generic(
                metadata_json=trial.metadata_json, assay_or_analysis=assay_or_analysis
            )

        # business print
        print(cimac_ids)

def list_clinical(trial_id: str) -> None:
    """
    Prints a table describing all clinical files for the given trial

    Parameters
    ----------
    trial_id: str
        the id of the trial to investigate
    """
    with Session.begin() as session:
        trial: TrialMetadata = get_trial_if_exists(trial_id, session=session)
        clinical_files: List[DownloadableFiles] = get_clinical_downloadable_files(
            trial_id, session=session
        )

        number_of_participants: Dict[str, int] = dict()
        comments: Dict[str, str] = dict()
        for record in trial.metadata_json.get("clinical_data", {}).get("records", []):
            object_url: str = record["clinical_file"]["object_url"]
            number_of_participants[object_url] = record["clinical_file"][
                "number_of_participants"
            ]
            if "comment" in record:
                comments[object_url] = record["comment"]

        print(
            pd.DataFrame(
                {
                    "object_url": f.object_url,
                    "filename": f.object_url.split("/clinical/")[1],
                    "num_participants": number_of_participants.get(f.object_url),
                    "created": f._created,
                    "comment": comments.get(f.object_url, pd.NA),
                }
                for f in clinical_files
            )
        )

def list_misc_data(trial_id: str) -> None:
    """
    Prints a table describing all misc_data files for the given trial

    Parameters
    ----------
    trial_id: str
        the id of the trial to investigate
    """
    with Session.begin() as session:
        trial: TrialMetadata = get_trial_if_exists(trial_id, session=session)
        misc_data_files: List[DownloadableFiles] = get_misc_data_files(
            trial_id, session=session
        )

        descriptions: Dict[str, str] = dict()
        batch_numbers: Dict[str, int] = dict()
        for batch_idx, batch in enumerate(
            trial.metadata_json.get("assays", {}).get("misc_data", [])
        ):
            for file in batch["files"]:
                object_url = file["file"]["object_url"]
                batch_numbers[object_url] = batch_idx

                if "description" in file:
                    descriptions[object_url] = file["description"]

        print(
            pd.DataFrame(
                {
                    "batch_id": batch_numbers.get(f.object_url, pd.NA),
                    "object_url": f.object_url,
                    "filename": f.object_url.split("/misc_data/")[1],
                    "created": f._created,
                    "description": descriptions.get(f.object_url, pd.NA),
                }
                for f in misc_data_files
            )
        )

def list_shipments(trial_id: str) -> None:
    """
    Prints a table describing all shipments for the given trial

    Parameters
    ----------
    trial_id: str
        the id of the trial to investigate
    """
    with Session.begin() as session:
        shipments: List[UploadJobs] = get_shipments(trial_id, session=session)
        print(
            pd.DataFrame(
                {
                    "upload_type": u.upload_type,
                    "manifest_id": u.metadata_patch["shipments"][0]["manifest_id"],
                    "num_samples": sum(
                        len(p["samples"]) for p in u.metadata_patch["participants"]
                    ),
                    "created": u._created,
                }
                for u in shipments
            )
        )


from django.http import HttpResponseServerError
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import serializers, status
from rareapi.models import Author, Comment, Post

class CommentView(ViewSet):
    def list(self, request):

        comments = Comment.objects.all()

        if "post_id" in request.query_params:
            post = Post.objects.get(pk=request.query_params["post_id"])
            comments = comments.filter(post=post)

        for comment in comments:
            comment.is_author = False
            if comment.author.user == request.auth.user:
                comment.is_author = True

        serialized = CommentSerializer(comments, many=True)
        return Response(serialized.data, status=status.HTTP_200_OK)

class CommentAuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ('id', 'username', 'profile_image_url')

class CommentSerializer(serializers.ModelSerializer):
    author = CommentAuthorSerializer(many=False)

    class Meta:
        model = Comment
        fields = ('id', 'author', 'body', 'post', 'date', 'is_author')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 15 14:01:33 2022

@author: gunnarfranko
"""

import pandas as pd

data1 = pd.read_csv('https://raw.githubusercontent.com/UVADS/orientation-technical/main/dat/2022-06-14-survey.csv')

data1 = data1[data1['Hard Drive Size (in GB)'] < 800]
import matplotlib.pyplot as plt

plt.hist(data1['Hard Drive Size (in GB)'], color='Orange')

plt.title('Hard Drive Size (in GB)')
plt.xlabel('Hard Drive Size')
plt.ylabel('Frequency')

print('hello world')
import matplotlib.pyplot as plt
import pandas as pd

data = pd.read_csv(r"C:\Users\kimbrelljm17\OneDrive - Grove City College\Documents\UVA\Orientation\2021-06-15-survey.csv")
data.hist()

plt.show()


from models.model import *
from utils.examen_fisico.schema_respiratorio import *
from flask import  jsonify, request, Blueprint

respiratorio_blueprint = Blueprint('respiratorio',__name__)

@respiratorio_blueprint.route('/respiratorio',methods=['POST'])
def crear_respiratorio():
    try:
        inspeccion = request.json['inspeccion']
        palpacion = request.json['palpacion']
        percusion = request.json['percusion']
        auscultacion = request.json['auscultacion']
        examen_fisico_id = request.json['examen_fisico_id']

        nuevo_respiratorio = Respiratorio(inspeccion=inspeccion,palpacion=palpacion,percusion=percusion,
        auscultacion=auscultacion,estado=True,examen_fisico_id=examen_fisico_id)

        db.session.add(nuevo_respiratorio)
        db.session.commit()

        return respiratorio_schema.jsonify(nuevo_respiratorio)
    except Exception as e:

        return jsonify({'Error':e})

@respiratorio_blueprint.route('/respiratorio',methods=['GET'])
def obtener_respiratorios():
    respiratorio = Respiratorio.query.filter_by(estado=True)
    resultado = respiratorio_schemas.dump(respiratorio)
    return jsonify(resultado)

@respiratorio_blueprint.route('/respiratorio/<int:id>', methods=['GET'])
def obtener_respiratorio(id):
    respiratorio = Respiratorio.query.get_or_404(int(id))
    if(respiratorio.estado != False):
        return respiratorio_schema.jsonify(respiratorio)
    else:
        return "
No existe el examen de respiratorio.
"

@respiratorio_blueprint.route('/respiratorio/<int:id>', methods=['PUT'])
def actualizar_respiratorio(id):
    respiratorio = Respiratorio.query.get_or_404(int(id))

    inspeccion = request.json['inspeccion']
    palpacion = request.json['palpacion']
    percusion = request.json['percusion']
    auscultacion = request.json['auscultacion']

    respiratorio.inspeccion=inspeccion
    respiratorio.palpacion=palpacion
    respiratorio.percusion=percusion
    respiratorio.auscultacion=auscultacion

    db.session.commit()

    return respiratorio_schema.jsonify(respiratorio)

@respiratorio_blueprint.route('/respiratorio/<int:id>', methods=['DELETE'])
def eliminar_respiratorio(id):
    respiratorio = Respiratorio.query.get_or_404(int(id))

    estado = False
    respiratorio.estado = estado
    db.session.commit()

    return respiratorio_schema.jsonify(respiratorio)


import boto3
from botocore.exceptions import ClientError

def grant_lex_lambda_permissions(client, function_name):
    try:
        response = client.add_permission(
            Action='lambda:InvokeFunction',
            FunctionName=function_name,
            Principal='lex.amazonaws.com',
            StatementId='ID-1'
        )
    except ClientError as e:
        pass

def create_bot_if_not_exists(client, bot_name, alias, intent_names, locale='en-US', child_directed=False):
    intents = []
    for intent_name in intent_names:
        intents.append({
            'intentName': intent_name,
            'intentVersion': '$LATEST'
        })

    chatbot = get_bot_by_name_and_alias(client, bot_name, alias)
    if chatbot is None:
        chatbot = client.put_bot(
            name=bot_name,
            locale=locale,
            childDirected=child_directed,
            intents=intents,
            abortStatement={
                'messages': [
                    build_message_dict("Sorry I can't fulfill your request.")
                ]
            }
        )
        print("Created bot with name {} and alias {}".format(bot_name, alias))
        client.put_bot_alias(name=alias, botName=bot_name, botVersion='$LATEST')
    return chatbot

def get_bot_by_name_and_alias(client, bot_name, alias):
    try:
        bot_metadata = client.get_bot(name=bot_name, versionOrAlias=alias)
        print("Bot with name {} and alias {} already exists".format(bot_name, alias))
        return bot_metadata
    except ClientError as e:
        print("Bot with name {} and alias {} doesn't exist".format(bot_name, alias))
        return None

def create_service_intents_if_not_exists(client):
    slots = build_user_data_slot_types()
    create_taxi_service_intent(client, slots)
    create_food_service_intent(client, slots)
    create_home_care_service_intent(client, slots)
    create_cleaning_service_intent(client, slots)
    return ['OrderTaxi', 'OrderFood', 'OrderHomeCare', 'OrderCleaning']

def build_user_data_slot_types():
    slots = []
    slots.append(build_first_name_slot())
    slots.append(build_last_name_slot())
    slots.append(build_street_address_slot())
    slots.append(build_city_slot())
    slots.append(build_email_address_slot())
    slots.append(build_phone_number_slot())
    slots.append(build_date_slot())
    slots.append(build_time_slot())
    return slots

def build_first_name_slot():
    first_name_slot = {
        'name': 'FirstName',
        'slotConstraint': 'Required',
        'slotType': 'AMAZON.US_FIRST_NAME',
        'valueElicitationPrompt': {
            'messages': [
                build_message_dict("What's your first name?")
            ],
            'maxAttempts': 5
        },
        'priority': 1
    }
    return first_name_slot

def build_last_name_slot():
    last_name_slot = {
        'name': 'LastName',
        'slotConstraint': 'Required',
        'slotType': 'AMAZON.US_LAST_NAME',
        'valueElicitationPrompt': {
            'messages': [
                build_message_dict("What's your last name?")
            ],
            'maxAttempts': 5
        },
        'priority': 2
    }
    return last_name_slot

def build_street_address_slot():
    address_slot = {
        'name': 'Address',
        'slotConstraint': 'Required',
        'slotType': 'AMAZON.StreetAddress',
        'valueElicitationPrompt': {
            'messages': [
                build_message_dict("What's your street address?")
            ],
            'maxAttempts': 5
        },
        'priority': 3
    }
    return address_slot

def build_city_slot():
    city_slot = {
        'name': 'City',
        'slotConstraint': 'Required',
        'slotType': 'AMAZON.EUROPE_CITY',
        'valueElicitationPrompt': {
            'messages': [
                build_message_dict("What city are you in?")
            ],
            'maxAttempts': 5
        },
        'priority': 4
    }
    return city_slot

def build_email_address_slot():
    email_slot = {
        'name': 'Email',
        'slotConstraint': 'Required',
        'slotType': 'AMAZON.EmailAddress',
        'valueElicitationPrompt': {
            'messages': [
                build_message_dict("What's your email address?")
            ],
            'maxAttempts': 5
        },
        'priority': 5
    }
    return email_slot

def build_phone_number_slot():
    phone_number_slot = {
        'name': 'PhoneNumber',
        'slotConstraint': 'Required',
        'slotType': 'AMAZON.PhoneNumber',
        'valueElicitationPrompt': {
            'messages': [
                build_message_dict("What's your phone number?")
            ],
            'maxAttempts': 5
        },
        'priority': 6
    }
    return phone_number_slot

def build_date_slot():
    date_slot = {
        'name': 'Date',
        'slotConstraint': 'Required',
        'slotType': 'AMAZON.DATE',
        'valueElicitationPrompt': {
            'messages': [
                build_message_dict("On what date should I place the order?")
            ],
            'maxAttempts': 5
        },
        'priority': 7
    }
    return date_slot

def build_time_slot():
    time_slot = {
        'name': 'Time',
        'slotConstraint': 'Required',
        'slotType': 'AMAZON.TIME',
        'valueElicitationPrompt': {
            'messages': [
                build_message_dict("For what time should I place the order?")
            ],
            'maxAttempts': 5
        },
        'priority': 8
    }
    return time_slot

def create_taxi_service_intent(client, slots):
    intent_name = 'OrderTaxi'

    try:
        client.get_intent(name=intent_name, version='$LATEST')
        print("Intent with name {} already exists".format(intent_name))

    except ClientError as e:
        confirmation_prompt = {}
        conclusion_statement = {}
        rejection_statement = {}

        confirmation_prompt['messages'] = []
        confirmation_prompt['maxAttempts'] = 5
        conclusion_statement['messages'] = []
        rejection_statement['messages'] = []

        sample_utterances = [
            "Taxi",
            "Order taxi",
            "I want to order a taxi",
            "Call me a taxi"
        ]

        confirmation_prompt['messages'].append(build_message_dict("Should I order the Taxi?"))
        conclusion_statement['messages'].append(build_message_dict("Taxi is on its way!"))
        rejection_statement['messages'].append(build_message_dict("Okay, I cancelled the order"))

        response = client.put_intent(
            name=intent_name,
            slots=slots,
            sampleUtterances=sample_utterances,
            confirmationPrompt=confirmation_prompt,
            rejectionStatement=rejection_statement,
            conclusionStatement=conclusion_statement,
            fulfillmentActivity={
                'type': 'CodeHook',
                'codeHook': {
                    'uri': '[YOUR_LAMBDA_ARN]',
                    'messageVersion': '1.0'
                }
            }
        )
        print("Intent with name {} doesn't exist. Created one instead".format(intent_name))

def create_food_service_intent(client, slots):
    intent_name = 'OrderFood'

    try:
        client.get_intent(name=intent_name, version='$LATEST')
        print("Intent with name {} already exists".format(intent_name))

    except ClientError as e:
        confirmation_prompt = {}
        conclusion_statement = {}
        rejection_statement = {}

        confirmation_prompt['messages'] = []
        confirmation_prompt['maxAttempts'] = 5
        conclusion_statement['messages'] = []
        rejection_statement['messages'] = []

        sample_utterances = [
            "Food",
            "Order food",
            "I want to order food",
            "Order me some food"
        ]

        confirmation_prompt['messages'].append(build_message_dict("Should I place the order?"))
        conclusion_statement['messages'].append(build_message_dict("Food is on its way!"))
        rejection_statement['messages'].append(build_message_dict("Okay, I cancelled the order"))

        response = client.put_intent(
            name=intent_name,
            slots=slots,
            sampleUtterances=sample_utterances,
            confirmationPrompt=confirmation_prompt,
            rejectionStatement=rejection_statement,
            conclusionStatement=conclusion_statement,
            fulfillmentActivity={
                'type': 'CodeHook',
                'codeHook': {
                    'uri': '[YOUR_LAMBDA_ARN]',
                    'messageVersion': '1.0'
                }
            }
        )
        print("Intent with name {} doesn't exist. Created one instead".format(intent_name))

def create_home_care_service_intent(client, slots):
    intent_name = 'OrderHomeCare'

    try:
        client.get_intent(name=intent_name, version='$LATEST')
        print("Intent with name {} already exists".format(intent_name))

    except ClientError as e:
        confirmation_prompt = {}
        conclusion_statement = {}
        rejection_statement = {}

        confirmation_prompt['messages'] = []
        confirmation_prompt['maxAttempts'] = 5
        conclusion_statement['messages'] = []
        rejection_statement['messages'] = []

        sample_utterances = [
            "Home care",
            "I need a home care service"
        ]

        confirmation_prompt['messages'].append(build_message_dict("Should I place the order?"))
        conclusion_statement['messages'].append(build_message_dict("A home care professional is on their way!"))
        rejection_statement['messages'].append(build_message_dict("Okay, I cancelled the order"))

        response = client.put_intent(
            name=intent_name,
            slots=slots,
            sampleUtterances=sample_utterances,
            confirmationPrompt=confirmation_prompt,
            rejectionStatement=rejection_statement,
            conclusionStatement=conclusion_statement,
            fulfillmentActivity={
                'type': 'CodeHook',
                'codeHook': {
                    'uri': '[YOUR_LAMBDA_ARN]',
                    'messageVersion': '1.0'
                }
            }
        )
        print("Intent with name {} doesn't exist. Created one instead".format(intent_name))

def create_cleaning_service_intent(client, slots):
    intent_name = 'OrderCleaning'

    try:
        client.get_intent(name=intent_name, version='$LATEST')
        print("Intent with name {} already exists".format(intent_name))

    except ClientError as e:
        confirmation_prompt = {}
        conclusion_statement = {}
        rejection_statement = {}

        confirmation_prompt['messages'] = []
        confirmation_prompt['maxAttempts'] = 5
        conclusion_statement['messages'] = []
        rejection_statement['messages'] = []

        sample_utterances = [
            "Cleaning service",
            "Order cleaning service",
            "I need someone to clean my house",
            "Order me a maid"
        ]

        confirmation_prompt['messages'].append(build_message_dict("Should I place the order?"))
        conclusion_statement['messages'].append(build_message_dict("A maid is on their way!"))
        rejection_statement['messages'].append(build_message_dict("Okay, I cancelled the order"))

        response = client.put_intent(
            name=intent_name,
            slots=slots,
            sampleUtterances=sample_utterances,
            confirmationPrompt=confirmation_prompt,
            rejectionStatement=rejection_statement,
            conclusionStatement=conclusion_statement,
            fulfillmentActivity={
                'type': 'CodeHook',
                'codeHook': {
                    'uri': '[YOUR_LAMBDA_ARN]',
                    'messageVersion': '1.0'
                }
            }
        )
        print("Intent with name {} doesn't exist. Created one instead".format(intent_name))

def build_message_dict(message_content, content_type='PlainText'):
    message = {}
    message['contentType'] = content_type
    message['content'] = message_content
    return message

if __name__ == "__main__":
    grant_lex_lambda_permissions(boto3.client('lambda', 'us-east-1'), '[YOUR_LAMBDA_NAME]')
    client = boto3.client('lex-models', 'us-east-1')
    created_service_names = create_service_intents_if_not_exists(client)
    chatbot = create_bot_if_not_exists(client, 'dimbot', 'dim', created_service_names)


class Solution:
    def countPairs(self, coordinates: List[List[int]], k: int) -> int:
        hm = {tuple(i): 0 for i in coordinates}
        for i in coordinates:
            hm[tuple(i)] += 1

        count = 0
        coordinates = list(set([(i, j) for i, j in coordinates]))
        for x, y in coordinates:
            for i in range(k + 1):
                j = k - i
                x2 = x ^ i
                y2 = y ^ j
                if (x, y) == (x2, y2):
                    count += (hm[(x, y)] * (hm[(x, y)] - 1)) // 2
                elif (x2, y2) in hm:
                    count += hm[(x, y)] * hm[(x2, y2)]
            del hm[(x, y)]

        return count


import matplotlib.pyplot as plt  # type: ignore

from typing import Any, Dict, Iterable, List, Tuple
from os.path import exists
from os import makedirs
from numpy import arange  # type: ignore

from grao_tables_processing.common.pickle_wrapper import PickleWrapper
from grao_tables_processing.common.configuration import Configuration
from grao_tables_processing.common.custom_types import UnexpectedNoneError

def autolabel(ax, rects: Iterable[Any]):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

def load_processed_data() -> Tuple[Dict[Any, Any], Dict[Any, Any]]:
  ekatte_to_triple = PickleWrapper.load_data('ekatte_to_triple')
  combined = PickleWrapper.load_data('combined_tables')

  if ekatte_to_triple is None or combined is None:
    raise UnexpectedNoneError('There was an issue loading the data!')

  combined_dict = combined.to_dict(orient='index')

  return ekatte_to_triple, combined_dict

def path_for_settlement_graphic(directory: str, name: str, suffix: str = '') -> str:
  modified_name = name.replace('.', '').replace(' ', '_')

  if suffix == '_':
    suffix = ''

  return f'{directory}/{modified_name}{suffix}'

def prepare_directory(triple: Tuple[str, str, str], base: str) -> str:
  sub_path = f'{triple[0]}/{triple[1]}'.replace(' ', '_')
  full_path = f'{base}/{sub_path}'

  if not exists(full_path):
    makedirs(full_path)

  return full_path

def clear_figure():
  # Clear the current axes.
  plt.cla()

  # Clear the current figure.
  plt.clf()
  plt.ioff()

def draw_plot(directory: str, plot_name: str, type_name: str):
  plt_path = path_for_settlement_graphic(directory, plot_name.split(',')[-1].strip(), f'_{type_name.lower()}')
  plt.savefig(plt_path)
  print(plt_path)
  clear_figure()

def plot_single_value(directory: str, plot_name: str, values: List[int], labels: List[str], type_name: str = ''):
  _, ax = plt.subplots()

  xticks = arange(len(labels))
  width = 0.4

  # Add some text for labels, title and custom x-axis tick labels, etc.
  ax.set_ylabel('Number of residents')
  ax.set_xticks(xticks)
  ax.set_xticklabels(labels)
  ax.set_title(plot_name)

  rects = ax.bar(xticks - width / 20, values, width, label=type_name.capitalize(), align='center')
  autolabel(ax, rects)

  ax.legend()

  draw_plot(directory, plot_name, type_name)

def plot_comparison(
  directory: str,
  settlement_name: str,
  values_list: List[List[int]],
  labels: List[str],
  type_name: str = ''
):
  _, ax = plt.subplots()
  xticks = arange(len(labels))

  ax.set_xticks(xticks)
  ax.set_xticklabels(labels)

  for values in values_list:
    plt.plot(values)

  plt.title('Comparison between permanent and current')
  plt.xlabel('Year')
  plt.ylabel('Number of residents')
  plt.legend(['Permanent', 'Current'], loc='upper right')

  draw_plot(directory, settlement_name, type_name)

def create_visualizations(config: Configuration):
  ekatte_to_triple, combined_dict = load_processed_data()

  plt.rcParams['figure.figsize'] = [45, 15]

  labels = list(combined_dict[list(combined_dict.keys())[0]].keys())
  date_labels = list(map(lambda l: ' '.join(l.split('_')[1:]), labels[0::2]))
  date_labels.reverse()

  for item in combined_dict:
    triple = ekatte_to_triple[item]
    name = f'обл. {triple[0]}, общ. {triple[1]}, {triple[2]}'
    full_path = prepare_directory(triple, config.visualizations_path)

    values = list(combined_dict[item].values())

    permanent_values = values[0::2]
    permanent_values.reverse()
    plot_single_value(full_path, name, permanent_values, date_labels, 'permanent')

    current_values = values[1::2]
    current_values.reverse()
    plot_single_value(full_path, name, current_values, date_labels, 'current')

    plot_comparison(full_path, name, [permanent_values, current_values], date_labels, 'compare')

    # Closes all the figure windows.
    plt.close('all')


# packs of 6, 11, or 13 peppers
# take peppers and find the most economic way to pack
# input must be an int and < 1000
# take input and output how many of each pack
# mostly division

import sys

numPeppers = input('How many peppers are you shipping? ')

if '.' in numPeppers:
    input('Please input an integer: ')
    numPeppers = input()
else:
    numPeppers = int(numPeppers)
    if numPeppers > 1000:
        input('Please input an integer: ')
        numPeppers = input()

# so we want the least number of packs
# probably won't divide evenly
# start by looking for how many times 13 goes into it and make sure the remainder is bigger than 6
# then make sure when you divide by 11, the remainder is bigger than 6
# then when you divide by 6, the remainder has to be 0

num6 = []
num11 = []
num13 = []

if (numPeppers % 13) < 6:
    if (numPeppers % 11) < 6:
        if (numPeppers % 6) != 0:
            print("This can't be packed :(")

#if (numPeppers % 13) > 6:
#       if (numPeppers % 6) == 0:


class List:
    def __init__(self,key,value):
        self.key = key
        self.value = value
        self.next = None
class MyHashMap:
    def __init__(self):
        self.size = 1000
        self.hash = [None]*1000
    def put(self, key: int, value: int) -> None:
        ind = (key%self.size)
        ptr = self.hash[ind]
        if(ptr==None):
            self.hash[ind] = List(key,value)
            return
        while(1):
            if(ptr.key==key):
                ptr.value = value
                return
            if(ptr.next==None):
                break
            ptr = ptr.next
        # if there is no key then we can append at the end
        ptr.next = List(key,value)
    def get(self, key: int) -> int:
        ind = (key%1000)
        ptr = self.hash[ind]
        while(ptr):
            if(ptr.key==key):
                return ptr.value
            ptr = ptr.next
        return -1

    def remove(self, key: int) -> None:
        ind = (key%1000)
        ptr = self.hash[ind]
        ctr = ptr
        if(ptr==None):
            return
        if(ptr.key==key):
            self.hash[ind] = self.hash[ind].next
            return
        while(ptr):
            if(ptr.key==key):
                ctr.next = ptr.next
                return
            ctr = ptr
            ptr = ptr.next

# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)


import pytest
from fixtures.constants import Links
from fixtures.request import Request
import json
import os
import requests

#отправление запроса на получение нового access token
def update_refresh_token_api():
    token_data = {
        'refresh_token': Links.REFRESH_TOKEN,
        'client_id': Links.CLIENT_ID,
        'client_secret': Links.CLIENT_SECRET,
        'grant_type': 'refresh_token',
    }
    response = Request("Update refresh token").send_request(method="POST",
                       url=Links.TOKEN_URL,
                       data=token_data)
    return response

# функция для обновления токена
@pytest.fixture()
def update_refresh_token():
    response = update_refresh_token_api()
    if response.ok:
        token = response.json()['access_token']
        Links.ACCESS_TOKEN = token
        return token
    else:
        return None

# функция для получения ID файла
@pytest.fixture()
def get_file_id():
    file_path = os.path.join(os.getcwd(), Links.FILE_PATH)
    headers = {"Authorization": f"Bearer {Links.ACCESS_TOKEN}"}
    params = {"name": Links.FILE_NAME, "parents": [Links.PARENTS]}
    files = {"data": ("metadata", json.dumps(params),
                      "application/json; charset=UTF-8"),
             "file": open(file_path, "rb")}
    response = requests.post(Links.URL_DOWNLOAD, headers=headers, files=files)
    Links.FILE_ID_CORR = response.json()["id"]
    return response.json()["id"]


import json, requests
from flask import Flask, render_template, flash, request, redirect

app = Flask(__name__)
@app.route('/')
def getdata():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def submit():

    SearchCity = request.form.get('city')
    my_params = {'name': SearchCity}
    res = requests.post('https://us-central1-poised-aleph-290508.cloudfunctions.net/testfun', json = my_params)
    data = json.loads(res.text)

    city = data['city']['name']
    weatherTitle = data['list'][0]['weather'][0]['description']
    temperature = str(data['list'][0]['main']['temp'])
    result = SearchCity+" weather: "+weatherTitle+" \n Temperature: "+temperature+"°C"
    # return result
    return render_template('index.html', message = result)

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


from cgitb import text
from tkinter import *
from tkinter import messagebox
from tkcalendar import DateEntry
from tkinter import ttk

from PIL import Image, ImageTk
import homemenu
import viewaddtask
import database

class createAddTask:

    # constructor
    def __init__(self):
        self.root = Tk()
        self.root.title('Add Task')

        # to get the width and height of your computer screen
        self.fullwidth = self.root.winfo_screenwidth()
        self.fullheight = self.root.winfo_screenheight()

        # 800 x 500 is the size of your screen

        self.width = int((self.fullwidth-800)/2)
        self.height=int((self.fullheight-500)/2)

        s = "800x500+" +str(self.width)+ "+" +str(self.height)
        # s = "200x200"

        # so screen cant be resized
        self.root.resizable(height=False,width=False)

        self.root.geometry(s)

    def firstFrame(self):

        # create a frame
        self.mainFrame = Frame(self.root)
        self.mainFrame.place(x = 0, y = 0, width="800", height="500")

        self.my_label=Label(self.root,text="Add Task",font=("Mongolian Baiti",20))
        self.my_label.place(x=50,y=30,width="200")

        # set background image
        self.image = ImageTk.PhotoImage(Image.open('images/taskimg.webp'))
        self.bgLabel = Label(self.mainFrame, image=self.image)
        self.bgLabel.place(x = 350, y =  0,  width="450", height = "500")

        # self.EmpIdEntry = Entry(self.mainFrame)
        # self.EmpIdEntry.place(x = 150, y = 100, width="150",height=30)
        self.projectLabel = Label(self.mainFrame, text="Project",font=("Mongolian Baiti",16))
        self.projectLabel.place(x = 15, y = 100, width="120")

        self.project = database.namePro()
        print(self.project)
        # self.project = ['a', 'b', 'c']
        self.projectName = StringVar()
        self.projectEntry = ttk.Combobox(self.mainFrame,value=self.project, textvariable=self.projectName)
        self.projectEntry.place(x = 150, y = 100, width="150",height=30)

        self.Taskname = Label(self.mainFrame, text="Task Name",font=("Mongolian Baiti",16))
        self.Taskname.place(x = 30, y = 160, width="120")

        self.TasknameEntry = Entry(self.mainFrame)
        self.TasknameEntry.place(x = 150, y = 160, width="150",height=30)

        self.submit = Button(self.mainFrame, text = "Submit", command=self.create,font=("Mongolian Baiti",16),bg="white")
        self.submit.place(x = 80, y = 240, width="70")

        self.backBtn=Button(self.mainFrame,text="Back",font=("Mongolian Baiti",16),bg="white", command= self.back)
        self.backBtn.place(x=230,y=240,width="70",height=40)

        self.root.mainloop()

    def create(self):

        # print(tuple(self.projectName.get()))
        # print(self.projectName.get()[0])
        self.data = [
            self.projectEntry.get(),
            self.TasknameEntry.get()
        ]

        if self.projectEntry.get() == '':
            messagebox.showinfo('Alert', 'Enter your Project.')
        elif self.TasknameEntry.get() == '':
            messagebox.showinfo('Alert', 'Enter your Tasks.')
        else:
            res = database.addtask(self.data)
            if res:
                messagebox.showinfo('Alert','Submitted Successfully')
                self.root.destroy()
                obj = viewaddtask.viewAddTask()
                obj.manageTask()
            else:
                messagebox.showinfo('Alert', 'Something went wrong.')

    def back(self):
        self.root.destroy()
        obj = homemenu.createhome_menu()
        obj.firstFrame()

if __name__ == '__main__':
    obj = createAddTask()
    obj.firstFrame()


from django.shortcuts import render, redirect
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from googlesearch import search
from bs4 import BeautifulSoup
import nltk
import string
import random
import requests

data = ""

def find_data(query):
    global data
    for j in search(query, tld='co.in', num=10, stop=10, pause=3):
        res = requests.get(j)
        contents = res.text

        soup = BeautifulSoup(contents, "html.parser")

        paragraph = soup.find_all(name="p")
        # print(soup.p)

        for each in paragraph:
            # print(each.getText())
            data += each.getText()
        print(data)

def utility_func():
    raw_doc = data
    raw_doc = raw_doc.lower()
    nltk.download('punkt')
    nltk.download('wordnet')
    nltk.download('omw-1.4')
    sentence_tokens = nltk.sent_tokenize(raw_doc)
    word_tokens = nltk.word_tokenize(raw_doc)
    return sentence_tokens, word_tokens

def lem_tokens(tokens):
    lemmer = nltk.stem.WordNetLemmatizer()
    return [lemmer.lemmatize(token) for token in tokens]

def lemmatizer(text):
    remove_punc_dict = dict((ord(punct), None) for punct in string.punctuation)
    return lem_tokens(nltk.word_tokenize(text.lower().translate(remove_punc_dict)))

def greet(sentence):
    greet_inputs = ('hello', 'hi', 'hey')
    greet_outputs = ('hi', 'hey', 'Hey there')
    for word in sentence.split():
        if word.lower == 'wassup':
            return 'M good! You say!';
        if word.lower in greet_inputs and word.lower != 'wassup':
            return random.choice(greet_outputs)

def response(user_response, sentence_tokens):
    robo1_response = ''
    tf_idf_vec = TfidfVectorizer(tokenizer=lemmatizer, stop_words='english')
    tfidf = tf_idf_vec.fit_transform(sentence_tokens)
    vals = cosine_similarity(tfidf[-1], tfidf)
    idx = vals.argsort()[0][-2]
    flat = vals.flatten()
    flat.sort()
    req_tfidf = flat[-2]
    if req_tfidf == 0:
        robo1_response = robo1_response + 'I am Sorry. Unable to understand you!'
        return robo1_response
    else:
        robo1_response = robo1_response + sentence_tokens[idx]
        return robo1_response

def home(request):
    if request.method == 'POST':
        topic = request.POST.get('topic').lower()
        find_data(topic)
        return redirect('bot')

    return render(request,'home.html')

def bot_page(request):
    bot_text = 'Hello there! I am a learning Bot. Start typing your text after greeting to talk to me. To exit type ' \
               'bye! '
    if request.method == 'POST':
        u_text = request.POST.get('u_text').lower()
        user_response = u_text
        user_response = user_response.lower()
        if user_response != 'bye':
            if user_response == 'thank you' or user_response == 'thanks':
                bot_text = 'You are Welcome..'
            else:
                if greet(user_response) is not None:
                    bot_text = greet(user_response)
                else:
                    sentence_tokens, word_tokens = utility_func()
                    sentence_tokens.append(user_response)
                    bot_text = response(user_response, sentence_tokens)
                    sentence_tokens.remove(user_response)
        else:
            bot_text = 'Goodbye!'

    return render(request, 'bot.html', {'bot_text': bot_text})


class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class BST:
    def __init__(self):
        self.root = None

    def insert(self, val):
        newNode = Node(val)
        if self.root == None:
            self.root = newNode
            return val
        else:
            current = self.root
            while True:
                if val > current.val:
                    if not current.right:
                        current.right = newNode
                        return val
                    else:
                        current = current.right
                elif val < current.val:
                    if not current.left:
                        current.left = newNode
                        return val
                    else:
                        current = current.left
                else:
                    return "Value Present Already"

    def find_Max(self):
        if not self.root:
            return "No Data"
        else:
            current = self.root
            while current.right:
                current = current.right
                if not current.right:
                    return f'Max : {current.val}'

    def find_min(self):
        if not self.root:
            return "No Data"
        else:
            current = self.root
            while current.left:
                current = current.left
                if not current.left:
                    return f'Min : {current.val}'

b = BST()

b.insert(10)
b.insert(15)
b.insert(7)
b.insert(20)
b.insert(5)
print(b.insert(25))

print(b.find_Max())
print(b.find_min())


import logging

import xtgeo
import numpy as np
from vtk.util.numpy_support import vtk_to_numpy
import pyvista
from dash import Dash, html, dcc, callback, Input, Output, no_update
import dash_vtk
from dash_vtk.utils import to_mesh_state
from webviz_config._plugin_abc import WebvizPluginABC
from webviz_subsurface._utils.perf_timer import PerfTimer

from vtkmodules.vtkFiltersGeometry import vtkGeometryFilter
from vtkmodules.vtkFiltersGeometry import vtkExplicitStructuredGridSurfaceFilter

TIMER = PerfTimer()
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)

def time_it(text: str) -> str:
    return print(f"TIME: {text} {TIMER.lap_s():.2f}s")

class SurfaceApp(WebvizPluginABC):
    """Testing vtk performance"""

    def __init__(
        self,
        irap_file,
    ) -> None:
        super().__init__(self)
        time_it("Initializing app")

        surface = xtgeo.surface_from_file(irap_file)
        surface.values = surface.values * -1
        self.value_range = [np.min(surface.values), np.max(surface.values)]
        time_it("Read xtgeo surface")

        # surface.coarsen(4)
        time_it("Reduce resolution")

        xi, yi = surface.get_xy_values(asmasked=False)
        zi = surface.values
        zif = np.ma.filled(zi, fill_value=np.nan)
        time_it("Extract xyz from surface")

        self.sgrid = pyvista.StructuredGrid(xi, yi, zif)
        self.sgrid["Elevation"] = zif.flatten(order="F")
        time_it("Convert to structured grid")

        @callback(
            Output("vtk-mesh", "state"),
            Output("vtk-contours-mesh", "state"),
            Output("vtk-view", "triggerResetCamera"),
            Input("click", "n_clicks"),
        )
        def _update(nclicks):
            # Flipping z to trigger a change
            self.sgrid.flip_z(inplace=True)
            # sgrid = self.sgrid.decimate_boundary(0.75)
            # time_it("Decimate")
            TIMER.lap_s()
            contours = self.sgrid.contour()
            time_it("Make contours")

            mesh_state = to_mesh_state(self.sgrid, field_to_keep="Elevation")

            time_it("TO MESH STATE")
            contours_mesh_state = to_mesh_state(contours, field_to_keep="Elevation")
            time_it("CONTOURS TO MESH STATE")
            return mesh_state, contours_mesh_state, nclicks

        @callback(
            Output("dummy", "data"),
            Input("vtk-mesh", "state"),
        )
        def _update(_):
            time_it("Package delivered")
            return no_update

    @property
    def layout(self) -> html.Div:
        return html.Div(
            style={"height": "90vh"},
            children=[
                dash_vtk.View(
                    id="vtk-view",
                    children=[
                        dash_vtk.GeometryRepresentation(
                            id="vtk-representation",
                            children=[
                                dash_vtk.Mesh(id="vtk-mesh", state={}),
                            ],
                            property={"edgeVisibility": True},
                            colorDataRange=self.value_range,
                        ),
                        dash_vtk.GeometryRepresentation(
                            id="vtk-contours-representation",
                            children=[
                                dash_vtk.Mesh(id="vtk-contours-mesh", state={}),
                            ],
                            property={
                                "color": "black",
                                "width": 5,
                                "opacity": 1,
                            },
                        ),
                    ],
                ),
                html.Button(
                    id="click",
                    style={"fontSize": "10em"},
                    children="click",
                ),
                dcc.Store(id="dummy"),
            ],
        )


import pyro
import pyro.distributions as dist
import torch
import numpy as np
from congas.models.Model import Model
from pyro.ops.indexing import Vindex
from pyro import poutine
from pyro.infer.autoguide import AutoDelta
from torch.distributions import constraints
from congas.utils import entropy, log_sum_exp

"""

CNVs events are modelled as Categorical variables, what is shared by the clusters is the class probabilities for a given CNV satet
but different cells in the same clusters are allowed to have different CNVs profiles. It tries to get a mean

Model parameters:
    T = max number of clusters (default = 6)
    probs = prior probs for the Dirichlet modelling group CNV probabilities (default=torch.tensor([0.1,0.1,0.2,0.3,0.2,0.1]))
    hidden_dim = hidden dimensions (should be len(probs))
    theta_scale = scale for the normalization factor variable (default = 3)
    theta_rate = rate for the normalization factor variable (default = 1)
    batch_size = batch size (default = None)
    mixture = prior for the mixture weights (default = 1/torch.ones(K))
    gamma_multiplier = multiplier Gamma(rate * gamma_multiplier, shape  * gamma_multiplier) when we also want to
    infer the shape and rate parameter (i.e. when MAP = FALSE) (default = 4)

TODO:
    test on meaningful datasets
"""

class MixtureDirichlet(Model):

    params = {'K': 2, 'probs': torch.tensor([0.00001,0.25,0.5,0.25,0.05,0.05]), 'hidden_dim': 5,'theta_scale' : None, 'theta_rate': None, 'batch_size': None,
              'mixture': None, "nb_size_init": None, "binom_prior_limits" : [0.01,10000] }
    data_name = set(['data', 'mu', 'pld', 'segments', 'norm_factor'])

    def __init__(self, data_dict):
        self._params = self.params.copy()
        self._data = None
        super().__init__(data_dict, self.data_name)

    def model(self,*args, **kwargs):
        I, N = self._data['data'].shape
        batch = N if self._params['batch_size'] else self._params['batch_size']
        weights = pyro.sample('mixture_weights', dist.Dirichlet((1 / self._params['K']) * torch.ones(self._params['K'])))
        with pyro.plate('segments', I):
            size = pyro.sample("NB_size", dist.Uniform(self._params['binom_prior_limits'][0],
                                                        self._params['binom_prior_limits'][1]))
            segment_factor = pyro.sample('segment_factor',
                                         dist.Gamma(self._params['theta_scale'], self._params['theta_rate']))
            with pyro.plate('components', self._params['K']):
                cnv_probs = pyro.sample("CNV_probabilities", dist.Dirichlet(self._params['probs']))

        with pyro.plate('data', N, batch):
            assignment = pyro.sample('assignment', dist.Categorical(weights), infer={"enumerate": "parallel"})
            cc = pyro.sample('copy_number', dist.Categorical(Vindex(cnv_probs)[assignment,:, :]),
                             infer={"enumerate": "parallel"})
            mean = (cc * segment_factor * self._data['norm_factor'].reshape([1,N])) + 1e-8
            pyro.factor('obs', dist.NegativeBinomial(probs = mean / (mean + size), total_count = size).log_prob(self._data['data'])
                        - entropy(cnv_probs))

    def guide(self,MAP = False,  *args, **kwargs):
        return AutoDelta(poutine.block(self.model, expose=['mixture_weights', 'segment_factor', 'CNV_probabilities', 'NB_size']), init_loc_fn=self.init_fn())

    def full_guide(self, MAP = False , *args, **kwargs):
        def full_guide_ret(*args, **kargs):
            I, N = self._data['data'].shape
            batch = N if self._params['batch_size'] else self._params['batch_size']

            with poutine.block(hide_types=["param"]):  # Keep our learned values of global parameters.
                self.guide(MAP)()
            with pyro.plate('data', N, batch):
                assignment_probs = pyro.param('assignment_probs', torch.ones(N, self._params['K']) / self._params['K'],
                                              constraint=constraints.unit_interval)
                pyro.sample('assignment', dist.Categorical(assignment_probs), infer={"enumerate": "parallel"})

        return full_guide_ret

    def create_dirichlet_init_values(self):

        bins = self._params['hidden_dim'] * 2
        low_prob = 1 / bins
        high_prob = low_prob * (self._params['hidden_dim'] + 1)
        init = torch.zeros(self._params['K'], self._data['segments'], self._params['hidden_dim'])

        for i in range(len(self._data['pld'])):
            for j in range(self._params['hidden_dim']):
                for k in range(self._params['K']):
                    if k == 0:
                        init[k, i, j] = high_prob if j == torch.ceil(self._data['pld'][i]) else low_prob
                    else:
                        init[k, i, j] = high_prob if j == torch.floor(self._data['pld'][i]) else low_prob

        return init

    def init_fn(self):

        def init_function(site):
            if site["name"] == "CNV_probabilities":
                return self.create_dirichlet_init_values()
            if site["name"] == "mixture_weights":
                return self._params['mixture']
            if site["name"] == "NB_size":
                return self._params['nb_size_init']
            if site["name"] == "segment_factor":
                return dist.Gamma(self._params['theta_scale'], self._params['theta_rate']).mean
            raise ValueError(site["name"])

        return init_function

    def likelihood_model(self, segment_fact_marg, weights, size, probs_cnv):
        lk = torch.zeros(self._params['hidden_dim'], self._params['K'], self._data['data'].shape[1],
                         self._data['data'].shape[0])
        if self._params['K'] == 1:
            # norm_f = torch.sum(segment_fact_marg)
            for i in range(self._data['data'].shape[0]):
                for h in range(self._params['hidden_dim']):
                    mean = (segment_fact_marg[i, h] * self._data['norm_factor'])  # / norm_f
                    lk[h, 0, :, i] = dist.NegativeBinomial(probs=mean / (mean + size[i]), total_count=size[i]).log_prob(
                        self._data['data'][i, :]) + torch.log(probs_cnv[0, i, h])
            return lk

        for k in range(self._params['K']):
            # norm_f = torch.sum(segment_fact_marg[k,:])
            for i in range(self._data['data'].shape[0]):
                for h in range(self._params['hidden_dim']):
                    mean = (segment_fact_marg[i, h] * self._data['norm_factor'])  # / norm_f
                    lk[h, k, :, i] = dist.NegativeBinomial(probs=mean / (mean + size[i]), total_count=size[i]).log_prob(
                        self._data['data'][i, :]) + torch.log(probs_cnv[k, i, h])

        return log_sum_exp(lk)

    def likelihood(self, inf_params):
        I, N = self._data['data'].shape
        cat_vector = torch.tensor(np.arange(self._params['hidden_dim']) + 1, dtype=torch.float)
        segment_fact = torch.matmul(inf_params["segment_factor"].reshape([I, 1]),
                                    cat_vector.reshape([1, self._params['hidden_dim']]))

        lk = self.likelihood_model(segment_fact, inf_params["mixture_weights"], inf_params["NB_size"],
                                   inf_params["CNV_probabilities"])
        return lk

    def calculate_cluster_assignements(self, inf_params):

        lk = self.likelihood(inf_params)
        lk = torch.sum(lk, dim=2) + torch.log(inf_params["mixture_weights"]).reshape([self._params['K'], 1])

        summed_lk = log_sum_exp(lk)
        ret = lk - summed_lk
        res = {"assignment_probs": torch.exp(ret).detach().numpy()}
        return res


import time

from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(executable_path='..//drivers//chromedriver.exe')
driver.maximize_window()
map_coord = {
    "latitude": 39.73925065383228,
    "longitude": -104.99024801028608,
    "accuracy": 1
}
driver.execute_cdp_cmd("Emulation.setGeolocationOverride", map_coord)
# time.sleep(2)
driver.get("https://google.com")
driver.find_element(By.NAME,"q").send_keys("netflix")
driver.find_element(By.NAME,'q').send_keys(Keys.ENTER)
driver.find_element(By.XPATH,'//div[@class="TbwUpd NJjxre"][1]').click()
print("Geolocation testing with Selenium is complete")

# https://chromedevtools.github.io/devtools-protocol/tot/Emulation/#method-setGeolocationOverride


# -*- coding: utf-8 -*-
import os
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
from flask_app import db

from tool.Util import Util

class FileInfo(db.Model):
    __tablename__ = 'FileInfo'
    fileID = db.Column(db.String(100), primary_key=True)
    fileName = db.Column(db.String(100))
    userID = db.Column(db.String(100))
    createTime = db.Column(db.DateTime)
    superID = db.Column(db.String(100))
    isDirectory = db.Column(db.Boolean)
    privateLevel = db.Column(db.Integer)
    filePath = db.Column(db.String(1000))
    areaID = db.Column(db.String(100))
    tag = db.Column(db.Integer)

    def __init__(self, fileID=None, fileName=None,
                 userID=None, createTime=None, superID='-1',
                 isDirectory=False, privateLevel=0, filePath=None,
                 areaID=None, tag=0):
        self.fileID = fileID
        self.fileName = fileName
        self.userID = userID
        self.createTime = createTime
        self.superID = superID
        self.isDirectory = isDirectory
        self.privateLevel = privateLevel
        self.filePath = filePath
        self.areaID = areaID
        self.tag = tag

    @staticmethod
    def generate(o, ossInfo):
        res = {}
        res['fileID'] = o.fileID
        res['fileName'] = o.fileName
        res['userID'] = o.userID
        res['isDirectory'] = o.isDirectory
        res['tag'] = o.tag
        res['createTime'] = str(o.createTime)

        util = Util()
        if o.isDirectory is False:
            ossInfo['objectKey'] = '%s/%s' % ('files', o.filePath)
            res['filePath'] = util.getSecurityFileUrl(ossInfo)
        return res

    def __repr__(self):
        return self.fileID


# One example of the application of 2d-arrays is in image processing. A digital,
# grayscale image can be thought of as a 2d array of integers between 0 and 255.
# Each element of the 2d array represents light intensity of a single pixel in the
# image. Let's write a function that uses so called mean filter to smooth an image.
# The idea of mean filtering is simply to replace each pixel value in an image with the
# mean (`average') value of its neighbors, including itself. This has the effect of eliminating
# pixel values which are unrepresentative of their surroundings. Most pixels have eight neighbors.
# The pixels in the boundary rows and columns have 5 neighbors and the corner pixels have only three neighbors.

# Your function called meanFitler should take one parameter which is an object of type Grid
# (defined in the attached file) and apply mean filter to that object. The function should
# not return anything it should modify the object passed as a parameter.

from grid import Grid

def median_filter(data: Grid):
    xmax = data.getWidth()
    ymax = data.getHeight()

    for x in range(0, xmax):
        for y in range(0, ymax):
            _run_filter(x, y, xmax, ymax, data)

def _run_filter(x: int, y: int, xmax: int, ymax: int, data: Grid):
    mean = data[y][x]
    vals = 1
    for xrel in range(-1, 2):
        for yrel in range(-1, 2):
            absx = x + xrel
            absy = y + yrel
            if absx < 0 or absy < 0 or absx >= xmax or absy >= ymax:
                continue
            mean += data[absy][absx]
            vals += 1

    mean /= vals
    data[y][x] = mean

def main():
    g = Grid(3, 3, 1)
    g[1][1] = 2
    print(g)
    median_filter(g)
    print("------------------")
    print("SMOOTHED")
    print("------------------")
    print()
    print(g)

if __name__ == "__main__":
    main()


n, m, x, y, k = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(n)]
moves = list(map(int, input().split()))
dice = [0 for _ in range(6)]
dx = [0, 0, 0, -1, 1]
dy = [0, 1, -1, 0, 0]

def roll(move: int , dice: list):
    if move == 1:
        return [dice[3], dice[1], dice[0], dice[5], dice[4], dice[2]]
    elif move == 2:
        return [dice[2], dice[1], dice[5], dice[0], dice[4], dice[3]]
    elif move == 3:
        return [dice[4], dice[0], dice[2], dice[3], dice[5], dice[1]]
    else:
        return [dice[1], dice[5], dice[2], dice[3], dice[0], dice[4]]

if board[x][y] != 0:
    dice[5] = board[x][y]

for move in moves:
    newX = x+dx[move]
    newY = y+dy[move]
    if 0<=newX<n and 0<=newY<m:
        x, y = newX, newY
        dice = roll(move, dice)
        if board[x][y] == 0:
            board[x][y] = dice[5]
        else:
            dice[5] = board[x][y]
            board[x][y] = 0
        print(dice[0])


# coding=utf-8
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import os

VLSM = ({'slash': '/25', 'mask': 128, 'hosts': 126, 'block': 128},
        {'slash': '/26', 'mask': 192, 'hosts': 62, 'block': 64},
        {'slash': '/27', 'mask': 224, 'hosts': 30, 'block': 32},
        {'slash': '/28', 'mask': 240, 'hosts': 14, 'block': 16},
        {'slash': '/29', 'mask': 248, 'hosts': 6, 'block': 8},
        {'slash': '/30', 'mask': 252, 'hosts': 2, 'block': 4})

def compute():
    source = raw_input("输入要划分的IP：")
    source_s = ''
    for c in source.rpartition(".")[:-1]:
        source_s += c

    a_sum = int(raw_input("输入划分段数："))
    if a_sum > 64:
        raw_input("大于最大子网数 退出")
        return

    alist = {}
    for i in range(a_sum):
        alist.update({i: int(raw_input("第" + str(i + 1) + "段主机数:"))})

    sum = 0
    for i in alist.values():
        for example in VLSM[::-1]:
            if (i) <= example['hosts']:
                sum += example['block']
                break
    if sum > 256:
        raw_input("大于最大主机数 退出")
        return

    alist_order = alist.items()
    alist_order.sort(key=lambda x: x[1], reverse=True)

    subnet_type = []
    for i in alist_order:
        for example in VLSM[::-1]:
            if i[1] <= example['hosts']:
                subnet_type.append(VLSM.index(example))
                break

    subnet_list = [{}] * len(subnet_type)
    number = 0
    for index in range(len(subnet_type)):
        i = subnet_type[index]
        start = number
        end = start + VLSM[i]['block'] - 1
        subnet_list[alist_order[index][0]] = {'start': start, 'end': end, 'mask': i}
        number = end + 1

    outimg_a(source_s, alist, subnet_list)
    outimg_b(source_s, subnet_list)

def compute_web(source, alist):
    os.chdir(os.path.split(os.path.realpath(__file__))[0])

    # source=raw_input("输入要划分的IP：")
    source_s = ''
    for c in source.rpartition(".")[:-1]:
        source_s += c

    # a_sum=int(raw_input("输入划分段数："))
    # if a_sum>64:
    #     raw_input("大于最大子网数 退出")
    #     return

    # alist={}
    # for i in range(a_sum):
    #     alist.update({i:int(raw_input("第"+str(i+1)+"段主机数:"))})

    sum = 0
    for i in alist.values():
        for example in VLSM[::-1]:
            if (i) <= example['hosts']:
                sum += example['block']
                break
    if sum > 256:
        raw_input("大于最大主机数 退出")
        return False

    alist_order = alist.items()
    alist_order.sort(key=lambda x: x[1], reverse=True)

    subnet_type = []
    for i in alist_order:
        for example in VLSM[::-1]:
            if i[1] <= example['hosts']:
                subnet_type.append(VLSM.index(example))
                break

    subnet_list = [{}] * len(subnet_type)
    number = 0
    for index in range(len(subnet_type)):
        i = subnet_type[index]
        start = number
        end = start + VLSM[i]['block'] - 1
        subnet_list[alist_order[index][0]] = {'start': start, 'end': end, 'mask': i}
        number = end + 1

    outimg_a(source_s, alist, subnet_list)
    outimg_b(source_s, subnet_list)
    return True

def outimg_a(source, alist, subnet):
    h = len(alist) * 30 + 40 + 3
    im = Image.new('RGB', (600, h), 0xffffff)
    draw = ImageDraw.Draw(im)
    width, height = im.size
    # 画行横线，每行30像素，第一行多10像素。
    for i in range(1, len(alist) + 2):
        y = i * 30 + 10;
        draw.line(((10, y), (width - 10, y)), fill=(225, 225, 225))

    # 边线
    draw.line(((10, 1), (10, height - 2)), fill=(225, 225, 225))
    draw.line(((width - 10, 1), (width - 10, height - 2)), fill=(225, 225, 225))

    # 标题

    # 标题背景
    draw.rectangle(((10, 1), (width - 10, 40)), fill=(223, 223, 223));
    # 标题文字，使用雅黑粗
    font = ImageFont.truetype("msyhbd.ttc", 14)
    fontcolor = (14, 77, 157)

    draw.text((20, 10), "No", fill=fontcolor, font=font)
    draw.line(((50, 1), (50, height - 3)), fill=(0, 0, 0))
    draw.text((56, 10), "need hosts", fill=fontcolor, font=font)
    draw.line(((137, 1), (137, height - 3)), fill=(0, 0, 0))
    draw.text((150, 10), "subnet pool", fill=fontcolor, font=font)
    draw.line(((460, 1), (460, height - 3)), fill=(0, 0, 0))
    draw.text((465, 10), "mask", fill=fontcolor, font=font)

    font = ImageFont.truetype("msyh.ttc", 12)
    fontcolor = (50, 100, 100)

    for i in range(len(subnet)):
        h = (i + 1) * 30 + 15
        draw.text((20, h), str(i + 1), fill=fontcolor, font=font)
        draw.text((56, h), str(alist[i]), fill=fontcolor, font=font)
        draw.text((150, h), source + str(subnet[i]['start']) + VLSM[subnet[i]['mask']]['slash'], fill=fontcolor,
                  font=font)
        draw.text((270, h), "----", fill=fontcolor, font=font)
        draw.text((305, h), source + str(subnet[i]['end']) + VLSM[subnet[i]['mask']]['slash'], fill=fontcolor,
                  font=font)
        draw.text((465, h), "255.255.255." + str(VLSM[subnet[i]['mask']]['mask']), fill=fontcolor, font=font)

    im.save('a.jpg')

def outimg_b(source, subnet):
    im = Image.new('RGB', (300, 1320), 0xffffff)
    draw = ImageDraw.Draw(im)

    font_l = ImageFont.truetype("msyh.ttc", 12)
    font_h = ImageFont.truetype("msyhbd.ttc", 12)
    fontcolor = (50, 100, 100)

    for i in range(0, 256 + 1, 4):
        h = (i / 4) * 20 + 12
        if i % 16 == 0:
            draw.text((10, h), str(i).rjust(3), fill=fontcolor, font=font_h)
            draw.line(((37, h + 8), (50, h + 8)), fill=(0, 0, 0), width=4)
        else:
            draw.text((10, h), str(i).rjust(3), fill=fontcolor, font=font_l)
            draw.line(((37, h + 8), (50, h + 8)), fill=(0, 0, 0), width=2)
    draw.line(((43, 20), (43, 1300)), fill=(0, 0, 0), width=2)

    for i in subnet:
        sline_h = i['start'] / 4 * 20 + 12 + 8
        eline_h = (i['end'] + 1) / 4 * 20 + 12 + 8
        text_h = (sline_h + eline_h) / 2 - 8

        draw.line(((60, sline_h), (290, sline_h)), fill=(0, 0, 0), width=2)
        draw.line(((60, eline_h), (290, eline_h)), fill=(0, 0, 0), width=2)
        draw.text((95, text_h),
                  "No." + str(subnet.index(i) + 1) + " - " + source + str(i['start']) + VLSM[i['mask']]['slash'],
                  fill=fontcolor, font=font_l)

    im.save('b.jpg')

if __name__ == '__main__':
    compute()


import util.File as File
import os.path as op
import random
from functools import reduce

class MajorProcess:

    def __init__(self, total):
        self.__total = total
        self.__data = self.__packager()

    def __packager(self):
        doc_data = File.File.read_file(op.join('data', 'doc.txt'))
        tags_data = File.File.read_file(op.join('data', 'tags.txt'))
        return [[int(tags_data[i][0]), int(tags_data[i][2]), doc_data[i][:-1]] for i in range(len(doc_data))]

    def __create_start(self, page):
        """ 生成文章的开头
        """
        art = ""
        if page > int(self.__total / 2):
            parta = ['时间过得真快', '光阴似箭', '时光匆匆']
            art += random.choice(parta)
            art += '，'

        partb = ['这是实习的第 ' + str(page + 1),
                 '现在是实习的第 ' + str(page + 1),
                 '这周是实习的第 ' + str(page + 1),
                 ]
        if page > int(self.__total / 2):
            partb.append('这周已经是实习的第 ' + str(page + 1))
            partb.append('眨眼就到了实习的第 ' + str(page + 1))

        art += random.choice(partb)
        art += ' '

        partc = ['周', '个星期']
        art += random.choice(partc)
        art += '。'

        return art

    def __create_main(self, page, emotion):
        """ 生成文章主体

        :param page:
        :param emotion:
        :return:
        """
        if page == 0:
            result = list(filter(lambda item: item[0] == emotion and (item[1] == 0 or item[1] == 4), self.__data))
        elif page == self.__total-1:
            result = list(filter(lambda item: item[0] == emotion and (item[1] == 1 or item[1] == 4), self.__data))
        elif page <= int(self.__total/2):
            result = list(filter(lambda item: item[0] == emotion and (item[1] == 2 or item[1] == 4), self.__data))
        else:
            result = list(filter(lambda item: item[0] == emotion and (item[1] == 3 or item[1] == 4), self.__data))

        res = random.choices(result, k=5)
        art = ''
        for item in res:
            art += item[2]
        return art

    def __create_end(self, page, emotion):
        """ 生成文章的末尾

        :param page:
        :param emotion:
        :return:
        """
        if emotion == 0:
            if page == 0:
                part = ['挑战才刚刚开始。', '感觉未来的生活充满着挑战。']
                return random.choice(part)
            elif page == self.__total-1:
                part = ['尽管有诸多不如意，实习终归结束了。', '最后感谢这次的宝贵的实习机会。']
                return random.choice(part)
            elif page <= int(self.__total / 2):
                part = ['接下来，我会好好调整心态，直面困难。',
                        '感觉是应该好好反省一下自己了。',
                        '未来还有很多查漏补缺的地方，任重而道远啊。'
                        ]
                return random.choice(part)
            else:
                part = ['实习已经过了一大半了，剩下的时间要好好努力。',
                        '虽然实习中有很多挑困难，但是我成长了很多。']
                return random.choice(part)
        else:
            if page == 0:
                part = ['']
                return random.choice(part)
            elif page == self.__total - 1:
                part = ['到今天，实习就结束了，最后感谢在实习中帮助了我的人。',
                        '最后感谢这次的宝贵的实习机会。'
                        ]
                return random.choice(part)
            elif page <= int(self.__total / 2):
                part = ['剩下的时间要再接再厉。', '剩下的实习时间还有一大半，我会好好珍惜的。']
                return random.choice(part)
            else:
                part = ['过去的一段时间中，总的来说收获了很多。',
                        '不得不说，这次实习让我成长了许多。']
                return random.choice(part)

    def process(self):
        """ 生成指定数量的周志

        :return:
        """
        for page in range(self.__total):
            self.single_process(page)

    def single_process(self, week):
        """ 生成指定周的周志, 文章为总分总结构, 大于 200 字, week 从 0 开始计数

        :param week:
        :return:
        """
        emotions = [0, 1]
        emotion = random.choice(emotions)
        article = ""
        article += self.__create_start(week)
        article += self.__create_main(week, emotion)
        has_end = random.choice([0, 1, 2, 3])
        if has_end == 1 or week == 0 or week == self.__total-1:
            article += self.__create_end(week, emotion)
        File.File.write_file(op.join('article', str(week) + '.txt'), article)

if __name__ == '__main__':
    # 获得 10 周的全部周志
    MajorProcess(10).process()
    # 获得 10 周中第 3 周的周志
    MajorProcess(10).single_process(2)


import aiohttp
import json
from pyrogram import Client, filters, emoji
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from config import api_hash, api_id, bot_token, ARQ_API_BASE_URL

app = Client("torrent_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token)

print("\nBot Started\n")

@app.on_message(filters.command(['start']))
async def start(_, message):
    await message.reply_text("Hello I'm Torrent Scraper Bot\nSend Command 'help' To Show Help Screen, Join @TheHamkerChat For Support.")

@app.on_message(filters.command(['help']))
async def help(_, message):
    await message.reply_text("/torrent query, To Search For Torrents")

m = None
i = 0
a = None
query = None

@app.on_message(filters.command(["torrent"]))
async def torrent(_, message):
    global m
    global i
    global a
    global query
    try:
        await message.delete()
    except:
        pass
    if len(message.command) < 2:
        await message.reply_text("Usage: /torrent query")
        return
    query = message.text.split(None, 1)[1].replace(" ", "%20")
    m = await message.reply_text("Searching")
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"{ARQ_API_BASE_URL}torrent?query={query}") \
                    as resp:
                a = json.loads(await resp.text())
    except:
        await m.edit("Found Nothing.")
        return
    result = (
        f"**Page - {i+1}**\n\n"
        f"Name: {a[i]['name']}\n"
        f"Upload: {a[i]['uploaded']}\n"
        f"Size: {a[i]['size']}\n"
        f"Leechers: {a[i]['leechs']} "
        f"seeders: {a[i]['seeds']}\n"
        f"Magnet: `{a[i]['magnet']}`\n\n\n"
    )
    await m.edit(
        result,
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(f"Next {emoji.RIGHT_ARROW}",
                                         callback_data="next"),
                    InlineKeyboardButton(f"Delete {emoji.CROSS_MARK}",
                                         callback_data="delete")
                ]
            ]
        ),
        parse_mode="markdown",
    )

@app.on_callback_query(filters.regex("next"))
async def callback_query_next(_, message):
    global i
    global m
    global a
    global query
    i += 1
    result = (
        f"**Page - {i+1}**\n\n"
        f"Name: {a[i]['name']}\n"
        f"Upload: {a[i]['uploaded']}\n"
        f"Size: {a[i]['size']}\n"
        f"Leechers: {a[i]['leechs']} "
        f"seeders: {a[i]['seeds']}\n"
        f"Magnet: `{a[i]['magnet']}`\n\n\n"
    )
    await m.edit(
        result,
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(f"{emoji.LEFT_ARROW} Previous",
                                         callback_data="previous"),
                    InlineKeyboardButton(f"Next {emoji.RIGHT_ARROW}",
                                         callback_data="next"),
                    InlineKeyboardButton(f"Delete {emoji.CROSS_MARK}",
                                         callback_data="delete")

                ]
            ]
        ),
        parse_mode="markdown",
    )

@app.on_callback_query(filters.regex("previous"))
async def callback_query_previous(_, message):
    global i
    global m
    global a
    global query
    i -= 1
    result = (
        f"**Page - {i+1}**\n\n"
        f"Name: {a[i]['name']}\n"
        f"Upload: {a[i]['uploaded']}\n"
        f"Size: {a[i]['size']}\n"
        f"Leechers: {a[i]['leechs']} "
        f"seeders: {a[i]['seeds']}\n"
        f"Magnet: `{a[i]['magnet']}`\n\n\n"
    )
    await m.edit(
        result,
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(f"{emoji.LEFT_ARROW} Previous",
                                         callback_data="previous"),
                    InlineKeyboardButton(f"Next {emoji.RIGHT_ARROW}",
                                         callback_data="next"),
                    InlineKeyboardButton(f"Delete {emoji.CROSS_MARK}",
                                         callback_data="delete")
                ]
            ]
        ),
        parse_mode="markdown",
    )

@app.on_callback_query(filters.regex("delete"))
async def callback_query_delete(_, message):
    global m
    global i
    global a
    global query
    await m.delete()
    m = None
    i = 0
    a = None
    query = None

app.run()


sentence = "whale hello there. Don't we all love whales? I absolutely love whales! whales are so huge!!!"

with open('moby.txt') as f:
    for line in f:
        sentence = line.strip()
        counter = 0
        whales = "whales"
        for i in range(0,len(sentence)):
            if (whales[i:i+5].lower() == "whales"):
                counter = counter + 1

#with open('moby.txt') as f:
#    for line in f:
#        sentence = line.strip()
#        ##YOUR CODE GOES HERE
#
f.close()
print(counter)


try:
    import pygame
except ImportError:
    raise ImportError("\n<pygame> library is missing on your system."
          "\nTry: \n   C:\\pip install pygame on a window command prompt.")

from SoundServer import *

if __name__ == "__main__":

    pygame.mixer.init()
    sound1 = pygame.mixer.Sound('Alarm9.ogg')
    SCREENRECT = pygame.Rect(0, 0, 800, 1024)
    pygame.display.set_mode((SCREENRECT.w, SCREENRECT.h))
    SND = SoundControl(SCREENRECT, 8)
    # SND.play(sound1, -1, volume_=1.0, panning_=False)
    SND.play(sound1, -1, volume_=1.0, panning_=True, x_=400, fade_in_ms=0, fade_out_ms=0)
    # SND.play(sound1, -1, volume_=1.0, panning_=True, x_=100)
    # SND.play(sound1, -1, volume_=1.0, panning_=True, x_=200)
    # SND.play(sound1, -1, volume_=1.0, panning_=True, x_=400)
    # SND.play(sound1, -1, volume_=1.0, panning_=True, x_=800)
    # SND.play(sound1, -1, volume_=1.0, panning_=True, x_=100)
    # SND.play(sound1, -1, volume_=1.0, panning_=True, x_=450)
    x = 0
    v = 1.0
    FRAME = 0
    while 1:
        # SND.show_sounds_playing()
        pygame.event.pump()
        pygame.display.flip()
        # SND.update_sounds_panning(x, v)

        SND.update_sound_panning(x, 1.0, name_="", id_=id(sound1))
        if x < SCREENRECT.w:
             SND.update_sound_panning(x, 0.2, None, id(sound1))
             x += 0.1
        else:
             SND.update_volume(1)

        SND.update()

        if 4000 < FRAME < 9000:
            SND.pause_sounds()
        else:
            SND.unpause_sound(id_=id(sound1))

        SND.show_free_channels()
        SND.show_sounds_playing()
        print(SND.return_time_left(id(sound1)))
        print(FRAME)
        if FRAME == 1000:
            SND.stop_all()

        print(SND.get_identical_sounds(sound1))
        print(SND.get_identical_id(id(sound1)))

        x += 1
        x %= SCREENRECT.w
        FRAME += 1


"""766. Toeplitz Matrix"""

from typing import List

class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        rows = len(matrix)
        columns = len(matrix[0])

        if rows == 1 or columns == 1:
            return True

        for i in range(rows - 1):
            target = matrix[i][0]

            for j in range(1, min(rows - i, columns)):
                if matrix[i + j][j] != target:
                    return False

        for i in range(1, columns - 1):
            target = matrix[0][i]

            for j in range(1, min(rows, columns - i)):
                if matrix[j][i + j] != target:
                    return False

        return True