from celery import shared_task
from celery.utils.log import get_task_logger

from flask import current_app

from invenio_db import db

from invenio_oauthclient.models import RemoteAccount, RemoteToken, UserIdentity

from invenio_pidstore.resolver import Resolver

from invenio_search import current_search_client
from invenio_search.utils import schema_to_index

from requests import RequestException

from .models import InspireOrcidRecords
from .utils import convert_to_orcid, get_authors_credentials

logger = get_task_logger(__name__)

def prepare_authors_data_for_pushing_to_orcid(json):
    """ Extracts the authors with valid orcid credentials from the list of authors
    of a given record in json format.
    """
    resolver = Resolver(pid_type='literature',
                        object_type='rec', getter=lambda x: x)
    record_id = resolver.resolve(json.get('control_number'))[
        0].object_uuid
    authors = get_orcid_valid_authors(json)
    token = None
    author_orcid = ''
    authors_with_orcid_credentials = []
    for author in authors:
        try:
            token, author_orcid = get_authors_credentials(author['_source'])
        except AttributeError:
            continue
        try:
            authors_with_orcid_credentials.append((InspireOrcidRecords.query.filter_by(
                orcid=author_orcid, record_id=record_id).first().put_code, token, author_orcid, record_id))
        except AttributeError:
            authors_with_orcid_credentials.append(
                ([], token, author_orcid, record_id))
            continue
    return authors_with_orcid_credentials

@shared_task(ignore_result=True)
def delete_from_orcid(sender, api=None):
    """ Deletes a record from orcid.
    """
    if not api:
        api = current_app.extensions['inspire-orcid'].orcid_api

    resolver = Resolver(pid_type='literature',
                        object_type='rec', getter=lambda x: x)
    record_id = resolver.resolve(sender.get('control_number'))[
        0].object_uuid
    records = InspireOrcidRecords.query.filter_by(record_id=record_id).all()
    for record in records:
        raw_user = UserIdentity.query.filter_by(
            id=record.orcid, method='orcid').first()
        remote_user = RemoteAccount.query.filter_by(user_id=raw_user.id_user).first()
        token = RemoteToken.query.filter_by(
            id_remote_account=remote_user.id).first().access_token
        api.remove_record(record.orcid, token, 'work', record.put_code)
        with db.session.begin_nested():
            db.session.delete(record)
        db.session.commit()

def doc_type_should_be_sent_to_orcid(record):
    index, doc_type = schema_to_index(record['$schema'])
    return doc_type == 'hep'

@shared_task(ignore_result=True)
def send_to_orcid(sender, api=None):
    """Sends records to orcid."""
    if doc_type_should_be_sent_to_orcid(sender):
        logger.info("Sending to orcid: ", sender.get('control_number'))
        try:
            if not api:
                api = current_app.extensions['inspire-orcid'].orcid_api
            orcid_json = convert_to_orcid(sender)
            authors = prepare_authors_data_for_pushing_to_orcid(sender)
            for put_code, token, author_orcid, record_id in authors:
                try:
                    if not put_code:
                        put_code = api.add_record(  # try-continue
                            author_orcid, token, 'work', orcid_json)
                        orcid_log_record = InspireOrcidRecords(
                            orcid=author_orcid,
                            record_id=record_id,
                            put_code=put_code)
                        with db.session.begin_nested():
                            db.session.add(orcid_log_record)
                        db.session.commit()
                    else:
                        api.update_record(author_orcid, token,
                                          'work', orcid_json, str(put_code))
                    logger.info("Successfully sent to orcid: ",
                                sender.get('control_number'))
                except RequestException as e:
                    print(e.response.text, sender['control_number'])
                    logger.error("Failed to push to orcid: ",
                                 sender.get('control_number'))
                    continue
        except (KeyError, AttributeError, TypeError) as e:
            logger.warning("Failed to convert: ", sender.get('control_number'))

def get_author_collection_records_from_valid_authors(authors_refs):
    """ Queries elasticsearch for the author-records of the given authors references.
    """
    es_query = {
        "filter": {
            "bool": {
                "must": [
                    {"terms": {
                        "self.$ref": authors_refs
                    }}, {"match": {
                        "ids.type": "ORCID"
                    }}
                ]
            }
        }
    }
    authors = current_search_client.search(
        index='records-authors',
        doc_type='authors',
        body=es_query
    )['hits']['hits']
    return authors

def get_orcid_valid_authors(record):
    """ Returns all the valid author-records from a hep-record.
    A valid author-rerord is one that contains an orcid id.
    """
    authors_refs = []
    for author in record['authors']:
        try:
            authors_refs.append(author['record']['$ref'])
        except KeyError:
            continue

    return get_author_collection_records_from_valid_authors(authors_refs)


from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView
from django.contrib.auth import logout, login
from django.views.generic import CreateView
from .forms import *
from .models import Target
import datetime
from random import choice
'''
bootstrap быстрый сделать
'''
def index(request):
    return render(request, "main_app/main_page.html", {})

class RegisterUser(CreateView):
    form_class = UserCreationForm
    template_name = 'main_app/register.html'
    success_url = reverse_lazy('login')
    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        #c_def = self.get_user_context(title="Register")
        return dict(list(context.items()))# + list(c_def.items())
    def form_valid(self, form):
        user = form.save()
        login(self.request, user)
        return redirect('index')

class LoginUser(LoginView):
    form_class = LoginUserForm
    template_name = "main_app/login.html"

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        #c_def = self.get_user_context(title="Enter acc")
        return dict(list(context.items()))# + list(c_def.items())
    def get_success_url(self):
        return reverse_lazy('main_screen')

def logout_user(request):
    logout(request)
    return redirect('index')

def check_today_yo(form, today):
    return form.pub_day == today

def clean_auxiliary_data(today):
    for i in Target.objects.all():
        if i.auxiliary:
            i.delete()
        if (today - i.pub_day).days > 3 and i.is_repeat == 0:
            i.delete()

def check_day_form(form, today):
    date = form.pub_day
    difference_between_two_days = today - date
    for _ in range(difference_between_two_days.days):
        date += datetime.timedelta(days=form.repeat_every)
        if date == today:
            new_form = Target.objects.create(text=form.text, day_to_beat=today, time_to_beat=form.time_to_beat, is_done=0, is_great=form.is_great, is_repeat=form.is_repeat, repeat_every=form.repeat_every, pub_date=form.pub_date, pub_day=form.pub_day, auxiliary=1)
            new_form.save()
            return [1, new_form]
    return [0]
def settings(request):
    return render(request, "main_app/settings.html", {})

def delete_item(request, task_id):
    goodbye = Target.objects.get(pk=task_id)
    goodbye.delete()
    return redirect('main_screen')

def end_task(request, task_id):
    task_end = Target.objects.get(pk=task_id)
    task_end.is_done = 1
    task_end.save()
    return redirect('main_screen')

def main_screen_yo(request):
    today = datetime.date.today()
    clean_auxiliary_data(today)
    latest_targets_list = Target.objects.order_by("-pub_date")
    if request.method == 'POST':
        form = AddTargetForm(request.POST)
        if form.is_valid():
            #print('сохранена цель')
            try:
                Target.objects.create(**form.cleaned_data)
                return redirect('main_screen')
            except:
                form.add_error(None, 'Error detected check')
    else:
        form = AddTargetForm()
    list_today_tasks = []
    list_tomorrow_tasks = []
    list_great_task = []
    tomorrow = datetime.date.today() + datetime.timedelta(days=1)
    for i in latest_targets_list:
        today_date_yo = check_day_form(i, today)
        tomorrow_date_yo = check_day_form(i, tomorrow)
        if check_today_yo(i, today):
            list_today_tasks.append(i)
        if today_date_yo[0]:
            list_today_tasks.append(today_date_yo[1])
        if tomorrow_date_yo[0]:
            list_tomorrow_tasks.append(tomorrow_date_yo[1])
        if i.is_great:
            list_great_task.append(i)
    context = {
        'random_great_task': choice(list_great_task),
        'list_great_tasks': list_great_task,
        'form': form,
        'today_tasks': list_today_tasks,
        'tomorrow_tasks': list_tomorrow_tasks,
        'latest_targets_list': latest_targets_list,
        'today': today.strftime('%A %d %B %Y'),
        'current_time': str(datetime.datetime.now().time()),
        'tomorrow': tomorrow.strftime('%A %d %B %Y'),
        'today_co': datetime.date.today(),
        'tomorrow_co': datetime.date.today() + datetime.timedelta(days=1),
    }
    return render(request, "main_app/main_screen.html", context)


import json
import os

import jsonschema

image_schema = {
    "type": "object",
    "properties": {"file_name": {"type": "string"}, "id": {"type": "integer"}},
    "required": ["file_name", "id"],
}

segmentation_schema = {
    "type": "array",
    "items": {
        "type": "array",
        "items": {
            "type": "number",
        },
        "additionalItems": False,
    },
    "additionalItems": False,
}

annotation_schema = {
    "type": "object",
    "properties": {
        "image_id": {"type": "integer"},
        "category_id": {"type": "integer"},
        "segmentation": segmentation_schema,
    },
    "required": ["image_id", "category_id", "segmentation"],
}

category_schema = {
    "type": "object",
    "properties": {"name": {"type": "string"}, "id": {"type": "integer"}},
    "required": ["name", "id"],
}

coco_schema = {
    "type": "object",
    "properties": {
        "images": {"type": "array", "items": image_schema, "additionalItems": False},
        "annotations": {
            "type": "array",
            "items": annotation_schema,
            "additionalItems": False,
        },
        "categories": {
            "type": "array",
            "items": category_schema,
            "additionalItems": False,
        },
    },
    "required": ["images", "annotations", "categories"],
}

def read_and_validate_coco_annotation(coco_annotation_path: str) -> (dict, bool):
    """
    Reads coco formatted annotation file and validates its fields.
    """
    try:
        with open(coco_annotation_path) as json_file:
            coco_dict = json.load(json_file)
        jsonschema.validate(coco_dict, coco_schema)
        response = True
    except jsonschema.exceptions.ValidationError as e:
        print("well-formed but invalid JSON:", e)
        response = False
    except json.decoder.JSONDecodeError as e:
        print("poorly-formed text, not JSON:", e)
        response = False

    return coco_dict, response


import requests
import json
from requests.auth import HTTPBasicAuth
import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

class Pagerdutyincident:

    def __init__(self, email,  api_key, service_id):
        self.__email = email
        self.__api_key = api_key
        self.__service_id = service_id

    # Creating new incident
    def create_incident(self, data):
        headers = {"Accept": "application/json",
                    "Content-Type": "application/json",
                    "From": self.__email ,
                    "Authorization" : "Token token={}".format( self.__api_key)
                    }
        payload =  {
            "incident": {
            "type": "incident",
            "title": "Overallscore.",
            "service": {
            "id": self.__service_id,
            "type": "service_reference"
            },
            "body":{
                "type":"incident_body",
                "details":data
            }
         }
        }
        try:
            url = "https://api.pagerduty.com/incidents"
            request = requests.post(url, json.dumps(payload), headers=headers)

            if request.status_code == 201:
                return request

            raise ValueError("Received invalid response {} with status code {}".format(
                request.content, request.status_code))
        except Exception as e:
            logger.error("Unexpected Exception occured:  %s ", e)
            return e


import os
from torchvision import transforms
import torch.utils.data as data
from utils.core_utils import is_image_file
from PIL import Image

# Custom dataset
class custom_ds( data.Dataset):
    def __init__( self, ImPath, preprocess,
                  samples= None):
        super( custom_ds, self).__init__()
        self.ImPath= ImPath
        self.image_list= [ os.path.join( root, name)
                           for root, dirs, files in os.walk( self.ImPath)
                           for name in files
                           if is_image_file( name)]

        # Keep first samples
        if samples is not None:
            self.image_list= self.image_list[ :samples]
        self.ImTransform= preprocess # set preprocessing

    def __getitem__( self, index):
        # Get image
        ImgPath= self.image_list[ index]
        Img= self.ImTransform( Image.open( ImgPath).convert( 'RGB')) # resize
        fname= self.image_list[ index].rsplit( "/", 2)[ -1].rsplit( ".", 2)[ 0] # get filename
        return Img, fname

    def __len__( self):
        return len( self.image_list)

# Generic transformations
def gen_transform(mode,init_dim,crop_dim=224,
                  model_config="train",final_dim=None,rf_pad=None,
                  rf_crop01=None,rf_crop02=None,rf_full_dim=None):
    # Check model_config
    if model_config not in ( "train", "predict"):
        raise ValueError( "Undefined model configuration.\
                          Check the 'model_config' argument.")
    if mode== "skip":
        # No transformation applied.
        norm_flag= True
        transf= transforms.ToTensor()
    elif mode== "resize":
        # Resize
        norm_flag= False
        if model_config== "train":
            # Final scaling applied by training routine
            transf= transforms.Compose([ transforms.Resize( ( init_dim, init_dim)),
                                         transforms.ToTensor(),])
        else:
            transf= transforms.Compose([ transforms.Resize( ( init_dim, init_dim)),
                                         transforms.Resize( ( final_dim, final_dim)),
                                         transforms.ToTensor(),])
    elif mode== "resize_norm":
        # Resize and normalize/scale
        norm_flag= True
        if final_dim is not None:
            transf= transforms.Compose([ transforms.Resize(( init_dim, init_dim)),
                                         transforms.Resize(( final_dim, final_dim)),
                                         transforms.ToTensor(),])
        else:
            transf= transforms.Compose([ transforms.Resize(( init_dim, init_dim)),
                                         transforms.ToTensor(),])
    elif mode== "resize_crop_norm":
        # Resize, crop and normalize/scale
        norm_flag= True
        if final_dim is not None:
            transf= transforms.Compose([ transforms.Resize(( init_dim, init_dim)),
                                         transforms.Resize(( final_dim, final_dim)),
                                         transform.CenterCrop((crop_dim,crop_dim)),
                                         transforms.ToTensor(),])
        else:
            transf= transforms.Compose([ transforms.Resize(( init_dim, init_dim)),
                                         transforms.CenterCrop((crop_dim,crop_dim)),
                                         transforms.ToTensor(),])
    else:
        raise ValueError( "Wrong input transformations. Check 'mode' input argument.")
    return transf, norm_flag


import asyncio
import sys
import traceback
from datetime import datetime, timedelta

import aiohttp
import pnwkit
from discord.ext import tasks
from discord.utils import sleep_until

from ...data.db import execute_query_many, execute_read_query
from ...env import APIKEY, GQL_URL, UPDATE_TIMES
from ...events import dispatch

query = """
    id
    date
    reason
    war_type
    groundcontrol
    airsuperiority
    navalblockade
    winner
    turnsleft
    attid
    att_alliance_id
    defid
    def_alliance_id
    attpoints
    defpoints
    attpeace
    defpeace
    att_resistance
    def_resistance
    att_fortify
    def_fortify
    att_gas_used
    def_gas_used
    att_mun_used
    def_mun_used
    att_alum_used
    def_alum_used
    att_steel_used
    def_steel_used
    att_infra_destroyed
    def_infra_destroyed
    att_money_looted
    def_money_looted
    att_soldiers_killed
    def_soldiers_killed
    att_tanks_killed
    def_tanks_killed
    att_aircraft_killed
    def_aircraft_killed
    att_ships_killed
    def_ships_killed
    att_missiles_used
    def_missiles_used
    att_nukes_used
    def_nukes_used
    att_infra_destroyed_value
    def_infra_destroyed_value
"""
attack_query = """
    {
        wars(active: false, days_ago: 7) {
            id
            attacks {
                id
                date
                type
                victor
                success
                attcas1
                defcas1
                attcas2
                defcas2
                cityid
                infradestroyed
                improvementslost
                moneystolen
                loot_info
                resistance_eliminated
                city_infra_before
                infra_destroyed_value
                att_mun_used
                def_mun_used
                att_gas_used
                def_gas_used
            }
        }
    }
"""

async def request():
    async with aiohttp.request("POST", GQL_URL, json={"query": query}) as response:
        return await response.json()

async def request2():
    async with aiohttp.request(
        "POST",
        GQL_URL,
        json={
            "query": query.replace(
                "active: true, days_ago: 6", "active: false, days_ago: 1"
            )
        },
    ) as response:
        return await response.json()

async def request3(min_war_attack_id):
    async with aiohttp.request(
        "GET",
        f"https://politicsandwar.com/api/war-attacks/key={APIKEY}&min_war_attack_id={min_war_attack_id}",
    ) as response:
        return await response.json()

async def request4():
    async with aiohttp.request(
        "POST",
        GQL_URL,
        json={
            "query": attack_query.replace(
                "active: true, days_ago: 6", "active: false, days_ago: 1"
            )
        },
    ) as response:
        return await response.json()

@tasks.loop(minutes=2)
async def fetch_wars():
    try:
        min_war_attack_id = (await execute_read_query("SELECT max(id) FROM attacks;"))[
            0
        ][0]
        min_war_id = (
            await execute_read_query(
                "SELECT min(id) FROM wars WHERE date >= $1;",
                str(datetime.utcnow() - timedelta(days=7)),
            )
        )[0][0]
        time = datetime.utcnow()
        attacks = await request3(min_war_attack_id)
        # data2 = data2["data"]["wars"]
        # data = [*data, *data2]
        attacks = attacks["war_attacks"]
        # data4 = data4["data"]["wars"]
        # data3 = [*data3, *data4]
        wars = {
            int(war["id"]): {
                "id": int(war["id"]),
                "date": war["date"],
                "reason": war["reason"],
                "war_type": war["war_type"],
                "active": True,
                "ground_control": int(war["groundcontrol"]),
                "air_superiority": int(war["airsuperiority"]),
                "naval_blockade": int(war["navalblockade"]),
                "winner": int(war["winner"]),
                "turns_left": int(war["turnsleft"]),
                "attacker_id": int(war["attid"]),
                "attacker_alliance_id": int(war["att_alliance_id"]),
                "defender_id": int(war["defid"]),
                "defender_alliance_id": int(war["def_alliance_id"]),
                "attacker_points": int(war["attpoints"]),
                "defender_points": int(war["defpoints"]),
                "attacker_peace": war["attpeace"],
                "defender_peace": war["defpeace"],
                "attacker_resistance": int(war["att_resistance"]),
                "defender_resistance": int(war["def_resistance"]),
                "attacker_fortify": war["att_fortify"],
                "defender_fortify": war["def_fortify"],
                "attacker_gasoline_used": float(war["att_gas_used"]),
                "defender_gasoline_used": float(war["def_gas_used"]),
                "attacker_munitions_used": float(war["att_mun_used"]),
                "defender_munitions_used": float(war["def_mun_used"]),
                "attacker_aluminum_used": int(war["att_alum_used"]),
                "defender_aluminum_used": int(war["def_alum_used"]),
                "attacker_steel_used": int(war["att_steel_used"]),
                "defender_steel_used": int(war["def_steel_used"]),
                "attacker_infra_destroyed": float(war["att_infra_destroyed"]),
                "defender_infra_destroyed": float(war["def_infra_destroyed"]),
                "attacker_money_looted": float(war["att_money_looted"]),
                "defender_money_looted": float(war["def_money_looted"]),
                "attacker_soldiers_killed": int(war["att_soldiers_killed"]),
                "defender_soldiers_killed": int(war["def_soldiers_killed"]),
                "attacker_tanks_killed": int(war["att_tanks_killed"]),
                "defender_tanks_killed": int(war["def_tanks_killed"]),
                "attacker_aircraft_killed": int(war["att_aircraft_killed"]),
                "defender_aircraft_killed": int(war["def_aircraft_killed"]),
                "attacker_ships_killed": int(war["att_ships_killed"]),
                "defender_ships_killed": int(war["def_ships_killed"]),
                "attacker_missiles_used": int(war["att_missiles_used"]),
                "defender_missiles_used": int(war["def_missiles_used"]),
                "attacker_nukes_used": int(war["att_nukes_used"]),
                "defender_nukes_used": int(war["def_nukes_used"]),
                "attacker_infra_destroyed_value": float(
                    war["att_infra_destroyed_value"]
                ),
                "defender_infra_destroyed_value": float(
                    war["def_infra_destroyed_value"]
                ),
            }
            async for war in pnwkit.async_war_query(
                {"min_id": min_war_id}, query, paginator=True
            ).batch(5)
        }
        attacks = {
            int(attack["war_attack_id"]): {
                "id": int(attack["war_attack_id"]),
                "war_id": int(attack["war_id"]),
                "date": attack["date"],
                "attack_type": attack["attack_type"],
                "victor": int(attack["victor"]),
                "success": int(attack["success"]),
                "attcas1": int(attack["attcas1"]),
                "defcas1": int(attack["defcas1"]),
                "attcas2": int(attack["attcas2"]),
                "defcas2": int(attack["defcas2"]),
                "city_id": int(attack["city_id"]),
                "infra_destroyed": float(attack["infra_destroyed"]),
                "improvements_destroyed": int(attack["improvements_destroyed"]),
                "money_looted": float(attack["money_looted"]),
                "loot_info": attack["note"] if not attack["note"].isdigit() else None,
                "resistance_eliminated": int(attack["note"])
                if attack["note"].isdigit()
                else None,
                "city_infra_before": float(attack["city_infra_before"]),
                "infra_destroyed_value": float(attack["infra_destroyed_value"]),
                "attacker_munitions_used": float(attack["att_mun_used"]),
                "defender_munitions_used": float(attack["def_mun_used"]),
                "attacker_gasoline_used": float(attack["att_gas_used"]),
                "defender_gasoline_used": float(attack["def_gas_used"]),
                "aicraft_killed_by_tanks": int(attack["aircraft_killed_by_tanks"])
                if attack["aircraft_killed_by_tanks"] is not None
                else None,
            }
            for attack in attacks
        }
        attack_data = {}
        war_data = {}
        old_wars = await execute_read_query(
            "SELECT * FROM wars WHERE id >= $1;", min(wars)
        )
        old_wars = [dict(i) for i in old_wars]
        old_wars = {i["id"]: i for i in old_wars}
        attack_dispatches = []
        for attack in attacks.values():
            attack_dispatches.append(attacks[attack["id"]])
            attack_data[attack["id"]] = attack
        declaration_dispatches = []
        updated_dispatches = []
        for after in wars.values():
            try:
                before = dict(old_wars[after["id"]])
                if before != after:
                    updated_dispatches.append(
                        {"before": old_wars[after["id"]], "after": wars[after["id"]]}
                    )
                    war_data[after["id"]] = after
                del old_wars[after["id"]]
            except KeyError:
                declaration_dispatches.append(wars[after["id"]])
                war_data[after["id"]] = after
        await execute_query_many(
            """
            INSERT INTO wars (id, date, reason, war_type, active, ground_control,
            air_superiority, naval_blockade, winner, turns_left, attacker_id,
            attacker_alliance_id, defender_id, defender_alliance_id, attacker_points,
            defender_points, attacker_peace, defender_peace, attacker_resistance,
            defender_resistance, attacker_fortify, defender_fortify, attacker_gasoline_used,
            defender_gasoline_used, attacker_munitions_used, defender_munitions_used,
            attacker_aluminum_used, defender_aluminum_used, attacker_steel_used,
            defender_steel_used, attacker_infra_destroyed, defender_infra_destroyed,
            attacker_money_looted, defender_money_looted, attacker_soldiers_killed,
            defender_soldiers_killed, attacker_tanks_killed, defender_tanks_killed,
            attacker_aircraft_killed, defender_aircraft_killed, attacker_ships_killed,
            defender_ships_killed, attacker_missiles_used, defender_missiles_used,
            attacker_nukes_used, defender_nukes_used, attacker_infra_destroyed_value,
            defender_infra_destroyed_value) VALUES ($1, $2, $3, $4, $5, $6, $7, $8,
            $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23,
            $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38,
            $39, $40, $41, $42, $43, $44, $45, $46, $47, $48) ON CONFLICT (id) DO UPDATE SET
            id = $1,
            date = $2,
            reason = $3,
            war_type = $4,
            active = $5,
            ground_control = $6,
            air_superiority = $7,
            naval_blockade = $8,
            winner = $9,
            turns_left = $10,
            attacker_id = $11,
            attacker_alliance_id = $12,
            defender_id = $13,
            defender_alliance_id = $14,
            attacker_points = $15,
            defender_points = $16,
            attacker_peace = $17,
            defender_peace = $18,
            attacker_resistance = $19,
            defender_resistance = $20,
            attacker_fortify = $21,
            defender_fortify = $22,
            attacker_gasoline_used = $23,
            defender_gasoline_used = $24,
            attacker_munitions_used = $25,
            defender_munitions_used = $26,
            attacker_aluminum_used = $27,
            defender_aluminum_used = $28,
            attacker_steel_used = $29,
            defender_steel_used = $30,
            attacker_infra_destroyed = $31,
            defender_infra_destroyed = $32,
            attacker_money_looted = $33,
            defender_money_looted = $34,
            attacker_soldiers_killed = $35,
            defender_soldiers_killed = $36,
            attacker_tanks_killed = $37,
            defender_tanks_killed = $38,
            attacker_aircraft_killed = $39,
            defender_aircraft_killed = $40,
            attacker_ships_killed = $41,
            defender_ships_killed = $42,
            attacker_missiles_used = $43,
            defender_missiles_used = $44,
            attacker_nukes_used = $45,
            defender_nukes_used = $46,
            attacker_infra_destroyed_value = $47,
            defender_infra_destroyed_value = $48;
        """,
            [tuple(i.values()) for i in war_data.values()],
        )
        await execute_query_many(
            """
            INSERT INTO attacks (id, war_id, date, type, victor, success, attcas1,
            defcas1, attcas2, defcas2, city_id, infra_destroyed, improvements_lost,
            money_stolen, loot_info, resistance_eliminated, city_infra_before,
            infra_destroyed_value, attacker_munitions_used, defender_munitions_used,
            attacker_gasoline_used, defender_gasoline_used, aircraft_killed_by_tanks) VALUES
            ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16,
            $17, $18, $19, $20, $21, $22, $23)
            ON CONFLICT (id) DO NOTHING;
        """,
            [tuple(i.values()) for i in attack_data.values()],
        )
        await UPDATE_TIMES.set_wars(time)
        if attack_dispatches:
            await dispatch("bulk_attack", str(time), data=attack_dispatches)
        if declaration_dispatches:
            await dispatch("bulk_war_create", str(time), data=declaration_dispatches)
        if updated_dispatches:
            await dispatch(
                "bulk_war_update",
                str(time),
                data=updated_dispatches,
            )
    except Exception as error:
        print("Ignoring exception in wars:", file=sys.stderr, flush=True)
        traceback.print_exception(
            type(error), error, error.__traceback__, file=sys.stderr
        )

@fetch_wars.before_loop
async def before_loop():
    now = datetime.utcnow()
    wait = now.replace(minute=0, second=8)
    while wait < now:
        wait += timedelta(minutes=2)
    await sleep_until(wait)

fetch_wars.add_exception_type(Exception)
fetch_wars.start()


from __future__ import annotations

import logging
import time
from typing import Optional

from chia.protocols import timelord_protocol
from chia.rpc.rpc_server import StateChangedProtocol
from chia.timelord.iters_from_block import iters_from_block
from chia.timelord.timelord import Timelord
from chia.timelord.types import Chain, IterationType
from chia.util.api_decorators import api_request
from chia.util.ints import uint64

log = logging.getLogger(__name__)

class TimelordAPI:
    log: logging.Logger
    timelord: Timelord

    def __init__(self, timelord) -> None:
        self.log = logging.getLogger(__name__)
        self.timelord = timelord

    def ready(self) -> bool:
        return True

    def _set_state_changed_callback(self, callback: StateChangedProtocol) -> None:
        self.timelord.state_changed_callback = callback

    @api_request()
    async def new_peak_timelord(self, new_peak: timelord_protocol.NewPeakTimelord) -> None:
        if self.timelord.last_state is None:
            return None
        async with self.timelord.lock:
            if self.timelord.bluebox_mode:
                return None
            self.timelord.max_allowed_inactivity_time = 60

            # if there is a heavier unfinished block from a diff chain, skip
            for unf_block in self.timelord.unfinished_blocks:
                if unf_block.reward_chain_block.total_iters > new_peak.reward_chain_block.total_iters:
                    found = False
                    for rc, total_iters in new_peak.previous_reward_challenges:
                        if rc == unf_block.rc_prev:
                            found = True
                            break

                    if not found:
                        log.info("there is a heavier unfinished block that does not belong to this chain- skip peak")
                        return None

            if new_peak.reward_chain_block.weight > self.timelord.last_state.get_weight():
                log.info("Not skipping peak, don't have. Maybe we are not the fastest timelord")
                log.info(
                    f"New peak: height: {new_peak.reward_chain_block.height} weight: "
                    f"{new_peak.reward_chain_block.weight} "
                )
                self.timelord.new_peak = new_peak
                self.timelord.state_changed("new_peak", {"height": new_peak.reward_chain_block.height})
            elif (
                self.timelord.last_state.peak is not None
                and self.timelord.last_state.peak.reward_chain_block == new_peak.reward_chain_block
            ):
                log.info("Skipping peak, already have.")
                self.timelord.state_changed("skipping_peak", {"height": new_peak.reward_chain_block.height})
            else:
                log.warning("block that we don't have, changing to it.")
                self.timelord.new_peak = new_peak
                self.timelord.state_changed("new_peak", {"height": new_peak.reward_chain_block.height})

    @api_request()
    async def new_unfinished_block_timelord(self, new_unfinished_block: timelord_protocol.NewUnfinishedBlockTimelord):
        if self.timelord.last_state is None:
            return None
        async with self.timelord.lock:
            if self.timelord.bluebox_mode:
                return None
            try:
                sp_iters, ip_iters = iters_from_block(
                    self.timelord.constants,
                    new_unfinished_block.reward_chain_block,
                    self.timelord.last_state.get_sub_slot_iters(),
                    self.timelord.last_state.get_difficulty(),
                    self.timelord.get_height(),
                )
            except Exception:
                return None
            last_ip_iters = self.timelord.last_state.get_last_ip()
            if sp_iters > ip_iters:
                self.timelord.overflow_blocks.append(new_unfinished_block)
                log.debug(f"Overflow unfinished block, total {self.timelord.total_unfinished}")
            elif ip_iters > last_ip_iters:
                new_block_iters: Optional[uint64] = self.timelord._can_infuse_unfinished_block(new_unfinished_block)
                if new_block_iters:
                    self.timelord.unfinished_blocks.append(new_unfinished_block)
                    for chain in [Chain.REWARD_CHAIN, Chain.CHALLENGE_CHAIN]:
                        self.timelord.iters_to_submit[chain].append(new_block_iters)
                    if self.timelord.last_state.get_deficit() < self.timelord.constants.MIN_BLOCKS_PER_CHALLENGE_BLOCK:
                        self.timelord.iters_to_submit[Chain.INFUSED_CHALLENGE_CHAIN].append(new_block_iters)
                    self.timelord.iteration_to_proof_type[new_block_iters] = IterationType.INFUSION_POINT
                    self.timelord.total_unfinished += 1
                    log.debug(f"Non-overflow unfinished block, total {self.timelord.total_unfinished}")

    @api_request()
    async def request_compact_proof_of_time(self, vdf_info: timelord_protocol.RequestCompactProofOfTime):
        async with self.timelord.lock:
            if not self.timelord.bluebox_mode:
                return None
            now = time.time()
            # work older than 5s can safely be assumed to be from the previous batch, and needs to be cleared
            while self.timelord.pending_bluebox_info and (now - self.timelord.pending_bluebox_info[0][0] > 5):
                del self.timelord.pending_bluebox_info[0]
            self.timelord.pending_bluebox_info.append((now, vdf_info))


import pygame # import the pygame library
from pygame.locals import * # provides constant variables like QUIT
import sys # commonly used library in Python. We use it to end the program.

pygame.init() # needed for other pygame functions to work
pygame.display.set_mode((640, 480)) # sets up a window with 640x480 dimensions

while True: # main game loop
   for event in pygame.event.get(): # get events and iterate through them
       if event.type == QUIT: # if user clicks exit button
           pygame.quit() # Deactivates the pygame library
           sys.exit() # ends the whole program


"""empty message

Revision ID: c248c9929c7b
Revises: d217cbb30d01
Create Date: 2019-02-19 20:58:20.595368

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'c248c9929c7b'
down_revision = 'd217cbb30d01'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('test', sa.Column('reference_date', sa.String(length=120), nullable=True))
    op.create_index(op.f('ix_test_reference_date'), 'test', ['reference_date'], unique=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_test_reference_date'), table_name='test')
    op.drop_column('test', 'reference_date')
    # ### end Alembic commands ###


from __future__ import annotations

import logging
from typing import List, Tuple

from chia.types.coin_spend import CoinSpend
from chia.util.db_wrapper import DBWrapper2
from chia.util.ints import uint32

log = logging.getLogger(__name__)

class WalletPoolStore:
    db_wrapper: DBWrapper2

    @classmethod
    async def create(cls, wrapper: DBWrapper2):
        self = cls()
        self.db_wrapper = wrapper

        async with self.db_wrapper.writer_maybe_transaction() as conn:
            await conn.execute(
                "CREATE TABLE IF NOT EXISTS pool_state_transitions("
                " transition_index integer,"
                " wallet_id integer,"
                " height bigint,"
                " coin_spend blob,"
                " PRIMARY KEY(transition_index, wallet_id))"
            )

        return self

    async def add_spend(
        self,
        wallet_id: int,
        spend: CoinSpend,
        height: uint32,
    ) -> None:
        """
        Appends (or replaces) entries in the DB. The new list must be at least as long as the existing list, and the
        parent of the first spend must already be present in the DB. Note that this is not committed to the DB
        until db_wrapper.commit() is called. However it is written to the cache, so it can be fetched with
        get_all_state_transitions.
        """
        async with self.db_wrapper.writer_maybe_transaction() as conn:
            # find the most recent transition in wallet_id
            rows = list(
                await conn.execute_fetchall(
                    "SELECT transition_index, height, coin_spend "
                    "FROM pool_state_transitions "
                    "WHERE wallet_id=? "
                    "ORDER BY transition_index DESC "
                    "LIMIT 1",
                    (wallet_id,),
                )
            )
            serialized_spend = bytes(spend)
            if len(rows) == 0:
                transition_index = 0
            else:
                existing = list(
                    await conn.execute_fetchall(
                        "SELECT COUNT(*) "
                        "FROM pool_state_transitions "
                        "WHERE wallet_id=? AND height=? AND coin_spend=?",
                        (wallet_id, height, serialized_spend),
                    )
                )
                if existing[0][0] != 0:
                    # we already have this transition in the DB
                    return

                row = rows[0]
                if height < row[1]:
                    raise ValueError("Height cannot go down")
                prev = CoinSpend.from_bytes(row[2])
                if spend.coin.parent_coin_info != prev.coin.name():
                    raise ValueError("New spend does not extend")
                transition_index = row[0]

            cursor = await conn.execute(
                "INSERT OR IGNORE INTO pool_state_transitions VALUES (?, ?, ?, ?)",
                (
                    transition_index + 1,
                    wallet_id,
                    height,
                    serialized_spend,
                ),
            )
            await cursor.close()

    async def get_spends_for_wallet(self, wallet_id: int) -> List[Tuple[uint32, CoinSpend]]:
        """
        Retrieves all entries for a wallet ID.
        """

        async with self.db_wrapper.reader_no_transaction() as conn:
            rows = await conn.execute_fetchall(
                "SELECT height, coin_spend FROM pool_state_transitions WHERE wallet_id=? ORDER BY transition_index",
                (wallet_id,),
            )
        return [(uint32(row[0]), CoinSpend.from_bytes(row[1])) for row in rows]

    async def rollback(self, height: int, wallet_id_arg: int) -> None:
        """
        Rollback removes all entries which have entry_height > height passed in. Note that this is not committed to the
        DB until db_wrapper.commit() is called. However it is written to the cache, so it can be fetched with
        get_all_state_transitions.
        """

        async with self.db_wrapper.writer_maybe_transaction() as conn:
            cursor = await conn.execute(
                "DELETE FROM pool_state_transitions WHERE height>? AND wallet_id=?", (height, wallet_id_arg)
            )
            await cursor.close()

    async def delete_wallet(self, wallet_id: uint32) -> None:
        async with self.db_wrapper.writer_maybe_transaction() as conn:
            cursor = await conn.execute("DELETE FROM pool_state_transitions WHERE wallet_id=?", (wallet_id,))
            await cursor.close()


# -*- coding:utf-8 -*-
import xgboost as xgb
from sklearn.metrics import f1_score

def val_predict_prob(bst, val_x, val_y):
    dval = xgb.DMatrix(val_x)
    prob = bst.predict(dval)
    # res = handmade_evalerror(prob, val_y)
    res = f1_score(y_true=val_y, y_pred=prob, average='weighted')
    print('f1_score is : %s' % res)

def test_predict_prob(bst, test_x):
    print("开始test预测")
    dtest = xgb.DMatrix(test_x)
    prob = bst.predict(dtest)
    return prob

def test_lgb_predict_prob(bst, test_x):
    print("开始test预测")
    prob = bst.predict(test_x)
    return prob


import discord

from bot.database import user_table, DBUser, get_db_user
from bot.msgs import templates, send

# REGISTRATION STEPS
# 0 - Already registered, is the info correct?  <== Entry point if already registered
# 1 - Prompt for first name                     <== Normal entry point
# 2 - Prompt for last name
# 3 - Prompt email
# 4 - Verify Info
# 5 - Registered!

from bot.utils.logger import info, error

async def handle_join_server(client, user: discord.Member):
    db_user = get_db_user(user)

    info("Added user to database", header=f"[{user}]")

    if db_user.registered:
        db_user.registration_step = 0
        user_table.update(db_user)
        info("User has already registered, setting registration step to 0", header=f"[{user}]")
        await step0(client, user, db_user)
    else:
        db_user.registration_step = 1
        user_table.update(db_user)
        info("User not registered, setting registration step to 1", header=f"[{user}]")
        await step1(user)

async def finish_registration(client, user: discord.User, db_user: DBUser):
    from bot.bot_client import CPUBotClient

    client: CPUBotClient

    info("Finishing user registration", header=f"[{user}]")
    db_user.registered = True
    user_table.update(db_user)

    member: discord.Member
    for member in client.guild.members:
        if member.id == user.id:
            break
    else:
        error(f"User not found in guild, cannot complete registration", header=f"[{user}]")
        return

    try:
        await member.edit(nick=f"{db_user.first_name} {db_user.last_name}")
        await member.add_roles(client.club_member_role)
    except discord.Forbidden:
        error("User registered, but bot lacks permission to edit user, are they the server owner?", header=f"[{user}]")

    await welcome_user(client, member)

async def step0(client, user: discord.User, db_user: DBUser):
    from bot.bot_client import CPUBotClient

    client: CPUBotClient

    # Create embed
    info_embed = discord.Embed(title="User Info", color=0x0000FF)
    info_embed.add_field(name="__First Name__", value=db_user.first_name)
    info_embed.add_field(name="__Last Name__", value=db_user.last_name)
    info_embed.add_field(name="__Choate Email__", value=db_user.choate_email)

    # Send message and add reactions
    message = await send(user, templates.welcome_back, embed=info_embed)
    await message.add_reaction("ðŸ‘�")
    await message.add_reaction("ðŸ‘Ž")
    info("Verification message sent, waiting for user reaction...", header=f"[{user}]")

    # Wait for user reaction
    def check(r: discord.Reaction, u: discord.User):
        return (
            r.message.id == message.id
            and r.emoji in ["ðŸ‘�", "ðŸ‘Ž"]
            and u.id != client.user.id
        )

    res = await client.wait_for("reaction_add", check=check)
    reaction: discord.reaction = res[0]
    info(f"User reacted with emoji '{reaction.emoji}'", header=f"[{user}]")

    if reaction.emoji == "ðŸ‘�":
        await message.remove_reaction("ðŸ‘�", client.user)
        await message.remove_reaction("ðŸ‘Ž", client.user)
        db_user.registered = True
        db_user.registration_step = 5
        user_table.update(db_user)
        await step5(client, user, db_user)

    elif reaction.emoji == "ðŸ‘Ž":
        await message.remove_reaction("ðŸ‘�", client.user)
        await message.remove_reaction("ðŸ‘Ž", client.user)
        db_user.registered = False
        db_user.registration_step = 1
        user_table.update(db_user)
        await send(user, templates.reset)
        await step1(user, user)

async def step1(user: discord.User, welcome=True):
    if welcome:
        await send(user, templates.new_welcome)
    await send(user, templates.first_name)

async def step1_input(user: discord.User, db_user: DBUser, first_name: str):
    info(f'User provided first name "{first_name}"', header=f"[{user}]")
    db_user.first_name = first_name
    db_user.registration_step = 2
    user_table.update(db_user)
    await step2(user, db_user)

async def step2(user: discord.User, db_user: DBUser):
    await send(user, templates.last_name.format(**locals()))

async def step2_input(user: discord.User, db_user: DBUser, last_name: str):
    info(f'User provided last name "{last_name}"', header=f"[{user}]")
    db_user.last_name = last_name
    db_user.registration_step = 3
    user_table.update(db_user)
    await step3(user, db_user)

async def step3(user: discord.User, db_user: DBUser):
    await send(user, templates.email_address.format(**locals()))

async def step3_input(client, user: discord.User, db_user: DBUser, choate_email: str):
    info(f'User provided Choate email "{choate_email}"', header=f"[{user}]")
    db_user.choate_email = choate_email
    db_user.registration_step = 4
    user_table.update(db_user)
    await step4(client, user, db_user)

async def step4(client, user: discord.User, db_user: DBUser):
    from bot.bot_client import CPUBotClient

    client: CPUBotClient

    # Create Embed
    info_embed = discord.Embed(title="User Info", color=0x0000FF)
    info_embed.add_field(name="__First Name__", value=db_user.first_name)
    info_embed.add_field(name="__Last Name__", value=db_user.last_name)
    info_embed.add_field(name="__Choate Email__", value=db_user.choate_email)

  # Nothing really happened   # Send message and add reactions
    message = await send(user,
        f"""Thanks! Is all of this info correct?""", embed=info_embed
    )
    await message.add_reaction("ðŸ‘�")
    await message.add_reaction("ðŸ‘Ž")
    info("Verification message sent", header=f"[{user}]")

    # Wait for user reaction
    def check(r: discord.Reaction, u: discord.User):
        return (
            r.message.id == message.id
            and r.emoji in ["ðŸ‘�", "ðŸ‘Ž"]
            and u.id != client.user.id
        )

    res = await client.wait_for("reaction_add", check=check)
    reaction: discord.reaction = res[0]
    info(f"User reacted with emoji '{reaction.emoji}'", header=f"[{user}]")

    if reaction.emoji == "ðŸ‘�":
        await message.remove_reaction("ðŸ‘�", client.user)
        await message.remove_reaction("ðŸ‘Ž", client.user)
        db_user.registration_step = 5
        user_table.update(db_user)
        await step5(client, user, db_user)

    elif reaction.emoji == "ðŸ‘Ž":
        await message.remove_reaction("ðŸ‘�", client.user)
        await message.remove_reaction("ðŸ‘Ž", client.user)
        await send(user, "Ok, asking for the info again.")
        info("User rejected the info, restarting at step 1", header=f"[{user}]")
        db_user.registration_step = 1
        user_table.update(db_user)
        await step1(user, welcome=False)

async def step5(client, user: discord.User, db_user: DBUser):
    from bot.bot_client import CPUBotClient

    client: CPUBotClient

    await finish_registration(client, user, db_user)
    await send(user, templates.finished_registration)
    await send(user, templates.help)

async def handle_dm(client, user: discord.User, message: discord.Message):
    db_user = get_db_user(user)

    if not db_user.registered:
        if db_user.registration_step == 1:
            await step1_input(user, db_user, message.content)
            return True
        elif db_user.registration_step == 2:
            await step2_input(user, db_user, message.content)
            return True
        elif db_user.registration_step == 3:
            await step3_input(client, user, db_user, message.content)
            return True
        elif message.content == "reset":
            db_user.registered = False
            db_user.registration_step = 1
            user_table.update(db_user)
            await step1(user)
            return True

    return False

async def welcome_user(client, member: discord.Member):
    from bot.bot_client import CPUBotClient

    client: CPUBotClient

    await client.new_members_channel.send(templates.public_welcome.format(**locals()))


import numpy as np
from matplotlib import pyplot as plt

N = 10
num_samples = 100000

mean = []
variance = []
entropy = []

def estimate_entropy(X):
    damin = np.min(X)
    damax = np.max(X)
    bins = 25
    rez = (damax - damin) / bins
    hst, _ = np.histogram(X, bins=25,range=(damin, damax))
    hst = hst / len(X) / rez
    good = hst > 0
    h = -rez * np.sum(hst[good] * np.log(hst[good]))
    return h

for n in range(1, N + 1):
    Y_n = []
    for i in range(num_samples):
        X_i = np.random.uniform(-np.sqrt(3), np.sqrt(3), size=n)
        Y = np.sum(X_i) / np.sqrt(n)
        Y_n.append(Y)

    mean_i = np.mean(Y_n)
    variance_i = np.var(Y_n)
    mean.append(mean_i)
    variance.append(variance_i)
    entropy.append(estimate_entropy(Y_n))

print(mean)
print(variance)
print(entropy)
plt.plot(range(1, N + 1), mean, marker='o', linestyle='-', label="Avg[Yn]")
plt.plot(range(1, N + 1), variance, marker='o', linestyle='-', label="Var[Yn]")
plt.plot(range(1, N + 1), entropy, marker='o', linestyle='-', label="Ent[Yn]")
plt.xlabel('Value of N')
plt.legend()
plt.show()


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

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('Sp_Projects', '__first__'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('Sp_Companies', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Project_client',
            fields=[
                ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')),
                ('client_name', models.CharField(blank=True, null=True, max_length=128, verbose_name='client_name')),
                ('client_id', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
                ('company_id', models.ForeignKey(blank=True, to='Sp_Companies.Companies', null=True)),
                ('projects_id', models.ForeignKey(unique=True, to='Sp_Projects.Projects')),
            ],
        ),
    ]


import json
class Query:
	def __init__(self, db):
		self.db = db

	""" Query the JSON with a key """
	def query_all(self, mode='DICTIONARY'):
		mode = mode.upper()
		with open(self.db,'r') as f:
			data = json.load(f)

		if mode == 'DICTIONARY':
			return data

	""" Query the JSON with a key """
	def filter_by(self, key, mode='DICTIONARY'):
		mode = mode.upper()
		with open(self.db,'r') as f:
			data = json.load(f)

		if mode == 'DICTIONARY':
			try:
				return data[key]
			except ValueError:
				return None


import pandas as pd
import numpy as np
import json
import apicalls.ontology as onto

def now_showing_rec(user_id):

    with open('../recommender/heat_movies.json') as file:
        new_data = json.load(file)

    user_profile = onto.getUserById(user_id)

    if user_profile is not None:

        feature_n_score = [[user_profile['actionScore'], 'Action'], [user_profile['comedyScore'], 'Comedy'], [user_profile['dramaScore'], 'Drama'], [user_profile['horrorScore'], 'Horror'], [user_profile['romanceScore'], 'Romance']]

        feature_n_score.sort()
        feature_n_score.reverse()
        first_three_features = feature_n_score[:2]
        print("user's",first_three_features)

        theatre_movies = new_data['intheatres']
        upcoming_movies = new_data['upcoming']
        suggesting_movies = {"intheatres": [], "upcoming": []}

        for theatre_movie in theatre_movies:
            print(theatre_movie['genres'])
            if len(np.intersect1d(theatre_movie['genres'], [i[1] for i in first_three_features])) > 0:
                suggesting_movies['intheatres'].append(theatre_movie)

        for upcoming_movie in upcoming_movies:
            print(upcoming_movie['genres'])
            if len(np.intersect1d(upcoming_movie['genres'], [i[1] for i in first_three_features])) > 0:
                suggesting_movies['upcoming'].append(upcoming_movie)

        return suggesting_movies
    else:
        return new_data

# print(now_showing_rec(17))


import webbrowser
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests
from bs4 import BeautifulSoup
from selenium.common.exceptions import TimeoutException
PATH="C:\chromedriver.exe"
driver=webdriver.Chrome(PATH)
driver.get("https://www.myntra.com/")
search=driver.find_element_by_class_name("desktop-searchBar")
search.send_keys("tshirt")
search.send_keys(Keys.RETURN)
try:
    output=WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CLASS_NAME,"results-base")))
    source=driver.page_source
    soup=BeautifulSoup(source,'lxml')
    l=soup.find_all('li',class_='product-base')
    for op in l:
        pic=op.find('img',class_='img-responsive')['src']
        inf1=op.find('h3',class_='product-brand').text
        inf2=op.find('h4',class_='product-product').text
        inf3=op.find('span',class_='product-discountedPrice').text
        inf4=op.find('span',class_='product-strike').text
        inf5=op.find('span',class_='product-discountPercentage').text
        html_content=f'
{inf1}

{inf2}

{inf3}

{inf4}

{inf5}
'
        with open("myntra.html","a") as html_file:
            html_file.write(html_content)
            print("html file created")
finally:
    driver.quit()


import os, logging, re
logger = logging.getLogger(__name__)

from ctk_cli import isCLIExecutable, listCLIExecutables, CLIModule
from mdl_writer import MDLGroup, MDLNewline, MDLComment, MDLFile, MDLInclude

SIMPLE_TYPE_MAPPING = {
    'boolean'   : 'Bool',
    'integer'   : 'Integer',
    'float'     : 'Float',
    'double'    : 'Double',
    'string'    : 'String',

    'directory' : 'String',
    'file'      : 'String',
    }

def fieldName(parameter):
    """Return field name of MeVisLab macro module that shall be used
    for the given CLI module parameter.  Usually, this is identical to
    parameter.identifier(), but for images, we strip off postfixes like
    'name' or 'filename' if present."""
    result = parameter.identifier()
    if parameter.typ == 'image':
        if result.lower().endswith('filename'):
            result = result[:-8]
        if result.lower().endswith('name'):
            result = result[:-4]
    return result

def countFields(box):
    result = 0
    for el in box:
        if isinstance(el, MDLGroup) and el.tagName == 'Field':
            result += 1
    return result

def mdlDescription(cliModule, includePanelScreenshots = True):
    """Given CLIModule instance, return tuple (defFile, scriptFile,
    mlabFile, mhelpFile) containing a MeVisLab macro module
    definition.  The elements are MDLFile instances that can be
    converted into strings using their mdl() methods.  The .def file
    references the .script file in the same directory, and the
    mhelpFile should be placed in a subdirectory named 'mhelp' (as
    usual)."""

    moduleName = "CLI_" + cliModule.name

    defFile = MDLFile()
    scriptFile = MDLFile()
    mlabFile = MDLFile()
    mhelpFile = MDLFile()

    mlabFile.append(MDLComment('MDL v1 utf8'))

    # MacroModule definition & documentation
    definition = defFile.addGroup("MacroModule", moduleName)

    doc = mhelpFile.addGroup("ModuleHelp")
    docMeta = doc.addGroup("MetaInformation")
    docMeta.addTag(moduleName = moduleName)
    docMeta.addTag(moduleType = 'MacroModule')

    comment = cliModule.title
    docPurpose = cliModule.title
    if cliModule.version:
        comment += " v%s" % cliModule.version
        docPurpose += " (Version %s)" % cliModule.version
    if cliModule.description:
        comment += " - " + cliModule.description
        docPurpose += "\n%s\n\n%s\n" % ('-'*len(docPurpose), cliModule.description.rstrip())
    else:
        docPurpose += "\n"

    docUsage = """:module:`this` wraps a CLI module, which means that its execution (i.e. pressing :field:`update`) will save temporary files to disk, call the CLI executable behind the scenes, and load the results provided by it.  Compared with native MeVisLab modules, you will get limited feedback during execution, and the additional saving/loading of images introduces an additional cost (depending on the speed of your machine and I/O within the temporary directory).

This documentation is extracted from the CLI module's self-description."""

    if cliModule.documentation_url:
        url = cliModule.documentation_url
        if not url.startswith('http'):
            logger.warning("%r has a bad documentation url (%r)" % (cliModule.name, url))
        else:
            docUsage += " *Additional documentation* is provided at the following URL: %s\n" % (url, )

    if cliModule.acknowledgements:
        docPurpose += "\nAcknowledgements\n----------------\n\n%s\n" % (
            cliModule.acknowledgements.strip(), )

    if cliModule.license:
        docPurpose += "\nLicense\n-------\n\n%s\n" % (
            cliModule.license.strip(), )

    definition.addTag(comment = comment)

    if cliModule.contributor:
        authors = re.sub(r' *\([^)]*\)', '', cliModule.contributor)
        authors = ", ".join(
            author for author in re.split(r' *, *(?:and *)?| +and +', authors)
            if not author.startswith('http://') or re.search('@| -at- ', author))
        definition.addTag(author = authors)
        docMeta.addTag(author = authors)

    if cliModule.category:
        keywords = "CLI " + cliModule.category.replace('.', ' ')
        definition.addTag(keywords = keywords)
        docMeta.addTag(keywords = keywords)

    definition.addTag(externalDefinition = "$(LOCAL)/%s.script" % cliModule.name)

    # mhelp structure (mhelp parser needs a lot of empty groups/tags)
    doc.addGroup('Purpose').addTag(text = docPurpose)
    doc.addGroup('Usage').addTag(text = docUsage)
    doc.addGroup('Details').addTag(text = "")
    doc.addGroup('Interaction').addTag(text = "")
    doc.addGroup('Tips').addTag(text = "")

    if includePanelScreenshots:
        windows = doc.addGroup('Windows').addTag(text = "")
        for title in ('CLI GUI', ): # 'Execution Debugging'
            windows.addGroup('Window', title) \
              .addTag(title = "") \
              .addTag(text = ".. screenshot:: %s" % title)

    inputsDoc = doc.addGroup("Inputs")
    outputsDoc = doc.addGroup("Outputs")
    parametersDoc = doc.addGroup("Parameters")

    # Interface section
    interface = scriptFile.addGroup("Interface")

    inputsSection = MDLGroup("Inputs")
    outputsSection = MDLGroup("Outputs")
    parametersSection = MDLGroup("Parameters")

    networkPanel = scriptFile.addGroup("NetworkPanel")
    networkPanel.addGroup('Button', 'update')

    # Commands section
    scriptFile.append(MDLNewline)
    commands = scriptFile.addGroup("Commands")

    commands.addTag(source = '$(LOCAL)/../CLIModuleBackend.py')
    commands.append(MDLNewline)

    commands.addTag(initCommand = 'checkCLI')
    commands.addTag(finalizeCommand = 'cleanupTemporaryFiles')
    commands.append(MDLNewline)

    commands.addGroup('FieldListener', 'update') \
        .addTag(command = 'update')

    autoApplyListener = commands.addGroup('FieldListener', 'autoApply')
    autoUpdateListener = commands.addGroup('FieldListener', 'autoUpdate')

    # transform parameters
    xInput = xOutput = 0
    for parameter in cliModule.parameters():
        parameterFieldName = fieldName(parameter)
        ioModuleName = parameterFieldName
        field = MDLGroup("Field", parameterFieldName)
        fieldDoc = MDLGroup("Field", parameterFieldName)

        if parameter.typ == "image":
            if parameter.channel not in ('input', 'output'):
                logger.warning("image parameter (%r) has invalid channel (%r), don't know how to handle this!" % (
                        parameter.identifier(), parameter.channel))
                continue

            ioFields = MDLGroup("fields")
            ioFields.addTag(instanceName = ioModuleName)
            if parameter.channel == "input":
                inputsSection.append(field)
                inputsDoc.append(fieldDoc)

                field.addTag(internalName = "%s.input0" % ioModuleName)
                module = MDLGroup("module", "itkImageFileWriter")
                ioFields.addTag(forceDirectionCosineWrite = True)
                x, y = xInput, 160
                xInput += 200

                autoUpdateListener.addTag(listenField = parameterFieldName)
            else:
                assert parameter.channel == "output"
                outputsSection.append(field)
                outputsDoc.append(fieldDoc)

                field.addTag(internalName = "%s.output0" % ioModuleName)
                module = MDLGroup("module", "itkImageFileReader")
                ioFields.addTag(autoDetermineDataType = True)
                x, y = xOutput, 0
                xOutput += 200

            # add reader/writer module to network:
            module.addGroup("internal") \
                .addTag(frame = "%d %d 120 64" % (x, y))
            ioFields.addTag(correctSubVoxelShift = True)
            module.append(ioFields)
            mlabFile.append(module)

            fieldDoc.addTag(type_ = 'Image')
        else:
            if parameter.typ in SIMPLE_TYPE_MAPPING:
                field.addTag(type_ = SIMPLE_TYPE_MAPPING[parameter.typ])
            elif parameter.typ.endswith("-vector"):
                field.addTag(type_ = 'String')
            elif parameter.typ.endswith("-enumeration"):
                field.addTag(type_ = 'Enum')
                items = field.addGroup("items")
                for item in parameter.elements:
                    items.addTag('item', item)
            elif parameter.typ == 'point':
                if parameter.multiple:
                    logger.warning("multiple points (%r) not yet supported" % parameter.identifier())
                field.addTag(type_ = 'Vector3')
            else:
                logger.warning("Parameter type %r not yet supported (using pass-through String field)"
                                % parameter.typ)
                field.addTag(type_ = 'String')

            fieldDoc.addTag(type_ = field.tag('type').value())

            if parameter.default is not None:
                field.addTag('value', parameter.default)

            if parameter.channel == 'output':
                if not (parameter.isExternalType() or parameter.typ == 'file'):
                    field.addTag(editable = False)
            else:
                autoApplyListener.addTag(listenField = parameterFieldName)

            parametersSection.append(field)
            parametersDoc.append(fieldDoc)

        fieldDoc.addTag(text = parameter.description or "")
        if parameter.typ != "image":
            # copy more parameter properties into the .mhelp file:
            if parameter.label:
                fieldDoc.addTag(title = parameter.label)
            fieldDoc.addTag(visibleInGUI = not parameter.hidden) # FIXME: crude heuristic

            if fieldDoc.tag('type').value() == 'Enum':
                items = fieldDoc.addGroup("items")
                for item in parameter.elements:
                    items.addTag('item', item)

            defaultValue = field.tag('value')
            if defaultValue is not None:
                fieldDoc.addTag(default = defaultValue.value())

        if parameter.constraints:
            if parameter.constraints.minimum is not None:
                field.addTag(min = parameter.constraints.minimum)
            if parameter.constraints.maximum is not None:
                field.addTag(max = parameter.constraints.maximum)

        if parameter.hidden:
            field.addTag(hidden = True)

    if not autoApplyListener:
        commands.remove(autoApplyListener)
    else:
        autoApplyListener.addTag(command = 'updateIfAutoApply')

    if not autoUpdateListener:
        commands.remove(autoUpdateListener)
    else:
        autoUpdateListener.addTag(command = 'updateIfAutoUpdate')

    parametersSection.addGroup('Field', 'retainTemporaryFiles') \
        .addTag(type_ = 'Bool')

    parametersSection.addGroup('Field', 'cliExecutablePath') \
        .addTag(type_ = 'String') \
        .addTag('value', os.path.abspath(cliModule.path)) \
        .addTag(persistent = False)

    parametersSection.addGroup('Field', 'debugCommandline') \
        .addTag(type_ = 'String') \
        .addTag(editable = False)

    parametersSection.addGroup('Field', 'debugStdOut') \
        .addTag(type_ = 'String') \
        .addTag(editable = False)

    parametersSection.addGroup('Field', 'debugStdErr') \
        .addTag(type_ = 'String') \
        .addTag(editable = False)

    if autoUpdateListener:
        parametersSection.addGroup('Field', 'autoUpdate') \
            .addTag(type_ = 'Bool')

    if autoApplyListener:
        parametersSection.addGroup('Field', 'autoApply') \
            .addTag(type_ = 'Bool')

    parametersSection.addGroup('Field', 'update') \
        .addTag(type_ = 'Trigger')

    parametersSection.addGroup('Field', 'runInBackground_WIP') \
        .addTag(type_ = 'Bool')
    parametersDoc.addGroup('Field', 'runInBackground_WIP') \
        .addTag(type_ = 'Bool') \
        .addTag(text = 'Execute asynchroneously; outputs will be touched after execution finished (this API is still work in progress)') \
        .addTag(visibleInGUI = False)

    parametersDoc.addGroup('Field', 'retainTemporaryFiles') \
        .addTag(type_ = 'Bool') \
        .addTag(text = 'Do not delete temporary files after CLI execution') \
        .addTag(title = 'Retain Temporary Files')

    parametersDoc.addGroup('Field', 'cliExecutablePath') \
        .addTag(type_ = 'String') \
        .addTag(text = 'Path of the CLI executable to run (set by CLIImporter)') \
        .addTag(title = 'Executable Path') \
        .addTag(persistent = False)

    parametersDoc.addGroup('Field', 'debugCommandline') \
        .addTag(type_ = 'String') \
        .addTag(text = 'Full commandline used for executing the CLI module.  Actually, this string is composed for debugging; the real execution does not use this exact quoting (but calls a library function that takes arguments within an array).') \
        .addTag(persistent = False)

    parametersDoc.addGroup('Field', 'debugStdOut') \
        .addTag(type_ = 'String') \
        .addTag(text = 'Standard output collected during CLI execution') \
        .addTag(persistent = False)

    parametersDoc.addGroup('Field', 'debugStdErr') \
        .addTag(type_ = 'String') \
        .addTag(text = 'Standard error collected during CLI execution (may be very helpful if the module does not work as expected)') \
        .addTag(persistent = False)

    if autoUpdateListener:
        parametersDoc.addGroup('Field', 'autoUpdate') \
            .addTag(type_ = 'Bool') \
            .addTag(text = 'Automatically execute CLI module whenever any one of the input images changes (may be slow, use carefully)') \
            .addTag(title = 'Auto update') \
            .addTag(visibleInGUI = True)

    if autoApplyListener:
        parametersDoc.addGroup('Field', 'autoApply') \
            .addTag(type_ = 'Bool') \
            .addTag(text = 'Automatically execute CLI module whenever any one of the input parameters changes (may be slow, use carefully)') \
            .addTag(title = 'Auto apply') \
            .addTag(visibleInGUI = True)

    parametersDoc.addGroup('Field', 'update') \
        .addTag(type_ = 'Trigger') \
        .addTag(text = 'Execute the CLI module') \
        .addTag(title = 'Update') \
        .addTag(visibleInGUI = True)

    if inputsSection:
        interface.append(inputsSection)
    if outputsSection:
        interface.append(outputsSection)
    if parametersSection:
        interface.append(parametersSection)

    scriptFile.append(MDLNewline)
    window = scriptFile.addGroup('Window', 'CLI GUI') \
        .addGroup('Category') \
        .addTag(expandY = True)

    main = []
    advanced = []
    for parameters in cliModule:
        box = MDLGroup('Box', parameters.label)
        if parameters.description:
            box.addTag(tooltip = parameters.description)
        for parameter in parameters:
            parameterFieldName = fieldName(parameter)
            if parameter.typ == 'image':
                continue # already exposed is module input/output
            elif parameter.typ in ('file', 'directory') or parameter.isExternalType():
                field = box.addGroup('Field', parameterFieldName)
                if parameter.label:
                    field.addTag(title = parameter.label)
                field.addTag(browseButton = True)
                if parameter.typ == 'directory':
                    field.addTag(browseMode = 'Directory')
                elif parameter.channel == 'output':
                    field.addTag(browseMode = 'Save')
                else:
                    field.addTag(browseMode = 'Open') # default, but be explicit
                if parameter.fileExtensions:
                    field.addTag(browseFilter = "Supported files (%s);;All files (*)"
                                 % " ".join('*%s' % ext for ext in parameter.fileExtensions))
            else:
                field = box.addGroup('Field', parameterFieldName)
            if parameter.constraints:
                if parameter.constraints.step is not None:
                    field.addTag(step = parameter.constraints.step)
        if not countFields(box):
            continue # skip empty boxes (e.g. only image I/O)
        if parameters.advanced:
            advanced.append(box)
        else:
            main.append(box)

    # got (non-empty) groups, distribute over multiple tabs:
    tabs = []
    for boxes, category in ((main, 'Main'),
                            (advanced, 'Advanced')):
        if not boxes:
            continue
        pages = [[]]
        for box in boxes:
            if sum(countFields(box) for box in pages[-1]) > 15:
                pages.append([])
            pages[-1].append(box)

        # assign names to tabs:
        if len(pages) == 1:
            tabs.append((category, pages[0]))
        else:
            for i, page in enumerate(pages):
                tabs.append(('%s %d' % (category, i+1), page))

    if len(tabs) == 1:
        title, page = tabs[0]
        if len(page) == 1:
            window.extend(page[0])
        else:
            window.extend(page)
    else:
        tabView = window.addGroup("TabView")
        for title, page in tabs:
            tab = tabView.addGroup('Category', title)
            if len(page) == 1:
                tab.extend(page[0])
            else:
                tab.extend(page)

    # execution controls
    hori = window.addGroup("Horizontal")
    if autoApplyListener:
        hori.addGroup('CheckBox', 'autoApply')
    if autoUpdateListener:
        hori.addGroup('CheckBox', 'autoUpdate')
    hori.addGroup('Button', 'update')

    # debug Window section
    scriptFile.append(MDLNewline)
    scriptFile.append(MDLInclude('$(LOCAL)/../DebugWindow.script'))

    return defFile, scriptFile, mlabFile, mhelpFile

def cliToMacroModule(executablePath, targetDirectory, defFile = True,
                     includePanelScreenshots = True, env = None,
                     unexpandFilename = None):
    """Write .script/.mlab/.mhelp files for the CLI module `executablePath`
    to `targetDirectory`[/mhelp].  If `defFile` is set to an MLDFile instance,
    the .def file contents are appended to that object, otherwise a
    .def file for that single module gets written."""

    logger.info("processing %s..." % executablePath)
    #ET.dump(elementTree)
    m = CLIModule(executablePath, env = env)
    m.classifyParameters() # performs additional sanity checks

    mdefFile, scriptFile, mlabFile, mhelpFile = mdlDescription(m, includePanelScreenshots)
    if defFile is True:
        mdefFile.write(os.path.join(targetDirectory, "%s.def" % m.name))
    else:
        if defFile: # not empty, add separating newline
            defFile.append(MDLNewline)
        defFile.extend(mdefFile)

    if unexpandFilename is not None:
        cliExecutablePath = scriptFile.group('Interface').group('Parameters').group('Field', 'cliExecutablePath').tag('value')
        cliExecutablePath.tagValue = unexpandFilename(cliExecutablePath.tagValue)

    scriptFile.write(os.path.join(targetDirectory, "%s.script" % m.name))
    mlabFile.write(os.path.join(targetDirectory, "%s.mlab" % m.name))
    mhelpFile.write(os.path.join(targetDirectory, "mhelp", "CLI_%s.mhelp" % m.name))

    return mdefFile

def importAllCLIs(importPaths, targetDirectory, defFileName = 'CLIModules.def',
                  includePanelScreenshots = True, env = None,
                  unexpandFilename = None):
    """Generator function that imports any number of CLI modules at
    once.  `importPaths` shall contain either directory names to be
    scanned (non-recursively) or paths of CLI executables.  Before
    importing, the target directory will be wiped.  All module
    definitions will be put into the same .def file, and all generated
    files will be written to `targetDirectory` and an 'mhelp'
    subdirectory, which must both exist already.  See
    `cliToMacroModule` for more information.  The generator will yield
    (index, total, path) tuples for progress display (index being
    1-based for this purpose)."""

    defFile = MDLFile()

    executablePaths = []

    for path in importPaths:
        if os.path.isdir(path):
            executablePaths.extend(listCLIExecutables(path))
        elif isCLIExecutable(path):
            executablePaths.append(path)

    successful = 0
    total = len(executablePaths)
    for i, path in enumerate(executablePaths):
        yield (i, successful, total, path)
        try:
            cliToMacroModule(path, targetDirectory, defFile,
                             includePanelScreenshots, env = env,
                             unexpandFilename = unexpandFilename)
            successful += 1
        except Exception as e:
            logger.error(str(e))
    yield (total, successful, total, "")

    with open(os.path.join(targetDirectory, defFileName), "w") as f:
        f.write(defFile.mdl())


import numpy as np
import pandas as pd
import pickle

df_train = pd.read_csv('cs-training.csv')
df_train.drop('Unnamed: 0', axis = 1, inplace = True)

df_train.columns = ['target', 'UnsecuredLines', 'age', 'PastDue30-59days', 'DebtRatio', 'MonthlyIncome', 'OpenCredit',
                   'Late_90days', 'RealEstate','PastDue60-89days', 'Dependents']

df_train['MonthlyIncome'].fillna(np.mean(df_train['MonthlyIncome']), inplace = True)
df_train['Dependents'].fillna(df_train['Dependents'].value_counts().argmax(), inplace = True)

from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import precision_score, recall_score, f1_score

features = df_train.columns.tolist()
df_train.drop([features[2], features[4], features[5], features[6], features[8], features[10]], axis = 1, inplace = True)

X_train, X_valid, y_train, y_valid = train_test_split(np.array(df_train[df_train.columns[1:]]),
                                                      np.array(df_train['target']), random_state = 0)

clf = GradientBoostingClassifier(learning_rate = 1, max_depth = 3, n_estimators = 300, random_state = 0)
clf.fit(X_train, y_train)

pickle.dump(clf, open('model.pkl','wb'))

model = pickle.load(open('model.pkl','rb'))
probability = model.predict_proba(np.array([[0.766, 2, 0, 0]]))[:, 1]
print(probability)


import os
import sys
import requests
import json

client_id = "Client ID"
client_secret = "Client Secret"

url = "https://naveropenapi.apigw.ntruss.com/voice/v1/tts"

def main(tts_text, file_name = "input.mp3") :

    datas = {
        "speaker" : "mijin",
        "speed" : "0",
        "text" : tts_text
    }

    headers = {
            "X-NCP-APIGW-API-KEY-ID": client_id,
            "X-NCP-APIGW-API-KEY": client_secret,
            "Content-Type": "application/x-www-form-urlencoded"
    }

    response = requests.post(url, data=datas, headers=headers)

    with open(file_name, 'wb') as f:
        f.write(response.content)

    return file_name

if __name__ == "__main__" :
    file_name = main("안녕하세요 Gcamp")
    os.system("mpg123 {}".format(file_name))


import anpr_wrap as anpr

import sys, os
import cv2

def load_files(path):
	files = [os.path.join(path, f) for f in os.listdir(path)]
	return files

def main():
	files = load_files(sys.argv[1])
	anpr.load_model()

	for f in files:
            print (f)
            img = cv2.imread(f)
            ret = anpr.detect(img)
            print (ret)

if __name__ == "__main__":
	main()


from collections import deque

# 노드의 개수와 간선의 개수를 입력 받기
v = int(input())
# 모든 노드에 대한 진입차수는 0으로 초기화
indegree = [0] * (v + 1)
# 각 노드에 연결된 간선 정보를 담기 위한 연결 리스트 초기화
graph = [[] for i in range(v + 1)]
graph_2 = [[] for i in range(v + 1)]
costs = [0] * (v + 1)
accumulated_costs = [0] * (v + 1)

# 방향 그래프의 모든 간선 정보를 입력 받기
for i in range(v):
    nums = list(map(int, input().split()))
    costs[i+1] = nums[0]
    for j in range(1, len(nums)-1):
        graph[i+1].append(nums[j]) # 정점 A에서 B로 이동 가능
        graph_2[nums[j]].append(i+1)
    # 진입 차수를 1 증가
        indegree[i+1] = len(nums) - 2

print('graph', graph)
print('graph2', graph_2)
print('indegree', indegree)

for i in range(len(costs)):
    accumulated_costs[i] = costs[i]

# def gogo():
#     for i in range(1, v+1):
#         graph[i]

def topology_sort():
    result = [] # 알고리즘 수행 결과를 담을 리스트
    q = deque() # 큐 기능을 위한 deque 라이브러리 사용

    # 처음 시작할 때는 진입차수가 0인 노드를 큐에 삽입
    for i in range(1, v + 1):
        if indegree[i] == 0:
            q.append(i)

    # 큐가 빌 때까지 반복
    while q:
        # 큐에서 원소 꺼내기
        now = q.popleft()
        result.append(now)
        # 해당 원소와 연결된 노드들의 진입차수에서 1 빼기
        for i in graph_2[now]:
            indegree[i] -= 1
            cost = accumulated_costs[now] + costs[i]
            accumulated_costs[i] = max(accumulated_costs[i], cost)
            # 새롭게 진입차수가 0이 되는 노드를 큐에 삽입
            if indegree[i] == 0:
                q.append(i)

    # 위상 정렬을 수행한 결과 출력
    for i in result:
        print(i, end=' ')

topology_sort()

print(costs)
print(accumulated_costs)

# 5
# 10 -1
# 10 1 -1
# 4 1 -1
# 4 3 1 -1
# 3 3 -1


from __future__ import absolute_import
from traits.api import HasTraits, Str
from traitsui.api import View, UItem, Item, VGroup

# ============= standard library imports ========================
# ============= local library imports  ==========================

class DBSaveView(HasTraits):
    name = Str
    note = Str

    def traits_view(self):
        v = View(
            VGroup(
                Item("name"),
                VGroup(UItem("note", style="custom"), show_border=True, label="Note"),
            ),
            title="DB Save",
            buttons=["OK", "Cancel"],
            resizable=True,
            kind="livemodal",
        )
        return v

# ============= EOF =============================================


from pathlib import Path
from typing import Union, Callable

import cv2
import torch
import numpy as np
from sklearn.model_selection import train_test_split

from data.heplers.base_dataset import BaseDataset

class MRIStrokeDataset(BaseDataset):
    """
    Data resides here: /mercurySOFS/Medical/MKDC_stroke_CT_MRI/1stBatchWithMasks
    """

    def __init__(
        self,
        root: Union[str, Path],
        samples_per_epoch: int,
        transforms: Callable,
        is_train: bool,
        patient_names: list,
    ):
        super().__init__(root, samples_per_epoch, transforms, is_train)
        self.paths = []
        for patient_path in self.root.iterdir():
            if patient_path.stem in patient_names:
                self.paths.extend(self.read_patient(patient_path))

    def _len(self):
        return len(self.paths)

    def _getitem(self, index: int) -> dict:
        """Returns a dictionary that contains image, mask and some metadata
        image (tensor) -- an image in the input domain
        mask (tensor) -- corresponding mask
        """
        img_path, mask_path = self.paths[index]
        image = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE)[..., np.newaxis]
        mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE)
        if mask.max() == 255:
            mask = mask / 255

        sample = self.transforms(image=image, mask=mask)
        image = sample["image"].type(torch.float)
        mask = sample["mask"].type(torch.int64)

        return {"image": image, "mask": mask}

    @staticmethod
    def prepare_data(dataset_cfg=None, root=None) -> dict:
        """Read train/validation split
        Returns:
            a dictionary of data that will be used for creation of dataset and dataloader
        """
        root = root if dataset_cfg is None else dataset_cfg.root
        root = Path(root)
        dirnames = [p.stem for p in root.iterdir() if not p.stem.startswith(".")]

        train_filenames, valid_filenames = train_test_split(dirnames, random_state=42)

        result = dict(
            train={"patient_names": train_filenames},
            valid={"patient_names": valid_filenames},
        )
        return result

    @staticmethod
    def read_patient(patient_path):
        mask_dir = patient_path / "masks"
        img_dir = next(patient_path.glob("*DWI*"))
        filenames = mask_dir.glob("*.png")

        ret = []
        for name in filenames:
            img_path = img_dir / name.name
            mask_path = name
            ret += [(img_path, mask_path)]

        return ret


#!/usr/bin/python3
"""
Script takes in a URL, sends a request to the URL
displays the body of the response
"""
import requests
from sys import argv

if __name__ == "__main__":
    url = argv[1]
    r = requests.get(url)
    code = r.status_code

    if code >= 400:
        print("Error code: {}".format(code))
    else:
        print(r.text)


from typing import Any

from app.db_crud import feature_db
from app.deps import get_async_session
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

router = APIRouter()

@router.get(
    "",
)
async def get_features(
    name: str | None = None,
    session: AsyncSession = Depends(get_async_session),
) -> Any:
    """
    Список симптомов с фильтрацией
    """
    features = await feature_db.filter(session, name=name)
    resp = []
    for feature in features:
        resp.append(feature.name)
    return resp


import math
from collections import defaultdict

import nltk
import torch
from torch import nn, optim
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
from nltk.corpus import treebank

nltk.download('treebank')

class Vocab:
    def __init__(self,tokens = None):
        # 使用列表存储所有的标记，从而可根据索引值获取相应的标记
        self.idx_to_token = list()
        # 使用字典实现标记到索引值的映射
        self.token_to_idx = dict()

        if tokens is not None:
            if "<unk>" not in tokens:
                tokens = tokens + ["<unk>"]
            for token in tokens:
                self.idx_to_token.append(token)
                self.token_to_idx[token] = len(self.idx_to_token) - 1

            self.unk = self.token_to_idx["<unk>"]

    # 创建词表，text包含若干句子，每个句子由若干标记构成
    @classmethod
    def build(cls,text,min_freq = 1 , reserved_tokens = None):
        # 存储标记及其出现次数的映射字典
        token_freqs = defaultdict(int)
        # 无重复地进行标记
        for sentence in text:
            for token in sentence:
                token_freqs[token] += 1

        # 用户自定义的预留标记
        uniq_tokens = ["<unk>"] + (reserved_tokens if reserved_tokens else [])
        uniq_tokens += [token for token,freq in token_freqs.items() if freq >= min_freq and token != "<unk>"]

        return cls(uniq_tokens)

    # 返回词表的大小，即词表中有多少个互不相同的标记
    def __len__(self):
        return len(self.idx_to_token)

    # 查找输入标记对应的索引值
    def __getitem__(self, token):
        return self.token_to_idx.get(token,self.unk)

    # 查找一系列输入标记对应的索引值
    def convert_tokens_to_ids(self,tokens):
        return [self[token] for token in tokens]

    # 查找一系列索引值对应的标记
    def convert_ids_to_tokens(self,indices):
        return [self.idx_to_token[index] for index in indices]

# 根据批次中每个序列长度生成Mask矩阵，以便处理长度不一致的序列，忽略掉比较短的序列的无效部分
def length_to_mask(lengths):
    max_len = torch.max(lengths)
    mask = torch.arange(max_len).expand(lengths.shape[0], max_len) < lengths.unsqueeze(1)
    return mask

# 创建存储数据的TransformerDataset的子类 → Transformer
class TransformerDataset(Dataset):
    def __init__(self,data):
        self.data = data
    def __len__(self):
        return len(self.data)
    def __getitem__(self, i):
        return self.data[i]

# 数据处理
def collate_fn(examples):
    lengths = torch.tensor([len(ex[0]) for ex in examples])
    inputs = [torch.tensor(ex[0]) for ex in examples]
    targets = [torch.tensor(ex[1]) for ex in examples]
    # 对batch内的样本进行padding，使其具有相同长度
    inputs = pad_sequence(inputs,batch_first=True,padding_value=vocab["<pad>"])
    targets = pad_sequence(targets,batch_first=True,padding_value=vocab["<pad>"])
    return inputs , lengths , targets , inputs != vocab["<pad>"]

## 位置编码
class PositionalEncoding(nn.Module):
    def __init__(self,d_model,dropout = 0.1,max_len = 512):
        super(PositionalEncoding, self).__init__()

        pe = torch.zeros(max_len,d_model)
        position = torch.arange(0 , max_len , dtype= torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0 , d_model ,2).float() * (-math.log(10000.0) / d_model))

        pe[:,0::2] = torch.sin(position * div_term)
        pe[:,1::2] = torch.cos(position * div_term)

        pe = pe.unsqueeze(0).transpose(0,1)
        self.register_buffer("pe",pe)

    def forward(self,x):
        x = x + self.pe[:x.size(0),:]
        return x

## 模型
class Transformer(nn.Module):
    def __init__(self,vocab_size,embedding_dim,hidden_dim,num_class,dim_feedforward = 512,num_head = 2,num_layers = 2,dropout=0.1,max_len = 512,activation:str = "relu"):
        super(Transformer, self).__init__()
        # 词嵌入层
        self.embedding_dim = embedding_dim
        self.embeddings = nn.Embedding(vocab_size,embedding_dim)
        self.position_embedding = PositionalEncoding(embedding_dim,dropout,max_len)
        # 编码层
        encoder_layer = nn.TransformerEncoderLayer(hidden_dim,num_head,dim_feedforward,dropout,activation)
        self.transformer = nn.TransformerEncoder(encoder_layer,num_layers)
        # 输出层
        self.output = nn.Linear(hidden_dim,num_class)

    def forward(self,inputs,lengths):
        inputs = torch.transpose(inputs,0,1)
        hidden_states = self.embeddings(inputs)
        hidden_states = self.position_embedding(hidden_states)
        attention_mask = length_to_mask(lengths) == False
        hidden_states = self.transformer(hidden_states,src_key_padding_mask = attention_mask).transpose(0,1)
        logits = self.output(hidden_states)
        log_probs = torch.log_softmax(logits,dim = -1)
        return log_probs

# 设置超参数
embedding_dim = 128
hidden_dim = 128
batch_size = 32
num_epoch = 5

# 加载数据
def load_treebank():
    sents, postags = zip(*(zip(*sent) for sent in treebank.tagged_sents()))

    vocab = Vocab.build(sents, reserved_tokens=["<pad>"])

    tag_vocab = Vocab.build(postags)

    train_data = [(vocab.convert_tokens_to_ids(sentence), tag_vocab.convert_tokens_to_ids(tags)) for sentence, tags in zip(sents[:3000], postags[:3000])]
    test_data = [(vocab.convert_tokens_to_ids(sentence), tag_vocab.convert_tokens_to_ids(tags)) for sentence, tags in zip(sents[3000:], postags[3000:])]

    return train_data, test_data, vocab, tag_vocab

train_data , test_data , vocab ,pos_vocab = load_treebank()
train_dataset = TransformerDataset(train_data)
test_dataset = TransformerDataset(test_data)
train_data_loader = DataLoader(train_dataset,batch_size = batch_size,collate_fn=collate_fn,shuffle=True)
test_data_loader = DataLoader(test_dataset,batch_size = 1,collate_fn=collate_fn,shuffle=False)

num_class = len(pos_vocab)

# 加载模型
device = torch.device("cpu")
model = Transformer(len(vocab),embedding_dim,hidden_dim,num_class)
model.to(device)

# 训练过程
nll_loss = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(),lr=0.001)

model.train()
for epoch in range(num_epoch):
    total_loss = 0
    for batch in tqdm(train_data_loader,desc=f"Training Epoch{epoch}"):
        inputs , lengths , targets , mask = [x.to(device) for x in batch]
        log_probs = model(inputs,lengths)
        loss = nll_loss(log_probs[mask],targets[mask])

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total_loss += loss.item()
    print(f"Loss:{total_loss:.2f}")

# 测试过程
acc = 0
total = 0
for batch in tqdm(test_data_loader,desc=f"Testing"):
    inputs , lengths , targets , mask = [x.to(device) for x in batch]
    with torch.no_grad():
        output = model(inputs,lengths)
        acc += (output.argmax(dim = -1) == targets)[mask].sum().item()
        total += mask.sum().item()

# 输出在测试集上的准确率
print(f"Acc:{acc / total:.2f}")


# Enter your code here. Read input from STDIN. Print output to STDOUT
import itertools

first_line = input().split()
all_lists = []

for i in range(int(first_line[0])):
    new_list = [int(i) for i in input().split()][1:]
    all_lists.append(new_list)

combinations = list(itertools.product(*all_lists))
Result = []
for i in combinations:
    result1 = sum(map(lambda x:x**2, [a for a in i]))
    result2 = result1 % int(first_line[1])
    Result.append(result2)

print(max(Result))


# rest_framework
from rest_framework import viewsets, views
from rest_framework.response import Response
from rest_framework import status

# local DJango
from .serializers import PersonSerializer, SearchSerializer
from .models import Person
from .utilities import find_time_slots

class PersonViewset(viewsets.ModelViewSet):
    """Viewset for candidate"""
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

class SearchViewset(views.APIView):

    def post(self, request, format=None):
        serializer = SearchSerializer(data=request.data)

        if serializer.is_valid():

            try:
                candidate = Person.objects.get(pk=serializer.data["candidate_id"])
                interviewer = Person.objects.get(pk=serializer.data["interviewer_id"])
            except Person.DoesNotExist as error:
                return Response(data={"detail": f"{error}"}, status=status.HTTP_404_NOT_FOUND)

            if candidate.available_on != interviewer.available_on:
                return Response({"detail": f"Not available on {interviewer.available_on}"})

            date = candidate.available_on
            candidate_timing = (candidate.available_from, candidate.available_to)
            interviewer_timing = (interviewer.available_from, interviewer.available_to)

            proper_timing = find_time_slots(date, candidate_timing, interviewer_timing)

            return Response(proper_timing, status=status.HTTP_200_OK)

        return Response({"detail": f"Not time slots available"}, status=status.HTTP_404_NOT_FOUND)


from io import BytesIO

import qrcode
import telegram
from telegram import Update, InputMedia
from telegram.ext import ContextTypes

from ticket_bot import config
from ticket_bot.handlers.keyboards import get_my_tickets_keyboard
from ticket_bot.handlers.response import send_text_response, send_photo_response
from ticket_bot.services.ticket_service import get_user_tickets_db
from ticket_bot.templates.strings import Strings as s
from ticket_bot.templates.templates import render_template

async def show_my_tickets_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user_tickets = await get_user_tickets_db(update.effective_user.id)
    if len(user_tickets) == 0:
        await send_text_response(update, context, response=s.NO_TICKETS_HERE)
        return
    ticket = user_tickets[0]
    if ticket.qr_id is None:
        bytes_io = BytesIO()
        img = qrcode.make(ticket.code)
        img.save(bytes_io)
        bytes_io.seek(0)
        qr = bytes_io
    else:
        qr = ticket.qr_id
    if len(user_tickets) == 1:
        await send_photo_response(update, context,
                                  response=render_template("ticket.j2", {"t": ticket}),
                                  photo=qr)
    else:
        await send_photo_response(update, context,
                                  response=render_template("ticket.j2", {"t": ticket}),
                                  photo=qr,
                                  keyboard=get_my_tickets_keyboard(
                                      current_ticket_index=0,
                                      tickets_count=len(user_tickets),
                                      callback_prefix=config.SELECT_TICKET_CALLBACK_PATTERN
                                  ))

async def all_my_tickets_button(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    if not query.data or not query.data.strip():
        return
    user_tickets = await get_user_tickets_db(update.effective_user.id)
    current_ticket_index = _get_current_ticket_index(query.data)
    ticket = user_tickets[current_ticket_index]
    if ticket.qr_id is None:
        bytes_io = BytesIO()
        img = qrcode.make(ticket.code)
        img.save(bytes_io)
        bytes_io.seek(0)
        qr = bytes_io
    else:
        qr = ticket.qr_id
    await query.edit_message_media(media=InputMedia('photo', qr,
                                                    caption=render_template("ticket.j2", {"t": ticket}),
                                                    parse_mode=telegram.constants.ParseMode.HTML),
                                   reply_markup=get_my_tickets_keyboard(
                                       current_ticket_index=current_ticket_index,
                                       tickets_count=len(user_tickets),
                                       callback_prefix=config.SELECT_TICKET_CALLBACK_PATTERN,
                                   ))

def _get_current_ticket_index(query_data) -> int:
    pattern_prefix_length = len(config.SELECT_TICKET_CALLBACK_PATTERN)
    return int(query_data[pattern_prefix_length:])